Merge pull request #1553 from wvanlint/dns_hostname
[rust-lightning] / lightning-invoice / src / utils.rs
index d287ea67283d6b62b6a290474c1a072a40565dd1..9ef2d2c8d39214e5a94423fa0c3e98006da9051c 100644 (file)
@@ -1,6 +1,6 @@
 //! Convenient utilities to create an invoice.
 
-use {CreationError, Currency, DEFAULT_EXPIRY_TIME, Invoice, InvoiceBuilder, SignOrCreationError};
+use {CreationError, Currency, Invoice, InvoiceBuilder, SignOrCreationError};
 use payment::{Payer, Router};
 
 use crate::{prelude::*, Description, InvoiceDescription, Sha256};
@@ -15,12 +15,11 @@ use lightning::ln::channelmanager::{ChannelDetails, ChannelManager, PaymentId, P
 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::scoring::Score;
-use lightning::routing::network_graph::{NetworkGraph, RoutingFees};
+use lightning::routing::gossip::{NetworkGraph, RoutingFees};
 use lightning::routing::router::{Route, RouteHint, RouteHintHop, RouteParameters, find_route};
+use lightning::routing::scoring::Score;
 use lightning::util::logger::Logger;
 use secp256k1::PublicKey;
-use core::convert::TryInto;
 use core::ops::Deref;
 use core::time::Duration;
 use sync::Mutex;
@@ -213,9 +212,12 @@ fn _create_phantom_invoice<Signer: Sign, K: Deref>(
 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
 /// that the payment secret is valid when the invoice is paid.
+///
+/// `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<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
        channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
-       amt_msat: Option<u64>, description: String
+       amt_msat: Option<u64>, description: String, invoice_expiry_delta_secs: u32
 ) -> Result<Invoice, SignOrCreationError<()>>
 where
        M::Target: chain::Watch<Signer>,
@@ -228,7 +230,8 @@ where
        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, network, amt_msat, description, duration
+               channelmanager, keys_manager, network, amt_msat, description, duration,
+               invoice_expiry_delta_secs
        )
 }
 
@@ -239,9 +242,12 @@ where
 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
 /// that the payment secret is valid when the invoice is paid.
 /// Use this variant if you want to pass the `description_hash` to the invoice.
+///
+/// `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<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
        channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
-       amt_msat: Option<u64>, description_hash: Sha256,
+       amt_msat: Option<u64>, description_hash: Sha256, invoice_expiry_delta_secs: u32
 ) -> Result<Invoice, SignOrCreationError<()>>
 where
        M::Target: chain::Watch<Signer>,
@@ -257,7 +263,8 @@ where
                .expect("for the foreseeable future this shouldn't happen");
 
        create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
-               channelmanager, keys_manager, network, amt_msat, description_hash, duration,
+               channelmanager, keys_manager, network, amt_msat,
+               description_hash, duration, invoice_expiry_delta_secs
        )
 }
 
@@ -267,6 +274,7 @@ where
 pub fn create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
        channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
        amt_msat: Option<u64>, description_hash: Sha256, duration_since_epoch: Duration,
+       invoice_expiry_delta_secs: u32
 ) -> Result<Invoice, SignOrCreationError<()>>
 where
        M::Target: chain::Watch<Signer>,
@@ -278,7 +286,7 @@ where
        _create_invoice_from_channelmanager_and_duration_since_epoch(
                channelmanager, keys_manager, network, amt_msat,
                InvoiceDescription::Hash(&description_hash),
-               duration_since_epoch,
+               duration_since_epoch, invoice_expiry_delta_secs
        )
 }
 
@@ -288,6 +296,7 @@ where
 pub fn create_invoice_from_channelmanager_and_duration_since_epoch<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
        channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
        amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
+       invoice_expiry_delta_secs: u32
 ) -> Result<Invoice, SignOrCreationError<()>>
 where
        M::Target: chain::Watch<Signer>,
@@ -301,13 +310,14 @@ where
                InvoiceDescription::Direct(
                        &Description::new(description).map_err(SignOrCreationError::CreationError)?,
                ),
-               duration_since_epoch,
+               duration_since_epoch, invoice_expiry_delta_secs
        )
 }
 
 fn _create_invoice_from_channelmanager_and_duration_since_epoch<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
        channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
        amt_msat: Option<u64>, description: InvoiceDescription, duration_since_epoch: Duration,
+       invoice_expiry_delta_secs: u32
 ) -> Result<Invoice, SignOrCreationError<()>>
 where
        M::Target: chain::Watch<Signer>,
@@ -321,7 +331,7 @@ where
        // `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, DEFAULT_EXPIRY_TIME.try_into().unwrap())
+               .create_inbound_payment(amt_msat, invoice_expiry_delta_secs)
                .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
        let our_node_pubkey = channelmanager.get_our_node_id();
 
@@ -338,7 +348,8 @@ 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(MIN_FINAL_CLTV_EXPIRY.into())
+               .expiry_time(Duration::from_secs(invoice_expiry_delta_secs.into()));
        if let Some(amt) = amt_msat {
                invoice = invoice.amount_milli_satoshis(amt);
        }
@@ -429,13 +440,13 @@ fn filter_channels(channels: Vec<ChannelDetails>, min_inbound_capacity_msat: Opt
 }
 
 /// A [`Router`] implemented using [`find_route`].
-pub struct DefaultRouter<G: Deref<Target = NetworkGraph>, L: Deref> where L::Target: Logger {
+pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref> where L::Target: Logger {
        network_graph: G,
        logger: L,
        random_seed_bytes: Mutex<[u8; 32]>,
 }
 
-impl<G: Deref<Target = NetworkGraph>, L: Deref> DefaultRouter<G, L> where L::Target: Logger {
+impl<G: Deref<Target = NetworkGraph<L>>, L: Deref> DefaultRouter<G, L> where L::Target: Logger {
        /// 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]) -> Self {
@@ -444,7 +455,7 @@ impl<G: Deref<Target = NetworkGraph>, L: Deref> DefaultRouter<G, L> where L::Tar
        }
 }
 
-impl<G: Deref<Target = NetworkGraph>, L: Deref, S: Score> Router<S> for DefaultRouter<G, L>
+impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Score> Router<S> for DefaultRouter<G, L>
 where L::Target: Logger {
        fn find_route(
                &self, payer: &PublicKey, params: &RouteParameters, _payment_hash: &PaymentHash,
@@ -455,7 +466,7 @@ where L::Target: Logger {
                        *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, scorer, &random_seed_bytes)
+               find_route(payer, params, &self.network_graph, first_hops, &*self.logger, scorer, &random_seed_bytes)
        }
 }
 
@@ -527,12 +538,14 @@ mod test {
                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, InitFeatures::known(), InitFeatures::known());
+               let non_default_invoice_expiry_secs = 4200;
                let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
                        &nodes[1].node, nodes[1].keys_manager, Currency::BitcoinTestnet, Some(10_000), "test".to_string(),
-                       Duration::from_secs(1234567)).unwrap();
+                       Duration::from_secs(1234567), non_default_invoice_expiry_secs).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.description(), InvoiceDescription::Direct(&Description("test".to_string())));
+               assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
 
                // Invoice SCIDs should always use inbound SCID aliases over the real channel ID, if one is
                // available.
@@ -553,12 +566,12 @@ mod test {
                        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 network_graph = &node_cfgs[0].network_graph;
                let logger = test_utils::TestLogger::new();
                let scorer = test_utils::TestScorer::with_penalty(0);
                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,
+                       &nodes[0].node.get_our_node_id(), &route_params, &network_graph,
                        Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
                ).unwrap();
 
@@ -593,7 +606,7 @@ mod test {
                let description_hash = crate::Sha256(Hash::hash("Testing description_hash".as_bytes()));
                let invoice = ::utils::create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
                        &nodes[1].node, nodes[1].keys_manager, Currency::BitcoinTestnet, Some(10_000),
-                       description_hash, Duration::from_secs(1234567),
+                       description_hash, Duration::from_secs(1234567), 3600
                ).unwrap();
                assert_eq!(invoice.amount_pico_btc(), Some(100_000));
                assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
@@ -645,7 +658,7 @@ mod test {
                // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
                // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
                let mut private_chan_cfg = UserConfig::default();
-               private_chan_cfg.channel_options.announced_channel = false;
+               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(), InitFeatures::known(), &open_channel);
@@ -659,10 +672,10 @@ mod test {
                connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
                confirm_transaction_at(&nodes[0], &tx, conf_height);
                connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH - 1);
-               let as_funding_locked = get_event_msg!(nodes[2], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id());
-               nodes[2].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendFundingLocked, nodes[2].node.get_our_node_id()));
+               let as_channel_ready = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReady, nodes[0].node.get_our_node_id());
+               nodes[2].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[2].node.get_our_node_id()));
                get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
-               nodes[0].node.handle_funding_locked(&nodes[2].node.get_our_node_id(), &as_funding_locked);
+               nodes[0].node.handle_channel_ready(&nodes[2].node.get_our_node_id(), &as_channel_ready);
                get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
 
                // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the second
@@ -753,7 +766,7 @@ mod test {
        ) {
                let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
                        &invoice_node.node, invoice_node.keys_manager, Currency::BitcoinTestnet, invoice_amt, "test".to_string(),
-                       Duration::from_secs(1234567)).unwrap();
+                       Duration::from_secs(1234567), 3600).unwrap();
                let hints = invoice.private_routes();
 
                for hint in hints {
@@ -802,12 +815,11 @@ mod test {
                };
                let non_default_invoice_expiry_secs = 4200;
 
-               let invoice = ::utils::create_phantom_invoice::<
-                       EnforcingSigner, &test_utils::TestKeysInterface
-               >(
-                       Some(payment_amt), payment_hash, "test".to_string(), non_default_invoice_expiry_secs,
-                       route_hints, &nodes[1].keys_manager, Currency::BitcoinTestnet
-               ).unwrap();
+               let invoice =
+                       ::utils::create_phantom_invoice::<EnforcingSigner, &test_utils::TestKeysInterface>(
+                               Some(payment_amt), payment_hash, "test".to_string(), non_default_invoice_expiry_secs,
+                               route_hints, &nodes[1].keys_manager, Currency::BitcoinTestnet
+                       ).unwrap();
                let (payment_hash, payment_secret) = (PaymentHash(invoice.payment_hash().into_inner()), *invoice.payment_secret());
                let payment_preimage = if user_generated_pmt_hash {
                        user_payment_preimage
@@ -830,12 +842,12 @@ mod test {
                        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 network_graph = &node_cfgs[0].network_graph;
                let logger = test_utils::TestLogger::new();
                let scorer = test_utils::TestScorer::with_penalty(0);
                let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
                let route = find_route(
-                       &nodes[0].node.get_our_node_id(), &params, network_graph,
+                       &nodes[0].node.get_our_node_id(), &params, &network_graph,
                        Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
                ).unwrap();
                let (payment_event, fwd_idx) = {
@@ -1033,7 +1045,7 @@ mod test {
                // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
                // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
                let mut private_chan_cfg = UserConfig::default();
-               private_chan_cfg.channel_options.announced_channel = false;
+               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(), InitFeatures::known(), &open_channel);
@@ -1047,10 +1059,10 @@ mod test {
                connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
                confirm_transaction_at(&nodes[3], &tx, conf_height);
                connect_blocks(&nodes[3], CHAN_CONFIRM_DEPTH - 1);
-               let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[3].node.get_our_node_id());
-               nodes[1].node.handle_funding_locked(&nodes[3].node.get_our_node_id(), &get_event_msg!(nodes[3], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id()));
+               let as_channel_ready = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReady, nodes[3].node.get_our_node_id());
+               nodes[1].node.handle_channel_ready(&nodes[3].node.get_our_node_id(), &get_event_msg!(nodes[3], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id()));
                get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
-               nodes[3].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
+               nodes[3].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &as_channel_ready);
                get_event_msg!(nodes[3], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
 
                // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the third