X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning-invoice%2Fsrc%2Futils.rs;h=47856fb487cf8b4164d92433e95eabdee4b4e5a3;hb=14d2e979651769bfff7acb6fed33b0e7df509d9a;hp=b161ebd32f8c415c9a72513050a7d4f4cefef836;hpb=ad82c9ea5bf735068c11c8eebdf68ac57f135eec;p=rust-lightning diff --git a/lightning-invoice/src/utils.rs b/lightning-invoice/src/utils.rs index b161ebd3..47856fb4 100644 --- a/lightning-invoice/src/utils.rs +++ b/lightning-invoice/src/utils.rs @@ -1,28 +1,25 @@ //! Convenient utilities to create an invoice. -use {CreationError, Currency, Invoice, InvoiceBuilder, SignOrCreationError}; -use payment::{InFlightHtlcs, Payer, Router}; +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, Sign}; +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::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, NodeId, RoutingFees}; -use lightning::routing::router::{Route, RouteHint, RouteHintHop, RouteParameters, find_route, RouteHop}; -use lightning::routing::scoring::{ChannelUsage, LockableScore, Score}; +use lightning::routing::gossip::RoutingFees; +use lightning::routing::router::{InFlightHtlcs, Route, RouteHint, RouteHintHop}; use lightning::util::logger::Logger; use secp256k1::PublicKey; use core::ops::Deref; use core::time::Duration; -use sync::Mutex; #[cfg(feature = "std")] /// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice." @@ -54,7 +51,7 @@ use 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( +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, @@ -65,7 +62,7 @@ where { 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, ) @@ -103,7 +100,7 @@ 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( +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 @@ -112,14 +109,14 @@ where K::Target: KeysInterface, 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, ) } #[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, @@ -235,14 +232,14 @@ 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, +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 ) -> Result> where - M::Target: chain::Watch, + M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -265,15 +262,15 @@ 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, +pub fn create_invoice_from_channelmanager_with_description_hash( + channelmanager: &ChannelManager, keys_manager: K, logger: L, network: Currency, amt_msat: Option, description_hash: Sha256, invoice_expiry_delta_secs: u32 ) -> Result> where - M::Target: chain::Watch, + M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -292,15 +289,15 @@ where /// 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, keys_manager: K, logger: L, network: Currency, amt_msat: Option, description_hash: Sha256, duration_since_epoch: Duration, invoice_expiry_delta_secs: u32 ) -> Result> where - M::Target: chain::Watch, + M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -314,15 +311,15 @@ where /// 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, keys_manager: K, logger: L, network: Currency, amt_msat: Option, description: String, duration_since_epoch: Duration, invoice_expiry_delta_secs: u32 ) -> Result> where - M::Target: chain::Watch, + M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -335,15 +332,15 @@ where ) } -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, keys_manager: K, logger: L, network: Currency, amt_msat: Option, description: InvoiceDescription, duration_since_epoch: Duration, invoice_expiry_delta_secs: u32 ) -> Result> where - M::Target: chain::Watch, + M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -524,72 +521,11 @@ 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, _payment_hash: &PaymentHash, - 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 +impl Payer for ChannelManager where - M::Target: chain::Watch, + M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -602,16 +538,16 @@ where } fn send_payment( - &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option - ) -> Result { - self.send_payment(route, payment_hash, payment_secret) + &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, - ) -> Result { - self.send_spontaneous_payment(route, Some(payment_preimage)) - .map(|(_, payment_id)| payment_id) + &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( @@ -623,74 +559,27 @@ where fn abandon_payment(&self, payment_id: PaymentId) { self.abandon_payment(payment_id) } -} - - -/// Used to store information about all the HTLCs that are inflight across all payment attempts. -pub(crate) struct ScorerAccountingForInFlightHtlcs<'a, S: Score> { - scorer: &'a mut S, - /// Maps a channel's short channel id and its direction to the liquidity used up. - inflight_htlcs: InFlightHtlcs, -} - -impl<'a, S: Score> ScorerAccountingForInFlightHtlcs<'a, S> { - pub(crate) fn new(scorer: &'a mut S, inflight_htlcs: InFlightHtlcs) -> Self { - ScorerAccountingForInFlightHtlcs { - scorer, - inflight_htlcs - } - } -} -#[cfg(c_bindings)] -impl<'a, S:Score> lightning::util::ser::Writeable for ScorerAccountingForInFlightHtlcs<'a, S> { - fn write(&self, writer: &mut W) -> Result<(), lightning::io::Error> { self.scorer.write(writer) } + fn inflight_htlcs(&self) -> InFlightHtlcs { self.compute_inflight_htlcs() } } -impl<'a, S: Score> Score for ScorerAccountingForInFlightHtlcs<'a, S> { - fn channel_penalty_msat(&self, short_channel_id: u64, source: &NodeId, target: &NodeId, usage: ChannelUsage) -> u64 { - if let Some(used_liqudity) = self.inflight_htlcs.used_liquidity_msat( - source, target, short_channel_id - ) { - let usage = ChannelUsage { - inflight_htlc_msat: usage.inflight_htlc_msat + used_liqudity, - ..usage - }; - - self.scorer.channel_penalty_msat(short_channel_id, source, target, usage) - } else { - self.scorer.channel_penalty_msat(short_channel_id, source, target, usage) - } - } - - fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) { unreachable!() } - - fn payment_path_successful(&mut self, _path: &[&RouteHop]) { unreachable!() } - - fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) { unreachable!() } - - fn probe_successful(&mut self, _path: &[&RouteHop]) { unreachable!() } -} - - #[cfg(test)] mod test { use core::time::Duration; - use {Currency, Description, InvoiceDescription}; + use crate::{Currency, Description, InvoiceDescription}; use bitcoin_hashes::Hash; use bitcoin_hashes::sha256::Hash as Sha256; use lightning::chain::keysinterface::PhantomKeysManager; use lightning::ln::{PaymentPreimage, PaymentHash}; - use lightning::ln::channelmanager::{self, PhantomRouteHints, MIN_FINAL_CLTV_EXPIRY}; + use lightning::ln::channelmanager::{self, PhantomRouteHints, MIN_FINAL_CLTV_EXPIRY, PaymentId}; use lightning::ln::functional_test_utils::*; use lightning::ln::msgs::ChannelMessageHandler; use lightning::routing::router::{PaymentParameters, RouteParameters, find_route}; - use lightning::util::enforcing_trait_impls::EnforcingSigner; use lightning::util::events::{MessageSendEvent, MessageSendEventsProvider, Event}; use lightning::util::test_utils; use lightning::util::config::UserConfig; use lightning::chain::keysinterface::KeysInterface; - use utils::create_invoice_from_channelmanager_and_duration_since_epoch; + use crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch; use std::collections::HashSet; #[test] @@ -741,7 +630,7 @@ mod test { let payment_event = { let mut payment_hash = PaymentHash([0; 32]); payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]); - nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap(); + nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone()), PaymentId(payment_hash.0)).unwrap(); let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap(); assert_eq!(added_monitors.len(), 1); added_monitors.clear(); @@ -767,7 +656,7 @@ mod test { let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); let nodes = create_network(2, &node_cfgs, &node_chanmgrs); 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( + 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 ).unwrap(); @@ -869,6 +758,8 @@ mod test { get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id()); 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()); + expect_channel_ready_event(&nodes[0], &nodes[2].node.get_our_node_id()); + expect_channel_ready_event(&nodes[2], &nodes[0].node.get_our_node_id()); // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the second // channel, the channel will never be assigned any `counterparty.forwarding_info`. @@ -1009,7 +900,7 @@ mod test { let non_default_invoice_expiry_secs = 4200; let invoice = - ::utils::create_phantom_invoice::( + crate::utils::create_phantom_invoice::<&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 ).unwrap(); @@ -1046,7 +937,7 @@ mod test { let (payment_event, fwd_idx) = { let mut payment_hash = PaymentHash([0; 32]); payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]); - nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap(); + nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone()), PaymentId(payment_hash.0)).unwrap(); let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap(); assert_eq!(added_monitors.len(), 1); added_monitors.clear(); @@ -1075,7 +966,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_received!(&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); @@ -1118,7 +1009,7 @@ mod test { nodes[2].node.get_phantom_route_hints(), ]; - let invoice = ::utils::create_phantom_invoice::(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::TestLogger>(Some(payment_amt), Some(payment_hash), "test".to_string(), 3600, route_hints, &nodes[1].keys_manager, &nodes[1].logger, Currency::BitcoinTestnet).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); @@ -1145,8 +1036,8 @@ mod test { let description_hash = crate::Sha256(Hash::hash("Description hash phantom invoice".as_bytes())); let non_default_invoice_expiry_secs = 4200; - let invoice = ::utils::create_phantom_invoice_with_description_hash::< - EnforcingSigner, &test_utils::TestKeysInterface, &test_utils::TestLogger, + let invoice = crate::utils::create_phantom_invoice_with_description_hash::< + &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 @@ -1257,6 +1148,8 @@ mod test { get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id()); 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()); + expect_channel_ready_event(&nodes[1], &nodes[3].node.get_our_node_id()); + expect_channel_ready_event(&nodes[3], &nodes[1].node.get_our_node_id()); // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the third // channel, the channel will never be assigned any `counterparty.forwarding_info`. @@ -1461,7 +1354,7 @@ mod test { .map(|route_hint| route_hint.phantom_scid) .collect::>(); - let invoice = ::utils::create_phantom_invoice::(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::TestLogger>(invoice_amt, None, "test".to_string(), 3600, phantom_route_hints, &invoice_node.keys_manager, &invoice_node.logger, Currency::BitcoinTestnet).unwrap(); let invoice_hints = invoice.private_routes();