X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning-invoice%2Fsrc%2Futils.rs;h=11a779b1028a8ddceb825cc833cceb57856d52f0;hb=0188861585db577723c4adedc43acd0f975944a5;hp=15ff9d6f47f04972ac77b188bd23c6a10acfb469;hpb=3f9868f2350db93e2f5256aee2112ccabf1b531a;p=rust-lightning diff --git a/lightning-invoice/src/utils.rs b/lightning-invoice/src/utils.rs index 15ff9d6f..11a779b1 100644 --- a/lightning-invoice/src/utils.rs +++ b/lightning-invoice/src/utils.rs @@ -1,30 +1,24 @@ //! Convenient utilities to create an invoice. use crate::{CreationError, Currency, Invoice, InvoiceBuilder, SignOrCreationError}; -use crate::payment::Payer; use crate::{prelude::*, Description, InvoiceDescription, Sha256}; use bech32::ToBase32; -use bitcoin_hashes::{Hash, sha256}; +use bitcoin_hashes::Hash; use lightning::chain; use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator}; -use lightning::chain::keysinterface::{Recipient, KeysInterface}; -use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret}; -use lightning::ln::channelmanager::{ChannelDetails, ChannelManager, PaymentId, PaymentSendFailure, MIN_FINAL_CLTV_EXPIRY}; -#[cfg(feature = "std")] +use lightning::chain::keysinterface::{Recipient, NodeSigner, SignerProvider, EntropySource}; +use lightning::ln::{PaymentHash, PaymentSecret}; +use lightning::ln::channelmanager::{ChannelDetails, ChannelManager, MIN_FINAL_CLTV_EXPIRY_DELTA}; use lightning::ln::channelmanager::{PhantomRouteHints, MIN_CLTV_EXPIRY_DELTA}; use lightning::ln::inbound_payment::{create, create_from_hash, ExpandedKey}; -use lightning::ln::msgs::LightningError; -use lightning::routing::gossip::{NetworkGraph, RoutingFees}; -use lightning::routing::router::{InFlightHtlcs, Route, RouteHint, RouteHintHop, RouteParameters, find_route, RouteHop, Router, ScorerAccountingForInFlightHtlcs}; -use lightning::routing::scoring::{LockableScore, Score}; +use lightning::routing::gossip::RoutingFees; +use lightning::routing::router::{RouteHint, RouteHintHop, Router}; use lightning::util::logger::Logger; use secp256k1::PublicKey; use core::ops::Deref; use core::time::Duration; -use crate::sync::Mutex; -#[cfg(feature = "std")] /// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice." /// See [`PhantomKeysManager`] for more information on phantom node payments. /// @@ -44,8 +38,15 @@ use crate::sync::Mutex; /// /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for /// in excess of the current time. +/// +/// `duration_since_epoch` is the current time since epoch in seconds. +/// +/// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to +/// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`] - 3. +/// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block +/// confirmations during routing. /// -/// Note that the provided `keys_manager`'s `KeysInterface` implementation must support phantom +/// Note that the provided `keys_manager`'s `NodeSigner` implementation must support phantom /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this /// requirement). /// @@ -54,24 +55,28 @@ use crate::sync::Mutex; /// [`ChannelManager::create_inbound_payment`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment /// [`ChannelManager::create_inbound_payment_for_hash`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash /// [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels -pub fn create_phantom_invoice( +/// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA +/// +/// This can be used in a `no_std` environment, where [`std::time::SystemTime`] is not +/// available and the current time is supplied by the caller. +pub fn create_phantom_invoice( amt_msat: Option, payment_hash: Option, description: String, - invoice_expiry_delta_secs: u32, phantom_route_hints: Vec, keys_manager: K, - logger: L, network: Currency, + invoice_expiry_delta_secs: u32, phantom_route_hints: Vec, entropy_source: ES, + node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option, duration_since_epoch: Duration, ) -> Result> where - K::Target: KeysInterface, + ES::Target: EntropySource, + NS::Target: NodeSigner, L::Target: Logger, { let description = Description::new(description).map_err(SignOrCreationError::CreationError)?; let description = InvoiceDescription::Direct(&description,); - _create_phantom_invoice::( + _create_phantom_invoice::( amt_msat, payment_hash, description, invoice_expiry_delta_secs, phantom_route_hints, - keys_manager, logger, network, + entropy_source, node_signer, logger, network, min_final_cltv_expiry_delta, duration_since_epoch, ) } -#[cfg(feature = "std")] /// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice." /// See [`PhantomKeysManager`] for more information on phantom node payments. /// @@ -93,8 +98,10 @@ where /// /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for /// in excess of the current time. +/// +/// `duration_since_epoch` is the current time since epoch in seconds. /// -/// Note that the provided `keys_manager`'s `KeysInterface` implementation must support phantom +/// Note that the provided `keys_manager`'s `NodeSigner` implementation must support phantom /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this /// requirement). /// @@ -103,32 +110,36 @@ where /// [`ChannelManager::create_inbound_payment`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment /// [`ChannelManager::create_inbound_payment_for_hash`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash /// [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels -pub fn create_phantom_invoice_with_description_hash( +/// +/// This can be used in a `no_std` environment, where [`std::time::SystemTime`] is not +/// available and the current time is supplied by the caller. +pub fn create_phantom_invoice_with_description_hash( amt_msat: Option, payment_hash: Option, invoice_expiry_delta_secs: u32, - description_hash: Sha256, phantom_route_hints: Vec, keys_manager: K, - logger: L, network: Currency + description_hash: Sha256, phantom_route_hints: Vec, entropy_source: ES, + node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option, duration_since_epoch: Duration, ) -> Result> where - K::Target: KeysInterface, + ES::Target: EntropySource, + NS::Target: NodeSigner, L::Target: Logger, { - _create_phantom_invoice::( + _create_phantom_invoice::( amt_msat, payment_hash, InvoiceDescription::Hash(&description_hash), - invoice_expiry_delta_secs, phantom_route_hints, keys_manager, logger, network, + invoice_expiry_delta_secs, phantom_route_hints, entropy_source, node_signer, logger, network, + min_final_cltv_expiry_delta, duration_since_epoch, ) } -#[cfg(feature = "std")] -fn _create_phantom_invoice( +fn _create_phantom_invoice( amt_msat: Option, payment_hash: Option, description: InvoiceDescription, - invoice_expiry_delta_secs: u32, phantom_route_hints: Vec, keys_manager: K, - logger: L, network: Currency, + invoice_expiry_delta_secs: u32, phantom_route_hints: Vec, entropy_source: ES, + node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option, duration_since_epoch: Duration, ) -> Result> where - K::Target: KeysInterface, + ES::Target: EntropySource, + NS::Target: NodeSigner, L::Target: Logger, { - use std::time::{SystemTime, UNIX_EPOCH}; if phantom_route_hints.len() == 0 { return Err(SignOrCreationError::CreationError( @@ -136,6 +147,10 @@ where )); } + if min_final_cltv_expiry_delta.is_some() && min_final_cltv_expiry_delta.unwrap().saturating_add(3) < MIN_FINAL_CLTV_EXPIRY_DELTA { + return Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort)); + } + let invoice = match description { InvoiceDescription::Direct(description) => { InvoiceBuilder::new(network).description(description.0.clone()) @@ -144,17 +159,16 @@ where }; // If we ever see performance here being too slow then we should probably take this ExpandedKey as a parameter instead. - let keys = ExpandedKey::new(&keys_manager.get_inbound_payment_key_material()); + let keys = ExpandedKey::new(&node_signer.get_inbound_payment_key_material()); let (payment_hash, payment_secret) = if let Some(payment_hash) = payment_hash { let payment_secret = create_from_hash( &keys, amt_msat, payment_hash, invoice_expiry_delta_secs, - SystemTime::now() - .duration_since(UNIX_EPOCH) - .expect("Time must be > 1970") + duration_since_epoch .as_secs(), + min_final_cltv_expiry_delta, ) .map_err(|_| SignOrCreationError::CreationError(CreationError::InvalidAmount))?; (payment_hash, payment_secret) @@ -163,11 +177,10 @@ where &keys, amt_msat, invoice_expiry_delta_secs, - &keys_manager, - SystemTime::now() - .duration_since(UNIX_EPOCH) - .expect("Time must be > 1970") + &entropy_source, + duration_since_epoch .as_secs(), + min_final_cltv_expiry_delta, ) .map_err(|_| SignOrCreationError::CreationError(CreationError::InvalidAmount))? }; @@ -176,10 +189,12 @@ where phantom_route_hints.len(), log_bytes!(payment_hash.0)); let mut invoice = invoice - .current_timestamp() + .duration_since_epoch(duration_since_epoch) .payment_hash(Hash::from_slice(&payment_hash.0).unwrap()) .payment_secret(payment_secret) - .min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into()) + .min_final_cltv_expiry_delta( + // Add a buffer of 3 to the delta if present, otherwise use LDK's minimum. + min_final_cltv_expiry_delta.map(|x| x.saturating_add(3)).unwrap_or(MIN_FINAL_CLTV_EXPIRY_DELTA).into()) .expiry_time(Duration::from_secs(invoice_expiry_delta_secs.into())); if let Some(amt) = amt_msat { invoice = invoice.amount_milli_satoshis(amt); @@ -219,7 +234,7 @@ where let hrp_str = raw_invoice.hrp.to_string(); let hrp_bytes = hrp_str.as_bytes(); let data_without_signature = raw_invoice.data.to_base32(); - let signed_raw_invoice = raw_invoice.sign(|_| keys_manager.sign_invoice(hrp_bytes, &data_without_signature, Recipient::PhantomNode)); + let signed_raw_invoice = raw_invoice.sign(|_| node_signer.sign_invoice(hrp_bytes, &data_without_signature, Recipient::PhantomNode)); match signed_raw_invoice { Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()), Err(e) => Err(SignOrCreationError::SignError(e)) @@ -235,23 +250,34 @@ where /// /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for /// in excess of the current time. -pub fn create_invoice_from_channelmanager( - channelmanager: &ChannelManager, keys_manager: K, logger: L, - network: Currency, amt_msat: Option, description: String, invoice_expiry_delta_secs: u32 +/// +/// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to +/// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. +/// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block +/// confirmations during routing. +/// +/// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA +pub fn create_invoice_from_channelmanager( + channelmanager: &ChannelManager, node_signer: NS, logger: L, + network: Currency, amt_msat: Option, description: String, invoice_expiry_delta_secs: u32, + min_final_cltv_expiry_delta: Option, ) -> Result> where - M::Target: chain::Watch<::Signer>, + M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + ES::Target: EntropySource, + NS::Target: NodeSigner, + SP::Target: SignerProvider, F::Target: FeeEstimator, + R::Target: Router, L::Target: Logger, { use std::time::SystemTime; let duration = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) .expect("for the foreseeable future this shouldn't happen"); create_invoice_from_channelmanager_and_duration_since_epoch( - channelmanager, keys_manager, logger, network, amt_msat, description, duration, - invoice_expiry_delta_secs + channelmanager, node_signer, logger, network, amt_msat, + description, duration, invoice_expiry_delta_secs, min_final_cltv_expiry_delta, ) } @@ -265,16 +291,26 @@ where /// /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for /// in excess of the current time. -pub fn create_invoice_from_channelmanager_with_description_hash( - channelmanager: &ChannelManager, keys_manager: K, logger: L, +/// +/// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to +/// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. +/// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block +/// confirmations during routing. +/// +/// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA +pub fn create_invoice_from_channelmanager_with_description_hash( + channelmanager: &ChannelManager, node_signer: NS, logger: L, network: Currency, amt_msat: Option, description_hash: Sha256, - invoice_expiry_delta_secs: u32 + invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option, ) -> Result> where - M::Target: chain::Watch<::Signer>, + M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + ES::Target: EntropySource, + NS::Target: NodeSigner, + SP::Target: SignerProvider, F::Target: FeeEstimator, + R::Target: Router, L::Target: Logger, { use std::time::SystemTime; @@ -284,77 +320,148 @@ where .expect("for the foreseeable future this shouldn't happen"); create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch( - channelmanager, keys_manager, logger, network, amt_msat, - description_hash, duration, invoice_expiry_delta_secs + channelmanager, node_signer, logger, network, amt_msat, + description_hash, duration, invoice_expiry_delta_secs, min_final_cltv_expiry_delta, ) } /// See [`create_invoice_from_channelmanager_with_description_hash`] /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not /// available and the current time is supplied by the caller. -pub fn create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch( - channelmanager: &ChannelManager, keys_manager: K, logger: L, +pub fn create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch( + channelmanager: &ChannelManager, node_signer: NS, logger: L, network: Currency, amt_msat: Option, description_hash: Sha256, - duration_since_epoch: Duration, invoice_expiry_delta_secs: u32 + duration_since_epoch: Duration, invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option, ) -> Result> -where - M::Target: chain::Watch<::Signer>, - T::Target: BroadcasterInterface, - K::Target: KeysInterface, - F::Target: FeeEstimator, - L::Target: Logger, + where + M::Target: chain::Watch<::Signer>, + T::Target: BroadcasterInterface, + ES::Target: EntropySource, + NS::Target: NodeSigner, + SP::Target: SignerProvider, + F::Target: FeeEstimator, + R::Target: Router, + L::Target: Logger, { _create_invoice_from_channelmanager_and_duration_since_epoch( - channelmanager, keys_manager, logger, network, amt_msat, + channelmanager, node_signer, logger, network, amt_msat, InvoiceDescription::Hash(&description_hash), - duration_since_epoch, invoice_expiry_delta_secs + duration_since_epoch, invoice_expiry_delta_secs, min_final_cltv_expiry_delta, ) } /// See [`create_invoice_from_channelmanager`] /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not /// available and the current time is supplied by the caller. -pub fn create_invoice_from_channelmanager_and_duration_since_epoch( - channelmanager: &ChannelManager, keys_manager: K, logger: L, +pub fn create_invoice_from_channelmanager_and_duration_since_epoch( + channelmanager: &ChannelManager, node_signer: NS, logger: L, network: Currency, amt_msat: Option, description: String, duration_since_epoch: Duration, - invoice_expiry_delta_secs: u32 + invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option, ) -> Result> -where - M::Target: chain::Watch<::Signer>, - T::Target: BroadcasterInterface, - K::Target: KeysInterface, - F::Target: FeeEstimator, - L::Target: Logger, + where + M::Target: chain::Watch<::Signer>, + T::Target: BroadcasterInterface, + ES::Target: EntropySource, + NS::Target: NodeSigner, + SP::Target: SignerProvider, + F::Target: FeeEstimator, + R::Target: Router, + L::Target: Logger, { _create_invoice_from_channelmanager_and_duration_since_epoch( - channelmanager, keys_manager, logger, network, amt_msat, + channelmanager, node_signer, logger, network, amt_msat, InvoiceDescription::Direct( &Description::new(description).map_err(SignOrCreationError::CreationError)?, ), - duration_since_epoch, invoice_expiry_delta_secs + duration_since_epoch, invoice_expiry_delta_secs, min_final_cltv_expiry_delta, ) } -fn _create_invoice_from_channelmanager_and_duration_since_epoch( - channelmanager: &ChannelManager, keys_manager: K, logger: L, +fn _create_invoice_from_channelmanager_and_duration_since_epoch( + channelmanager: &ChannelManager, node_signer: NS, logger: L, network: Currency, amt_msat: Option, description: InvoiceDescription, - duration_since_epoch: Duration, invoice_expiry_delta_secs: u32 + duration_since_epoch: Duration, invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option, ) -> Result> -where - M::Target: chain::Watch<::Signer>, - T::Target: BroadcasterInterface, - K::Target: KeysInterface, - F::Target: FeeEstimator, - L::Target: Logger, + where + M::Target: chain::Watch<::Signer>, + T::Target: BroadcasterInterface, + ES::Target: EntropySource, + NS::Target: NodeSigner, + SP::Target: SignerProvider, + F::Target: FeeEstimator, + R::Target: Router, + L::Target: Logger, { + if min_final_cltv_expiry_delta.is_some() && min_final_cltv_expiry_delta.unwrap().saturating_add(3) < MIN_FINAL_CLTV_EXPIRY_DELTA { + return Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort)); + } + // `create_inbound_payment` only returns an error if the amount is greater than the total bitcoin // supply. let (payment_hash, payment_secret) = channelmanager - .create_inbound_payment(amt_msat, invoice_expiry_delta_secs) + .create_inbound_payment(amt_msat, invoice_expiry_delta_secs, min_final_cltv_expiry_delta) .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?; + _create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash( + channelmanager, node_signer, logger, network, amt_msat, description, duration_since_epoch, + invoice_expiry_delta_secs, payment_hash, payment_secret, min_final_cltv_expiry_delta) +} + +/// See [`create_invoice_from_channelmanager_and_duration_since_epoch`] +/// This version allows for providing a custom [`PaymentHash`] for the invoice. +/// This may be useful if you're building an on-chain swap or involving another protocol where +/// the payment hash is also involved outside the scope of lightning. +pub fn create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash( + channelmanager: &ChannelManager, node_signer: NS, logger: L, + network: Currency, amt_msat: Option, description: String, duration_since_epoch: Duration, + invoice_expiry_delta_secs: u32, payment_hash: PaymentHash, min_final_cltv_expiry_delta: Option, +) -> Result> + where + M::Target: chain::Watch<::Signer>, + T::Target: BroadcasterInterface, + ES::Target: EntropySource, + NS::Target: NodeSigner, + SP::Target: SignerProvider, + F::Target: FeeEstimator, + R::Target: Router, + L::Target: Logger, +{ + let payment_secret = channelmanager + .create_inbound_payment_for_hash(payment_hash, amt_msat, invoice_expiry_delta_secs, + min_final_cltv_expiry_delta) + .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?; + _create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash( + channelmanager, node_signer, logger, network, amt_msat, + InvoiceDescription::Direct( + &Description::new(description).map_err(SignOrCreationError::CreationError)?, + ), + duration_since_epoch, invoice_expiry_delta_secs, payment_hash, payment_secret, + min_final_cltv_expiry_delta, + ) +} + +fn _create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash( + channelmanager: &ChannelManager, node_signer: NS, logger: L, + network: Currency, amt_msat: Option, description: InvoiceDescription, duration_since_epoch: Duration, + invoice_expiry_delta_secs: u32, payment_hash: PaymentHash, payment_secret: PaymentSecret, + min_final_cltv_expiry_delta: Option, +) -> Result> + where + M::Target: chain::Watch<::Signer>, + T::Target: BroadcasterInterface, + ES::Target: EntropySource, + NS::Target: NodeSigner, + SP::Target: SignerProvider, + F::Target: FeeEstimator, + R::Target: Router, + L::Target: Logger, +{ let our_node_pubkey = channelmanager.get_our_node_id(); let channels = channelmanager.list_channels(); + if min_final_cltv_expiry_delta.is_some() && min_final_cltv_expiry_delta.unwrap().saturating_add(3) < MIN_FINAL_CLTV_EXPIRY_DELTA { + return Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort)); + } + log_trace!(logger, "Creating invoice with payment hash {}", log_bytes!(payment_hash.0)); let invoice = match description { @@ -370,7 +477,9 @@ where .payment_hash(Hash::from_slice(&payment_hash.0).unwrap()) .payment_secret(payment_secret) .basic_mpp() - .min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into()) + .min_final_cltv_expiry_delta( + // Add a buffer of 3 to the delta if present, otherwise use LDK's minimum. + min_final_cltv_expiry_delta.map(|x| x.saturating_add(3)).unwrap_or(MIN_FINAL_CLTV_EXPIRY_DELTA).into()) .expiry_time(Duration::from_secs(invoice_expiry_delta_secs.into())); if let Some(amt) = amt_msat { invoice = invoice.amount_milli_satoshis(amt); @@ -388,7 +497,7 @@ where let hrp_str = raw_invoice.hrp.to_string(); let hrp_bytes = hrp_str.as_bytes(); let data_without_signature = raw_invoice.data.to_base32(); - let signed_raw_invoice = raw_invoice.sign(|_| keys_manager.sign_invoice(hrp_bytes, &data_without_signature, Recipient::Node)); + let signed_raw_invoice = raw_invoice.sign(|_| node_signer.sign_invoice(hrp_bytes, &data_without_signature, Recipient::Node)); match signed_raw_invoice { Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()), Err(e) => Err(SignOrCreationError::SignError(e)) @@ -524,125 +633,21 @@ fn filter_channels( .collect::>() } -/// A [`Router`] implemented using [`find_route`]. -pub struct DefaultRouter>, L: Deref, S: Deref> where - L::Target: Logger, - S::Target: for <'a> LockableScore<'a>, -{ - network_graph: G, - logger: L, - random_seed_bytes: Mutex<[u8; 32]>, - scorer: S -} - -impl>, L: Deref, S: Deref> DefaultRouter where - L::Target: Logger, - S::Target: for <'a> LockableScore<'a>, -{ - /// Creates a new router using the given [`NetworkGraph`], a [`Logger`], and a randomness source - /// `random_seed_bytes`. - pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32], scorer: S) -> Self { - let random_seed_bytes = Mutex::new(random_seed_bytes); - Self { network_graph, logger, random_seed_bytes, scorer } - } -} - -impl>, L: Deref, S: Deref> Router for DefaultRouter where - L::Target: Logger, - S::Target: for <'a> LockableScore<'a>, -{ - fn find_route( - &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&ChannelDetails]>, - inflight_htlcs: InFlightHtlcs - ) -> Result { - let random_seed_bytes = { - let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap(); - *locked_random_seed_bytes = sha256::Hash::hash(&*locked_random_seed_bytes).into_inner(); - *locked_random_seed_bytes - }; - - find_route( - payer, params, &self.network_graph, first_hops, &*self.logger, - &ScorerAccountingForInFlightHtlcs::new(&mut self.scorer.lock(), inflight_htlcs), - &random_seed_bytes - ) - } - - fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) { - self.scorer.lock().payment_path_failed(path, short_channel_id); - } - - fn notify_payment_path_successful(&self, path: &[&RouteHop]) { - self.scorer.lock().payment_path_successful(path); - } - - fn notify_payment_probe_successful(&self, path: &[&RouteHop]) { - self.scorer.lock().probe_successful(path); - } - - fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) { - self.scorer.lock().probe_failed(path, short_channel_id); - } -} - -impl Payer for ChannelManager -where - M::Target: chain::Watch<::Signer>, - T::Target: BroadcasterInterface, - K::Target: KeysInterface, - F::Target: FeeEstimator, - L::Target: Logger, -{ - fn node_id(&self) -> PublicKey { - self.get_our_node_id() - } - - fn first_hops(&self) -> Vec { - self.list_usable_channels() - } - - fn send_payment( - &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option, - payment_id: PaymentId - ) -> Result<(), PaymentSendFailure> { - self.send_payment(route, payment_hash, payment_secret, payment_id) - } - - fn send_spontaneous_payment( - &self, route: &Route, payment_preimage: PaymentPreimage, payment_id: PaymentId, - ) -> Result<(), PaymentSendFailure> { - self.send_spontaneous_payment(route, Some(payment_preimage), payment_id).map(|_| ()) - } - - fn retry_payment( - &self, route: &Route, payment_id: PaymentId - ) -> Result<(), PaymentSendFailure> { - self.retry_payment(route, payment_id) - } - - fn abandon_payment(&self, payment_id: PaymentId) { - self.abandon_payment(payment_id) - } - - fn inflight_htlcs(&self) -> InFlightHtlcs { self.compute_inflight_htlcs() } -} - #[cfg(test)] mod test { use core::time::Duration; - use crate::{Currency, Description, InvoiceDescription}; - use bitcoin_hashes::Hash; + use crate::{Currency, Description, InvoiceDescription, SignOrCreationError, CreationError}; + use bitcoin_hashes::{Hash, sha256}; use bitcoin_hashes::sha256::Hash as Sha256; - use lightning::chain::keysinterface::PhantomKeysManager; + use lightning::chain::keysinterface::{EntropySource, PhantomKeysManager}; use lightning::ln::{PaymentPreimage, PaymentHash}; - use lightning::ln::channelmanager::{self, PhantomRouteHints, MIN_FINAL_CLTV_EXPIRY, PaymentId}; + use lightning::ln::channelmanager::{PhantomRouteHints, MIN_FINAL_CLTV_EXPIRY_DELTA, PaymentId}; use lightning::ln::functional_test_utils::*; use lightning::ln::msgs::ChannelMessageHandler; use lightning::routing::router::{PaymentParameters, RouteParameters, find_route}; use lightning::util::events::{MessageSendEvent, MessageSendEventsProvider, Event}; use lightning::util::test_utils; use lightning::util::config::UserConfig; - use lightning::chain::keysinterface::KeysInterface; use crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch; use std::collections::HashSet; @@ -652,14 +657,15 @@ mod test { let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); let nodes = create_network(2, &node_cfgs, &node_chanmgrs); - create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001); let non_default_invoice_expiry_secs = 4200; let invoice = create_invoice_from_channelmanager_and_duration_since_epoch( &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet, Some(10_000), "test".to_string(), Duration::from_secs(1234567), - non_default_invoice_expiry_secs).unwrap(); + non_default_invoice_expiry_secs, None).unwrap(); assert_eq!(invoice.amount_pico_btc(), Some(100_000)); - assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64); + // If no `min_final_cltv_expiry_delta` is specified, then it should be `MIN_FINAL_CLTV_EXPIRY_DELTA`. + assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64); assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string()))); assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into())); @@ -673,18 +679,18 @@ mod test { assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan.inbound_htlc_minimum_msat); assert_eq!(invoice.route_hints()[0].0[0].htlc_maximum_msat, chan.inbound_htlc_maximum_msat); - let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key()) + let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(), + invoice.min_final_cltv_expiry_delta() as u32) .with_features(invoice.features().unwrap().clone()) .with_route_hints(invoice.route_hints()); let route_params = RouteParameters { payment_params, final_value_msat: invoice.amount_milli_satoshis().unwrap(), - final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32, }; let first_hops = nodes[0].node.list_usable_channels(); let network_graph = &node_cfgs[0].network_graph; let logger = test_utils::TestLogger::new(); - let scorer = test_utils::TestScorer::with_penalty(0); + let scorer = test_utils::TestScorer::new(); let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes(); let route = find_route( &nodes[0].node.get_our_node_id(), &route_params, &network_graph, @@ -713,6 +719,44 @@ mod test { assert_eq!(events.len(), 2); } + fn do_create_invoice_min_final_cltv_delta(with_custom_delta: bool) { + 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 nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let custom_min_final_cltv_expiry_delta = Some(50); + + let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch( + &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet, + Some(10_000), "".into(), Duration::from_secs(1234567), 3600, + if with_custom_delta { custom_min_final_cltv_expiry_delta } else { None }, + ).unwrap(); + assert_eq!(invoice.min_final_cltv_expiry_delta(), if with_custom_delta { + custom_min_final_cltv_expiry_delta.unwrap() + 3 /* Buffer */} else { MIN_FINAL_CLTV_EXPIRY_DELTA } as u64); + } + + #[test] + fn test_create_invoice_custom_min_final_cltv_delta() { + do_create_invoice_min_final_cltv_delta(true); + do_create_invoice_min_final_cltv_delta(false); + } + + #[test] + fn create_invoice_min_final_cltv_delta_equals_htlc_fail_buffer() { + 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 nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let custom_min_final_cltv_expiry_delta = Some(21); + + let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch( + &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet, + Some(10_000), "".into(), Duration::from_secs(1234567), 3600, + custom_min_final_cltv_expiry_delta, + ).unwrap(); + assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64); + } + #[test] fn test_create_invoice_with_description_hash() { let chanmon_cfgs = create_chanmon_cfgs(2); @@ -722,13 +766,31 @@ mod test { let description_hash = crate::Sha256(Hash::hash("Testing description_hash".as_bytes())); let invoice = crate::utils::create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch( &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet, - Some(10_000), description_hash, Duration::from_secs(1234567), 3600 + Some(10_000), description_hash, Duration::from_secs(1234567), 3600, None, ).unwrap(); assert_eq!(invoice.amount_pico_btc(), Some(100_000)); - assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64); + assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64); assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Testing description_hash".as_bytes())))); } + #[test] + fn test_create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash() { + 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 nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let payment_hash = PaymentHash([0; 32]); + let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash( + &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet, + Some(10_000), "test".to_string(), Duration::from_secs(1234567), 3600, + payment_hash, None, + ).unwrap(); + assert_eq!(invoice.amount_pico_btc(), Some(100_000)); + assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64); + assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string()))); + assert_eq!(invoice.payment_hash(), &sha256::Hash::from_slice(&payment_hash.0[..]).unwrap()); + } + #[test] fn test_hints_includes_single_channels_to_nodes() { let chanmon_cfgs = create_chanmon_cfgs(3); @@ -736,8 +798,8 @@ mod test { let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); let nodes = create_network(3, &node_cfgs, &node_chanmgrs); - let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); - let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001); + let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001); let mut scid_aliases = HashSet::new(); scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap()); @@ -752,13 +814,11 @@ mod test { let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); let nodes = create_network(2, &node_cfgs, &node_chanmgrs); - let _chan_1_0_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()); - let chan_1_0_high_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()); - let _chan_1_0_medium_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()); - + let _chan_1_0_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0); + let chan_1_0_high_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000_000, 0); + let _chan_1_0_medium_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 1_000_000, 0); let mut scid_aliases = HashSet::new(); scid_aliases.insert(chan_1_0_high_inbound_capacity.0.short_channel_id_alias.unwrap()); - match_invoice_routes(Some(5000), &nodes[0], scid_aliases); } @@ -768,9 +828,9 @@ mod test { let node_cfgs = create_node_cfgs(4, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]); let nodes = create_network(4, &node_cfgs, &node_chanmgrs); - let chan_a = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()); - let chan_b = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 10_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()); - let _chan_c = create_unannounced_chan_between_nodes_with_value(&nodes, 3, 0, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + let chan_a = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000_000, 0); + let chan_b = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 10_000_000, 0); + let _chan_c = create_unannounced_chan_between_nodes_with_value(&nodes, 3, 0, 1_000_000, 0); // With all peers connected we should get all hints that have sufficient value let mut scid_aliases = HashSet::new(); @@ -781,13 +841,13 @@ mod test { // With only one sufficient-value peer connected we should only get its hint scid_aliases.remove(&chan_b.0.short_channel_id_alias.unwrap()); - nodes[0].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false); + nodes[0].node.peer_disconnected(&nodes[2].node.get_our_node_id()); match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone()); // If we don't have any sufficient-value peers connected we should get all hints with // sufficient value, even though there is a connected insufficient-value peer. scid_aliases.insert(chan_b.0.short_channel_id_alias.unwrap()); - nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false); + nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id()); match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases); } @@ -797,7 +857,7 @@ mod test { let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); let nodes = create_network(3, &node_cfgs, &node_chanmgrs); - let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001); // Create an unannonced channel between `nodes[2]` and `nodes[0]`, for which the // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate` @@ -806,9 +866,9 @@ mod test { private_chan_cfg.channel_handshake_config.announced_channel = false; let temporary_channel_id = nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 1_000_000, 500_000_000, 42, Some(private_chan_cfg)).unwrap(); let open_channel = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id()); - nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel); + nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_channel); let accept_channel = get_event_msg!(nodes[0], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id()); - nodes[2].node.handle_accept_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel); + nodes[2].node.handle_accept_channel(&nodes[0].node.get_our_node_id(), &accept_channel); let tx = sign_funding_transaction(&nodes[2], &nodes[0], 1_000_000, temporary_channel_id); @@ -839,9 +899,9 @@ mod test { let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); let nodes = create_network(3, &node_cfgs, &node_chanmgrs); - let _chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + let _chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001); - let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001); nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1); nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0); @@ -857,11 +917,11 @@ mod test { let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); let nodes = create_network(3, &node_cfgs, &node_chanmgrs); - let chan_1_0 = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + let chan_1_0 = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001); nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_1_0.0); nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_1_0.1); - let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001); nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1); nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0); @@ -875,8 +935,8 @@ mod test { let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); let nodes = create_network(3, &node_cfgs, &node_chanmgrs); - let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()); - let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0); + let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 1_000_000, 0); // As the invoice amt is 1 msat above chan_1_0's inbound capacity, it shouldn't be included let mut scid_aliases_99_000_001_msat = HashSet::new(); @@ -914,7 +974,7 @@ mod test { let invoice = create_invoice_from_channelmanager_and_duration_since_epoch( &invoice_node.node, invoice_node.keys_manager, invoice_node.logger, Currency::BitcoinTestnet, invoice_amt, "test".to_string(), Duration::from_secs(1234567), - 3600).unwrap(); + 3600, None).unwrap(); let hints = invoice.private_routes(); for hint in hints { @@ -942,10 +1002,10 @@ mod test { let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); let nodes = create_network(3, &node_cfgs, &node_chanmgrs); - let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001); nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_0_1.1); nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_1.0); - let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001); nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1); nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0); @@ -964,9 +1024,10 @@ mod test { let non_default_invoice_expiry_secs = 4200; let invoice = - crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface, &test_utils::TestLogger>( + crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestLogger>( Some(payment_amt), payment_hash, "test".to_string(), non_default_invoice_expiry_secs, - route_hints, &nodes[1].keys_manager, &nodes[1].logger, Currency::BitcoinTestnet + route_hints, &nodes[1].keys_manager, &nodes[1].keys_manager, &nodes[1].logger, + Currency::BitcoinTestnet, None, Duration::from_secs(1234567) ).unwrap(); let (payment_hash, payment_secret) = (PaymentHash(invoice.payment_hash().into_inner()), *invoice.payment_secret()); let payment_preimage = if user_generated_pmt_hash { @@ -975,24 +1036,24 @@ mod test { nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap() }; - assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64); + assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64); assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string()))); assert_eq!(invoice.route_hints().len(), 2); assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into())); assert!(!invoice.features().unwrap().supports_basic_mpp()); - let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key()) + let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(), + invoice.min_final_cltv_expiry_delta() as u32) .with_features(invoice.features().unwrap().clone()) .with_route_hints(invoice.route_hints()); let params = RouteParameters { payment_params, final_value_msat: invoice.amount_milli_satoshis().unwrap(), - final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32, }; let first_hops = nodes[0].node.list_usable_channels(); let network_graph = &node_cfgs[0].network_graph; let logger = test_utils::TestLogger::new(); - let scorer = test_utils::TestScorer::with_penalty(0); + let scorer = test_utils::TestScorer::new(); let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes(); let route = find_route( &nodes[0].node.get_our_node_id(), ¶ms, &network_graph, @@ -1021,7 +1082,7 @@ mod test { nodes[fwd_idx].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); commitment_signed_dance!(nodes[fwd_idx], nodes[0], &payment_event.commitment_msg, false, true); - // Note that we have to "forward pending HTLCs" twice before we see the PaymentReceived as + // Note that we have to "forward pending HTLCs" twice before we see the PaymentClaimable as // this "emulates" the payment taking two hops, providing some privacy to make phantom node // payments "look real" by taking more time. expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]); @@ -1030,7 +1091,7 @@ mod test { nodes[fwd_idx].node.process_pending_htlc_forwards(); let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) }; - expect_payment_received!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt); + expect_payment_claimable!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt, route.paths[0].last().unwrap().pubkey); do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[fwd_idx])[..]), false, payment_preimage); let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 2); @@ -1063,17 +1124,20 @@ mod test { let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); let nodes = create_network(3, &node_cfgs, &node_chanmgrs); - create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); - create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001); + create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001); let payment_amt = 20_000; - let (payment_hash, _payment_secret) = nodes[1].node.create_inbound_payment(Some(payment_amt), 3600).unwrap(); + let (payment_hash, _payment_secret) = nodes[1].node.create_inbound_payment(Some(payment_amt), 3600, None).unwrap(); let route_hints = vec![ nodes[1].node.get_phantom_route_hints(), nodes[2].node.get_phantom_route_hints(), ]; - let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface, &test_utils::TestLogger>(Some(payment_amt), Some(payment_hash), "test".to_string(), 3600, route_hints, &nodes[1].keys_manager, &nodes[1].logger, Currency::BitcoinTestnet).unwrap(); + let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface, + &test_utils::TestKeysInterface, &test_utils::TestLogger>(Some(payment_amt), Some(payment_hash), + "test".to_string(), 3600, route_hints, &nodes[1].keys_manager, &nodes[1].keys_manager, + &nodes[1].logger, Currency::BitcoinTestnet, None, Duration::from_secs(1234567)).unwrap(); let chan_0_1 = &nodes[1].node.list_usable_channels()[0]; assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan_0_1.inbound_htlc_minimum_msat); @@ -1101,18 +1165,46 @@ mod test { let description_hash = crate::Sha256(Hash::hash("Description hash phantom invoice".as_bytes())); let non_default_invoice_expiry_secs = 4200; let invoice = crate::utils::create_phantom_invoice_with_description_hash::< - &test_utils::TestKeysInterface, &test_utils::TestLogger, + &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestLogger, >( Some(payment_amt), None, non_default_invoice_expiry_secs, description_hash, - route_hints, &nodes[1].keys_manager, &nodes[1].logger, Currency::BitcoinTestnet + route_hints, &nodes[1].keys_manager, &nodes[1].keys_manager, &nodes[1].logger, + Currency::BitcoinTestnet, None, Duration::from_secs(1234567), ) .unwrap(); assert_eq!(invoice.amount_pico_btc(), Some(200_000)); - assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64); + assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64); assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into())); assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Description hash phantom invoice".as_bytes())))); } + #[test] + #[cfg(feature = "std")] + fn create_phantom_invoice_with_custom_payment_hash_and_custom_min_final_cltv_delta() { + let chanmon_cfgs = create_chanmon_cfgs(3); + let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); + let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); + + let payment_amt = 20_000; + let route_hints = vec![ + nodes[1].node.get_phantom_route_hints(), + nodes[2].node.get_phantom_route_hints(), + ]; + let user_payment_preimage = PaymentPreimage([1; 32]); + let payment_hash = Some(PaymentHash(Sha256::hash(&user_payment_preimage.0[..]).into_inner())); + let non_default_invoice_expiry_secs = 4200; + let min_final_cltv_expiry_delta = Some(100); + let duration_since_epoch = Duration::from_secs(1234567); + let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface, + &test_utils::TestKeysInterface, &test_utils::TestLogger>(Some(payment_amt), payment_hash, + "".to_string(), non_default_invoice_expiry_secs, route_hints, &nodes[1].keys_manager, &nodes[1].keys_manager, + &nodes[1].logger, Currency::BitcoinTestnet, min_final_cltv_expiry_delta, duration_since_epoch).unwrap(); + assert_eq!(invoice.amount_pico_btc(), Some(200_000)); + assert_eq!(invoice.min_final_cltv_expiry_delta(), (min_final_cltv_expiry_delta.unwrap() + 3) as u64); + assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into())); + } + #[test] #[cfg(feature = "std")] fn test_multi_node_hints_includes_single_channels_to_participating_nodes() { @@ -1126,8 +1218,8 @@ mod test { let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); let nodes = create_network(3, &node_cfgs, &node_chanmgrs); - let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); - let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001); + let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001); let mut scid_aliases = HashSet::new(); scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap()); @@ -1155,9 +1247,9 @@ mod test { let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]); let nodes = create_network(4, &node_cfgs, &node_chanmgrs); - let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); - let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); - let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 3_000_000, 10005, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001); + let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001); + let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 3_000_000, 10005); let mut scid_aliases = HashSet::new(); scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap()); @@ -1186,8 +1278,8 @@ mod test { let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]); let nodes = create_network(4, &node_cfgs, &node_chanmgrs); - let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); - let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001); + let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001); // Create an unannonced channel between `nodes[1]` and `nodes[3]`, for which the // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate` @@ -1196,9 +1288,9 @@ mod test { private_chan_cfg.channel_handshake_config.announced_channel = false; let temporary_channel_id = nodes[1].node.create_channel(nodes[3].node.get_our_node_id(), 1_000_000, 500_000_000, 42, Some(private_chan_cfg)).unwrap(); let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[3].node.get_our_node_id()); - nodes[3].node.handle_open_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel); + nodes[3].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_channel); let accept_channel = get_event_msg!(nodes[3], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id()); - nodes[1].node.handle_accept_channel(&nodes[3].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel); + nodes[1].node.handle_accept_channel(&nodes[3].node.get_our_node_id(), &accept_channel); let tx = sign_funding_transaction(&nodes[1], &nodes[3], 1_000_000, temporary_channel_id); @@ -1244,9 +1336,9 @@ mod test { let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); let nodes = create_network(3, &node_cfgs, &node_chanmgrs); - let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001); - let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001); nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1); nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0); @@ -1277,12 +1369,12 @@ mod test { let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]); let nodes = create_network(4, &node_cfgs, &node_chanmgrs); - let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001); nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1); nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0); - let _chan_1_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + let _chan_1_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001); - let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100000, 10001); // Hints should include `chan_0_3` from as `nodes[3]` only have private channels, and no // channels for `nodes[2]` as it contains a mix of public and private channels. @@ -1311,10 +1403,10 @@ mod test { let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); let nodes = create_network(3, &node_cfgs, &node_chanmgrs); - let _chan_0_1_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()); - let chan_0_1_high_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()); - let _chan_0_1_medium_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()); - let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + let _chan_0_1_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0); + let chan_0_1_high_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0); + let _chan_0_1_medium_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0); + let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001); let mut scid_aliases = HashSet::new(); scid_aliases.insert(chan_0_1_high_inbound_capacity.0.short_channel_id_alias.unwrap()); @@ -1342,9 +1434,9 @@ mod test { let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]); let nodes = create_network(4, &node_cfgs, &node_chanmgrs); - let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()); - let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()); - let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 200_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()); + let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0); + let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100_000, 0); + let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 200_000, 0); // Since the invoice 1 msat above chan_0_3's inbound capacity, it should be filtered out. let mut scid_aliases_99_000_001_msat = HashSet::new(); @@ -1418,7 +1510,10 @@ mod test { .map(|route_hint| route_hint.phantom_scid) .collect::>(); - let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface, &test_utils::TestLogger>(invoice_amt, None, "test".to_string(), 3600, phantom_route_hints, &invoice_node.keys_manager, &invoice_node.logger, Currency::BitcoinTestnet).unwrap(); + let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface, + &test_utils::TestKeysInterface, &test_utils::TestLogger>(invoice_amt, None, "test".to_string(), + 3600, phantom_route_hints, &invoice_node.keys_manager, &invoice_node.keys_manager, + &invoice_node.logger, Currency::BitcoinTestnet, None, Duration::from_secs(1234567)).unwrap(); let invoice_hints = invoice.private_routes(); @@ -1441,4 +1536,20 @@ mod test { } assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match); } + + #[test] + fn test_create_invoice_fails_with_invalid_custom_min_final_cltv_expiry_delta() { + 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 nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let result = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch( + &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet, + Some(10_000), "Some description".into(), Duration::from_secs(1234567), 3600, Some(MIN_FINAL_CLTV_EXPIRY_DELTA - 4), + ); + match result { + Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort)) => {}, + _ => panic!(), + } + } }