1 //! Convenient utilities to create an invoice.
3 use {CreationError, Currency, DEFAULT_EXPIRY_TIME, Invoice, InvoiceBuilder, SignOrCreationError};
4 use payment::{Payer, Router};
6 use crate::{prelude::*, Description, InvoiceDescription, Sha256};
8 use bitcoin_hashes::{Hash, sha256};
10 use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
11 use lightning::chain::keysinterface::{Recipient, KeysInterface, Sign};
12 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
13 use lightning::ln::channelmanager::{ChannelDetails, ChannelManager, PaymentId, PaymentSendFailure, MIN_FINAL_CLTV_EXPIRY};
14 #[cfg(feature = "std")]
15 use lightning::ln::channelmanager::{PhantomRouteHints, MIN_CLTV_EXPIRY_DELTA};
16 use lightning::ln::msgs::LightningError;
17 use lightning::routing::scoring::Score;
18 use lightning::routing::network_graph::{NetworkGraph, RoutingFees};
19 use lightning::routing::router::{Route, RouteHint, RouteHintHop, RouteParameters, find_route};
20 use lightning::util::logger::Logger;
21 use secp256k1::key::PublicKey;
22 use core::convert::TryInto;
24 use core::time::Duration;
27 #[cfg(feature = "std")]
28 /// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice."
29 /// See [`PhantomKeysManager`] for more information on phantom node payments.
31 /// `phantom_route_hints` parameter:
32 /// * Contains channel info for all nodes participating in the phantom invoice
33 /// * Entries are retrieved from a call to [`ChannelManager::get_phantom_route_hints`] on each
34 /// participating node
35 /// * It is fine to cache `phantom_route_hints` and reuse it across invoices, as long as the data is
36 /// updated when a channel becomes disabled or closes
37 /// * Note that if too many channels are included in [`PhantomRouteHints::channels`], the invoice
38 /// may be too long for QR code scanning. To fix this, `PhantomRouteHints::channels` may be pared
41 /// `payment_hash` and `payment_secret` come from [`ChannelManager::create_inbound_payment`] or
42 /// [`ChannelManager::create_inbound_payment_for_hash`]. These values can be retrieved from any
43 /// participating node.
45 /// Note that the provided `keys_manager`'s `KeysInterface` implementation must support phantom
46 /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
49 /// [`PhantomKeysManager`]: lightning::chain::keysinterface::PhantomKeysManager
50 /// [`ChannelManager::get_phantom_route_hints`]: lightning::ln::channelmanager::ChannelManager::get_phantom_route_hints
51 /// [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels
52 pub fn create_phantom_invoice<Signer: Sign, K: Deref>(
53 amt_msat: Option<u64>, description: String, payment_hash: PaymentHash, payment_secret: PaymentSecret,
54 phantom_route_hints: Vec<PhantomRouteHints>, keys_manager: K, network: Currency,
55 ) -> Result<Invoice, SignOrCreationError<()>> where K::Target: KeysInterface {
56 let description = Description::new(description).map_err(SignOrCreationError::CreationError)?;
57 let description = InvoiceDescription::Direct(&description,);
58 _create_phantom_invoice::<Signer, K>(
59 amt_msat, description, payment_hash, payment_secret, phantom_route_hints, keys_manager, network,
63 #[cfg(feature = "std")]
64 /// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice."
65 /// See [`PhantomKeysManager`] for more information on phantom node payments.
67 /// `phantom_route_hints` parameter:
68 /// * Contains channel info for all nodes participating in the phantom invoice
69 /// * Entries are retrieved from a call to [`ChannelManager::get_phantom_route_hints`] on each
70 /// participating node
71 /// * It is fine to cache `phantom_route_hints` and reuse it across invoices, as long as the data is
72 /// updated when a channel becomes disabled or closes
73 /// * Note that if too many channels are included in [`PhantomRouteHints::channels`], the invoice
74 /// may be too long for QR code scanning. To fix this, `PhantomRouteHints::channels` may be pared
77 /// `description_hash` is a SHA-256 hash of the description text
79 /// `payment_hash` and `payment_secret` come from [`ChannelManager::create_inbound_payment`] or
80 /// [`ChannelManager::create_inbound_payment_for_hash`]. These values can be retrieved from any
81 /// participating node.
83 /// Note that the provided `keys_manager`'s `KeysInterface` implementation must support phantom
84 /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
87 /// [`PhantomKeysManager`]: lightning::chain::keysinterface::PhantomKeysManager
88 /// [`ChannelManager::get_phantom_route_hints`]: lightning::ln::channelmanager::ChannelManager::get_phantom_route_hints
89 /// [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels
90 pub fn create_phantom_invoice_with_description_hash<Signer: Sign, K: Deref>(
91 amt_msat: Option<u64>, description_hash: Sha256, payment_hash: PaymentHash,
92 payment_secret: PaymentSecret, phantom_route_hints: Vec<PhantomRouteHints>,
93 keys_manager: K, network: Currency,
94 ) -> Result<Invoice, SignOrCreationError<()>> where K::Target: KeysInterface
97 _create_phantom_invoice::<Signer, K>(
99 InvoiceDescription::Hash(&description_hash),
100 payment_hash, payment_secret, phantom_route_hints, keys_manager, network,
104 #[cfg(feature = "std")]
105 fn _create_phantom_invoice<Signer: Sign, K: Deref>(
106 amt_msat: Option<u64>, description: InvoiceDescription, payment_hash: PaymentHash,
107 payment_secret: PaymentSecret, phantom_route_hints: Vec<PhantomRouteHints>,
108 keys_manager: K, network: Currency,
109 ) -> Result<Invoice, SignOrCreationError<()>> where K::Target: KeysInterface
111 if phantom_route_hints.len() == 0 {
112 return Err(SignOrCreationError::CreationError(
113 CreationError::MissingRouteHints,
116 let invoice = match description {
117 InvoiceDescription::Direct(description) => {
118 InvoiceBuilder::new(network).description(description.0.clone())
120 InvoiceDescription::Hash(hash) => InvoiceBuilder::new(network).description_hash(hash.0),
123 let mut invoice = invoice
125 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
126 .payment_secret(payment_secret)
127 .min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into());
128 if let Some(amt) = amt_msat {
129 invoice = invoice.amount_milli_satoshis(amt);
132 for PhantomRouteHints { channels, phantom_scid, real_node_pubkey } in phantom_route_hints {
133 let mut route_hints = filter_channels(channels, amt_msat);
135 // If we have any public channel, the route hints from `filter_channels` will be empty.
136 // In that case we create a RouteHint on which we will push a single hop with the phantom
137 // route into the invoice, and let the sender find the path to the `real_node_pubkey`
138 // node by looking at our public channels.
139 if route_hints.is_empty() {
140 route_hints.push(RouteHint(vec![]))
142 for mut route_hint in route_hints {
143 route_hint.0.push(RouteHintHop {
144 src_node_id: real_node_pubkey,
145 short_channel_id: phantom_scid,
148 proportional_millionths: 0,
150 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
151 htlc_minimum_msat: None,
152 htlc_maximum_msat: None,});
153 invoice = invoice.private_route(route_hint.clone());
157 let raw_invoice = match invoice.build_raw() {
159 Err(e) => return Err(SignOrCreationError::CreationError(e))
161 let hrp_str = raw_invoice.hrp.to_string();
162 let hrp_bytes = hrp_str.as_bytes();
163 let data_without_signature = raw_invoice.data.to_base32();
164 let signed_raw_invoice = raw_invoice.sign(|_| keys_manager.sign_invoice(hrp_bytes, &data_without_signature, Recipient::PhantomNode));
165 match signed_raw_invoice {
166 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
167 Err(e) => Err(SignOrCreationError::SignError(e))
171 #[cfg(feature = "std")]
172 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
173 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
174 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
175 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
176 /// that the payment secret is valid when the invoice is paid.
177 pub fn create_invoice_from_channelmanager<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
178 channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
179 amt_msat: Option<u64>, description: String
180 ) -> Result<Invoice, SignOrCreationError<()>>
182 M::Target: chain::Watch<Signer>,
183 T::Target: BroadcasterInterface,
184 K::Target: KeysInterface<Signer = Signer>,
185 F::Target: FeeEstimator,
188 use std::time::SystemTime;
189 let duration = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
190 .expect("for the foreseeable future this shouldn't happen");
191 create_invoice_from_channelmanager_and_duration_since_epoch(
192 channelmanager, keys_manager, network, amt_msat, description, duration
196 #[cfg(feature = "std")]
197 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
198 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
199 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
200 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
201 /// that the payment secret is valid when the invoice is paid.
202 /// Use this variant if you want to pass the `description_hash` to the invoice.
203 pub fn create_invoice_from_channelmanager_with_description_hash<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
204 channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
205 amt_msat: Option<u64>, description_hash: Sha256,
206 ) -> Result<Invoice, SignOrCreationError<()>>
208 M::Target: chain::Watch<Signer>,
209 T::Target: BroadcasterInterface,
210 K::Target: KeysInterface<Signer = Signer>,
211 F::Target: FeeEstimator,
214 use std::time::SystemTime;
216 let duration = SystemTime::now()
217 .duration_since(SystemTime::UNIX_EPOCH)
218 .expect("for the foreseeable future this shouldn't happen");
220 create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
221 channelmanager, keys_manager, network, amt_msat, description_hash, duration,
225 /// See [`create_invoice_from_channelmanager_with_description_hash`]
226 /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
227 /// available and the current time is supplied by the caller.
228 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>(
229 channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
230 amt_msat: Option<u64>, description_hash: Sha256, duration_since_epoch: Duration,
231 ) -> Result<Invoice, SignOrCreationError<()>>
233 M::Target: chain::Watch<Signer>,
234 T::Target: BroadcasterInterface,
235 K::Target: KeysInterface<Signer = Signer>,
236 F::Target: FeeEstimator,
239 _create_invoice_from_channelmanager_and_duration_since_epoch(
240 channelmanager, keys_manager, network, amt_msat,
241 InvoiceDescription::Hash(&description_hash),
242 duration_since_epoch,
246 /// See [`create_invoice_from_channelmanager`]
247 /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
248 /// available and the current time is supplied by the caller.
249 pub fn create_invoice_from_channelmanager_and_duration_since_epoch<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
250 channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
251 amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
252 ) -> Result<Invoice, SignOrCreationError<()>>
254 M::Target: chain::Watch<Signer>,
255 T::Target: BroadcasterInterface,
256 K::Target: KeysInterface<Signer = Signer>,
257 F::Target: FeeEstimator,
260 _create_invoice_from_channelmanager_and_duration_since_epoch(
261 channelmanager, keys_manager, network, amt_msat,
262 InvoiceDescription::Direct(
263 &Description::new(description).map_err(SignOrCreationError::CreationError)?,
265 duration_since_epoch,
269 fn _create_invoice_from_channelmanager_and_duration_since_epoch<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
270 channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
271 amt_msat: Option<u64>, description: InvoiceDescription, duration_since_epoch: Duration,
272 ) -> Result<Invoice, SignOrCreationError<()>>
274 M::Target: chain::Watch<Signer>,
275 T::Target: BroadcasterInterface,
276 K::Target: KeysInterface<Signer = Signer>,
277 F::Target: FeeEstimator,
280 let route_hints = filter_channels(channelmanager.list_usable_channels(), amt_msat);
282 // `create_inbound_payment` only returns an error if the amount is greater than the total bitcoin
284 let (payment_hash, payment_secret) = channelmanager
285 .create_inbound_payment(amt_msat, DEFAULT_EXPIRY_TIME.try_into().unwrap())
286 .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
287 let our_node_pubkey = channelmanager.get_our_node_id();
289 let invoice = match description {
290 InvoiceDescription::Direct(description) => {
291 InvoiceBuilder::new(network).description(description.0.clone())
293 InvoiceDescription::Hash(hash) => InvoiceBuilder::new(network).description_hash(hash.0),
296 let mut invoice = invoice
297 .duration_since_epoch(duration_since_epoch)
298 .payee_pub_key(our_node_pubkey)
299 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
300 .payment_secret(payment_secret)
302 .min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into());
303 if let Some(amt) = amt_msat {
304 invoice = invoice.amount_milli_satoshis(amt);
306 for hint in route_hints {
307 invoice = invoice.private_route(hint);
310 let raw_invoice = match invoice.build_raw() {
312 Err(e) => return Err(SignOrCreationError::CreationError(e))
314 let hrp_str = raw_invoice.hrp.to_string();
315 let hrp_bytes = hrp_str.as_bytes();
316 let data_without_signature = raw_invoice.data.to_base32();
317 let signed_raw_invoice = raw_invoice.sign(|_| keys_manager.sign_invoice(hrp_bytes, &data_without_signature, Recipient::Node));
318 match signed_raw_invoice {
319 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
320 Err(e) => Err(SignOrCreationError::SignError(e))
324 /// Filters the `channels` for an invoice, and returns the corresponding `RouteHint`s to include
327 /// The filtering is based on the following criteria:
328 /// * Only one channel per counterparty node
329 /// * Always select the channel with the highest inbound capacity per counterparty node
330 /// * Filter out channels with a lower inbound capacity than `min_inbound_capacity_msat`, if any
331 /// channel with a higher or equal inbound capacity than `min_inbound_capacity_msat` exists
332 /// * If any public channel exists, the returned `RouteHint`s will be empty, and the sender will
333 /// need to find the path by looking at the public channels instead
334 fn filter_channels(channels: Vec<ChannelDetails>, min_inbound_capacity_msat: Option<u64>) -> Vec<RouteHint>{
335 let mut filtered_channels: HashMap<PublicKey, &ChannelDetails> = HashMap::new();
336 let min_inbound_capacity = min_inbound_capacity_msat.unwrap_or(0);
337 let mut min_capacity_channel_exists = false;
339 for channel in channels.iter() {
340 if channel.get_inbound_payment_scid().is_none() || channel.counterparty.forwarding_info.is_none() {
344 if channel.is_public {
345 // If any public channel exists, return no hints and let the sender
346 // look at the public channels instead.
350 if channel.inbound_capacity_msat >= min_inbound_capacity {
351 min_capacity_channel_exists = true;
353 match filtered_channels.entry(channel.counterparty.node_id) {
354 hash_map::Entry::Occupied(mut entry) => {
355 let current_max_capacity = entry.get().inbound_capacity_msat;
356 if channel.inbound_capacity_msat < current_max_capacity {
359 entry.insert(channel);
361 hash_map::Entry::Vacant(entry) => {
362 entry.insert(channel);
367 let route_hint_from_channel = |channel: &ChannelDetails| {
368 let forwarding_info = channel.counterparty.forwarding_info.as_ref().unwrap();
369 RouteHint(vec![RouteHintHop {
370 src_node_id: channel.counterparty.node_id,
371 short_channel_id: channel.get_inbound_payment_scid().unwrap(),
373 base_msat: forwarding_info.fee_base_msat,
374 proportional_millionths: forwarding_info.fee_proportional_millionths,
376 cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
377 htlc_minimum_msat: None,
378 htlc_maximum_msat: None,}])
380 // If all channels are private, return the route hint for the highest inbound capacity channel
381 // per counterparty node. If channels with an higher inbound capacity than the
382 // min_inbound_capacity exists, filter out the channels with a lower capacity than that.
383 filtered_channels.into_iter()
384 .filter(|(_counterparty_id, channel)| {
385 min_capacity_channel_exists && channel.inbound_capacity_msat >= min_inbound_capacity ||
386 !min_capacity_channel_exists
388 .map(|(_counterparty_id, channel)| route_hint_from_channel(&channel))
389 .collect::<Vec<RouteHint>>()
392 /// A [`Router`] implemented using [`find_route`].
393 pub struct DefaultRouter<G: Deref<Target = NetworkGraph>, L: Deref> where L::Target: Logger {
396 random_seed_bytes: Mutex<[u8; 32]>,
399 impl<G: Deref<Target = NetworkGraph>, L: Deref> DefaultRouter<G, L> where L::Target: Logger {
400 /// Creates a new router using the given [`NetworkGraph`], a [`Logger`], and a randomness source
401 /// `random_seed_bytes`.
402 pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32]) -> Self {
403 let random_seed_bytes = Mutex::new(random_seed_bytes);
404 Self { network_graph, logger, random_seed_bytes }
408 impl<G: Deref<Target = NetworkGraph>, L: Deref, S: Score> Router<S> for DefaultRouter<G, L>
409 where L::Target: Logger {
411 &self, payer: &PublicKey, params: &RouteParameters, _payment_hash: &PaymentHash,
412 first_hops: Option<&[&ChannelDetails]>, scorer: &S
413 ) -> Result<Route, LightningError> {
414 let random_seed_bytes = {
415 let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
416 *locked_random_seed_bytes = sha256::Hash::hash(&*locked_random_seed_bytes).into_inner();
417 *locked_random_seed_bytes
419 find_route(payer, params, &*self.network_graph, first_hops, &*self.logger, scorer, &random_seed_bytes)
423 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Payer for ChannelManager<Signer, M, T, K, F, L>
425 M::Target: chain::Watch<Signer>,
426 T::Target: BroadcasterInterface,
427 K::Target: KeysInterface<Signer = Signer>,
428 F::Target: FeeEstimator,
431 fn node_id(&self) -> PublicKey {
432 self.get_our_node_id()
435 fn first_hops(&self) -> Vec<ChannelDetails> {
436 self.list_usable_channels()
440 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
441 ) -> Result<PaymentId, PaymentSendFailure> {
442 self.send_payment(route, payment_hash, payment_secret)
445 fn send_spontaneous_payment(
446 &self, route: &Route, payment_preimage: PaymentPreimage,
447 ) -> Result<PaymentId, PaymentSendFailure> {
448 self.send_spontaneous_payment(route, Some(payment_preimage))
449 .map(|(_, payment_id)| payment_id)
453 &self, route: &Route, payment_id: PaymentId
454 ) -> Result<(), PaymentSendFailure> {
455 self.retry_payment(route, payment_id)
458 fn abandon_payment(&self, payment_id: PaymentId) {
459 self.abandon_payment(payment_id)
465 use core::time::Duration;
466 use {Currency, Description, InvoiceDescription};
467 use bitcoin_hashes::Hash;
468 use bitcoin_hashes::sha256::Hash as Sha256;
469 use lightning::chain::keysinterface::PhantomKeysManager;
470 use lightning::ln::{PaymentPreimage, PaymentHash};
471 use lightning::ln::channelmanager::{PhantomRouteHints, MIN_FINAL_CLTV_EXPIRY};
472 use lightning::ln::functional_test_utils::*;
473 use lightning::ln::features::InitFeatures;
474 use lightning::ln::msgs::ChannelMessageHandler;
475 use lightning::routing::router::{PaymentParameters, RouteParameters, find_route};
476 use lightning::util::enforcing_trait_impls::EnforcingSigner;
477 use lightning::util::events::{MessageSendEvent, MessageSendEventsProvider, Event};
478 use lightning::util::test_utils;
479 use lightning::util::config::UserConfig;
480 use lightning::chain::keysinterface::KeysInterface;
481 use utils::create_invoice_from_channelmanager_and_duration_since_epoch;
482 use std::collections::HashSet;
485 fn test_from_channelmanager() {
486 let chanmon_cfgs = create_chanmon_cfgs(2);
487 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
488 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
489 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
490 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
491 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
492 &nodes[1].node, nodes[1].keys_manager, Currency::BitcoinTestnet, Some(10_000), "test".to_string(),
493 Duration::from_secs(1234567)).unwrap();
494 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
495 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
496 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
498 // Invoice SCIDs should always use inbound SCID aliases over the real channel ID, if one is
500 assert_eq!(invoice.route_hints().len(), 1);
501 assert_eq!(invoice.route_hints()[0].0.len(), 1);
502 assert_eq!(invoice.route_hints()[0].0[0].short_channel_id,
503 nodes[1].node.list_usable_channels()[0].inbound_scid_alias.unwrap());
505 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
506 .with_features(invoice.features().unwrap().clone())
507 .with_route_hints(invoice.route_hints());
508 let route_params = RouteParameters {
510 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
511 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
513 let first_hops = nodes[0].node.list_usable_channels();
514 let network_graph = node_cfgs[0].network_graph;
515 let logger = test_utils::TestLogger::new();
516 let scorer = test_utils::TestScorer::with_penalty(0);
517 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
518 let route = find_route(
519 &nodes[0].node.get_our_node_id(), &route_params, network_graph,
520 Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
523 let payment_event = {
524 let mut payment_hash = PaymentHash([0; 32]);
525 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
526 nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
527 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
528 assert_eq!(added_monitors.len(), 1);
529 added_monitors.clear();
531 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
532 assert_eq!(events.len(), 1);
533 SendEvent::from_event(events.remove(0))
536 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
537 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
538 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
539 assert_eq!(added_monitors.len(), 1);
540 added_monitors.clear();
541 let events = nodes[1].node.get_and_clear_pending_msg_events();
542 assert_eq!(events.len(), 2);
546 fn test_create_invoice_with_description_hash() {
547 let chanmon_cfgs = create_chanmon_cfgs(2);
548 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
549 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
550 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
551 let description_hash = crate::Sha256(Hash::hash("Testing description_hash".as_bytes()));
552 let invoice = ::utils::create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
553 &nodes[1].node, nodes[1].keys_manager, Currency::BitcoinTestnet, Some(10_000),
554 description_hash, Duration::from_secs(1234567),
556 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
557 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
558 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Testing description_hash".as_bytes()))));
562 fn test_hints_includes_single_channels_to_nodes() {
563 let chanmon_cfgs = create_chanmon_cfgs(3);
564 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
565 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
566 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
568 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
569 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
571 let mut scid_aliases = HashSet::new();
572 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
573 scid_aliases.insert(chan_2_0.0.short_channel_id_alias.unwrap());
575 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
579 fn test_hints_has_only_highest_inbound_capacity_channel() {
580 let chanmon_cfgs = create_chanmon_cfgs(2);
581 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
582 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
583 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
584 let _chan_1_0_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0, InitFeatures::known(), InitFeatures::known());
585 let chan_1_0_high_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000_000, 0, InitFeatures::known(), InitFeatures::known());
586 let _chan_1_0_medium_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
588 let mut scid_aliases = HashSet::new();
589 scid_aliases.insert(chan_1_0_high_inbound_capacity.0.short_channel_id_alias.unwrap());
591 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
595 fn test_forwarding_info_not_assigned_channel_excluded_from_hints() {
596 let chanmon_cfgs = create_chanmon_cfgs(3);
597 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
598 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
599 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
600 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
602 // Create an unannonced channel between `nodes[2]` and `nodes[0]`, for which the
603 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
604 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
605 let mut private_chan_cfg = UserConfig::default();
606 private_chan_cfg.channel_options.announced_channel = false;
607 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();
608 let open_channel = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
609 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &open_channel);
610 let accept_channel = get_event_msg!(nodes[0], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id());
611 nodes[2].node.handle_accept_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
613 let tx = sign_funding_transaction(&nodes[2], &nodes[0], 1_000_000, temporary_channel_id);
615 let conf_height = core::cmp::max(nodes[2].best_block_info().1 + 1, nodes[0].best_block_info().1 + 1);
616 confirm_transaction_at(&nodes[2], &tx, conf_height);
617 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
618 confirm_transaction_at(&nodes[0], &tx, conf_height);
619 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH - 1);
620 let as_funding_locked = get_event_msg!(nodes[2], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id());
621 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()));
622 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
623 nodes[0].node.handle_funding_locked(&nodes[2].node.get_our_node_id(), &as_funding_locked);
624 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
626 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the second
627 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
628 // Therefore only `chan_1_0` should be included in the hints.
629 let mut scid_aliases = HashSet::new();
630 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
631 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
635 fn test_no_hints_if_a_mix_between_public_and_private_channel_exists() {
636 let chanmon_cfgs = create_chanmon_cfgs(3);
637 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
638 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
639 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
640 let _chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
642 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
643 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
644 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
646 // Ensure that the invoice doesn't include any route hints for any of `nodes[0]` channels,
647 // even though all channels between `nodes[1]` and `nodes[0]` are private, as there is a
648 // public channel between `nodes[2]` and `nodes[0]`
649 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
653 fn test_only_public_channels_includes_no_channels_in_hints() {
654 let chanmon_cfgs = create_chanmon_cfgs(3);
655 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
656 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
657 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
658 let chan_1_0 = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
659 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_1_0.0);
660 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_1_0.1);
662 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
663 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
664 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
666 // As all of `nodes[0]` channels are public, no channels should be included in the hints
667 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
671 fn test_channels_with_lower_inbound_capacity_than_invoice_amt_hints_filtering() {
672 let chanmon_cfgs = create_chanmon_cfgs(3);
673 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
674 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
675 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
676 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0, InitFeatures::known(), InitFeatures::known());
677 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
679 // As the invoice amt is 1 msat above chan_1_0's inbound capacity, it shouldn't be included
680 let mut scid_aliases_99_000_001_msat = HashSet::new();
681 scid_aliases_99_000_001_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
683 match_invoice_routes(Some(99_000_001), &nodes[0], scid_aliases_99_000_001_msat);
685 // As the invoice amt is exactly at chan_1_0's inbound capacity, it should be included
686 let mut scid_aliases_99_000_000_msat = HashSet::new();
687 scid_aliases_99_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
688 scid_aliases_99_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
690 match_invoice_routes(Some(99_000_000), &nodes[0], scid_aliases_99_000_000_msat);
692 // As the invoice amt is above all channels' inbound capacity, they will still be included
693 let mut scid_aliases_2_000_000_000_msat = HashSet::new();
694 scid_aliases_2_000_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
695 scid_aliases_2_000_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
697 match_invoice_routes(Some(2_000_000_000), &nodes[0], scid_aliases_2_000_000_000_msat);
699 // An invoice with no specified amount should include all channels in the route hints.
700 let mut scid_aliases_no_specified_amount = HashSet::new();
701 scid_aliases_no_specified_amount.insert(chan_1_0.0.short_channel_id_alias.unwrap());
702 scid_aliases_no_specified_amount.insert(chan_2_0.0.short_channel_id_alias.unwrap());
704 match_invoice_routes(None, &nodes[0], scid_aliases_no_specified_amount);
707 fn match_invoice_routes<'a, 'b: 'a, 'c: 'b>(
708 invoice_amt: Option<u64>,
709 invoice_node: &Node<'a, 'b, 'c>,
710 mut chan_ids_to_match: HashSet<u64>
712 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
713 &invoice_node.node, invoice_node.keys_manager, Currency::BitcoinTestnet, invoice_amt, "test".to_string(),
714 Duration::from_secs(1234567)).unwrap();
715 let hints = invoice.private_routes();
718 let hint_short_chan_id = (hint.0).0[0].short_channel_id;
719 assert!(chan_ids_to_match.remove(&hint_short_chan_id));
721 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
725 #[cfg(feature = "std")]
726 fn test_multi_node_receive() {
727 do_test_multi_node_receive(true);
728 do_test_multi_node_receive(false);
731 #[cfg(feature = "std")]
732 fn do_test_multi_node_receive(user_generated_pmt_hash: bool) {
733 let mut chanmon_cfgs = create_chanmon_cfgs(3);
734 let seed_1 = [42 as u8; 32];
735 let seed_2 = [43 as u8; 32];
736 let cross_node_seed = [44 as u8; 32];
737 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
738 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
739 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
740 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
741 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
742 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
743 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_0_1.1);
744 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_1.0);
745 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
746 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
747 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
749 let payment_amt = 10_000;
750 let (payment_preimage, payment_hash, payment_secret) = {
751 if user_generated_pmt_hash {
752 let payment_preimage = PaymentPreimage([1; 32]);
753 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
754 let payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(payment_amt), 3600).unwrap();
755 (payment_preimage, payment_hash, payment_secret)
757 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(payment_amt), 3600).unwrap();
758 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
759 (payment_preimage, payment_hash, payment_secret)
762 let route_hints = vec![
763 nodes[1].node.get_phantom_route_hints(),
764 nodes[2].node.get_phantom_route_hints(),
766 let invoice = ::utils::create_phantom_invoice::<EnforcingSigner, &test_utils::TestKeysInterface>(Some(payment_amt), "test".to_string(), payment_hash, payment_secret, route_hints, &nodes[1].keys_manager, Currency::BitcoinTestnet).unwrap();
768 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
769 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
770 assert_eq!(invoice.route_hints().len(), 2);
771 assert!(!invoice.features().unwrap().supports_basic_mpp());
773 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
774 .with_features(invoice.features().unwrap().clone())
775 .with_route_hints(invoice.route_hints());
776 let params = RouteParameters {
778 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
779 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
781 let first_hops = nodes[0].node.list_usable_channels();
782 let network_graph = node_cfgs[0].network_graph;
783 let logger = test_utils::TestLogger::new();
784 let scorer = test_utils::TestScorer::with_penalty(0);
785 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
786 let route = find_route(
787 &nodes[0].node.get_our_node_id(), ¶ms, network_graph,
788 Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
790 let (payment_event, fwd_idx) = {
791 let mut payment_hash = PaymentHash([0; 32]);
792 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
793 nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
794 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
795 assert_eq!(added_monitors.len(), 1);
796 added_monitors.clear();
798 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
799 assert_eq!(events.len(), 1);
800 let fwd_idx = match events[0] {
801 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
802 if node_id == nodes[1].node.get_our_node_id() {
806 _ => panic!("Unexpected event")
808 (SendEvent::from_event(events.remove(0)), fwd_idx)
810 nodes[fwd_idx].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
811 commitment_signed_dance!(nodes[fwd_idx], nodes[0], &payment_event.commitment_msg, false, true);
813 // Note that we have to "forward pending HTLCs" twice before we see the PaymentReceived as
814 // this "emulates" the payment taking two hops, providing some privacy to make phantom node
815 // payments "look real" by taking more time.
816 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
817 nodes[fwd_idx].node.process_pending_htlc_forwards();
818 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
819 nodes[fwd_idx].node.process_pending_htlc_forwards();
821 let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) };
822 expect_payment_received!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt);
823 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[fwd_idx])[..]), false, payment_preimage);
824 let events = nodes[0].node.get_and_clear_pending_events();
825 assert_eq!(events.len(), 2);
827 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
828 assert_eq!(payment_preimage, *ev_preimage);
829 assert_eq!(payment_hash, *ev_hash);
830 assert_eq!(fee_paid_msat, &Some(0));
832 _ => panic!("Unexpected event")
835 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
836 assert_eq!(hash, Some(payment_hash));
838 _ => panic!("Unexpected event")
843 #[cfg(feature = "std")]
844 fn create_phantom_invoice_with_description_hash() {
845 let chanmon_cfgs = create_chanmon_cfgs(3);
846 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
847 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
848 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
850 let payment_amt = 20_000;
851 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(payment_amt), 3600).unwrap();
852 let route_hints = vec![
853 nodes[1].node.get_phantom_route_hints(),
854 nodes[2].node.get_phantom_route_hints(),
857 let description_hash = crate::Sha256(Hash::hash("Description hash phantom invoice".as_bytes()));
858 let invoice = ::utils::create_phantom_invoice_with_description_hash::<EnforcingSigner,&test_utils::TestKeysInterface>(Some(payment_amt), description_hash, payment_hash, payment_secret, route_hints, &nodes[1].keys_manager, Currency::BitcoinTestnet).unwrap();
860 assert_eq!(invoice.amount_pico_btc(), Some(200_000));
861 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
862 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Description hash phantom invoice".as_bytes()))));
866 #[cfg(feature = "std")]
867 fn test_multi_node_hints_includes_single_channels_to_participating_nodes() {
868 let mut chanmon_cfgs = create_chanmon_cfgs(3);
869 let seed_1 = [42 as u8; 32];
870 let seed_2 = [43 as u8; 32];
871 let cross_node_seed = [44 as u8; 32];
872 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
873 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
874 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
875 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
876 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
878 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
879 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
881 let mut scid_aliases = HashSet::new();
882 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
883 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
885 match_multi_node_invoice_routes(
888 vec![&nodes[1], &nodes[2],],
895 #[cfg(feature = "std")]
896 fn test_multi_node_hints_includes_one_channel_of_each_counterparty_nodes_per_participating_node() {
897 let mut chanmon_cfgs = create_chanmon_cfgs(4);
898 let seed_1 = [42 as u8; 32];
899 let seed_2 = [43 as u8; 32];
900 let cross_node_seed = [44 as u8; 32];
901 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
902 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
903 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
904 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
905 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
907 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
908 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001, InitFeatures::known(), InitFeatures::known());
909 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 3_000_000, 10005, InitFeatures::known(), InitFeatures::known());
911 let mut scid_aliases = HashSet::new();
912 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
913 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
914 scid_aliases.insert(chan_1_3.0.short_channel_id_alias.unwrap());
916 match_multi_node_invoice_routes(
919 vec![&nodes[2], &nodes[3],],
926 #[cfg(feature = "std")]
927 fn test_multi_node_forwarding_info_not_assigned_channel_excluded_from_hints() {
928 let mut chanmon_cfgs = create_chanmon_cfgs(4);
929 let seed_1 = [42 as u8; 32];
930 let seed_2 = [43 as u8; 32];
931 let cross_node_seed = [44 as u8; 32];
932 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
933 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
934 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
935 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
936 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
938 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
939 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001, InitFeatures::known(), InitFeatures::known());
941 // Create an unannonced channel between `nodes[1]` and `nodes[3]`, for which the
942 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
943 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
944 let mut private_chan_cfg = UserConfig::default();
945 private_chan_cfg.channel_options.announced_channel = false;
946 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();
947 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[3].node.get_our_node_id());
948 nodes[3].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
949 let accept_channel = get_event_msg!(nodes[3], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
950 nodes[1].node.handle_accept_channel(&nodes[3].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
952 let tx = sign_funding_transaction(&nodes[1], &nodes[3], 1_000_000, temporary_channel_id);
954 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[3].best_block_info().1 + 1);
955 confirm_transaction_at(&nodes[1], &tx, conf_height);
956 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
957 confirm_transaction_at(&nodes[3], &tx, conf_height);
958 connect_blocks(&nodes[3], CHAN_CONFIRM_DEPTH - 1);
959 let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[3].node.get_our_node_id());
960 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()));
961 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
962 nodes[3].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
963 get_event_msg!(nodes[3], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
965 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the third
966 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
967 // Therefore only `chan_0_3` should be included in the hints for `nodes[3]`.
968 let mut scid_aliases = HashSet::new();
969 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
970 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
972 match_multi_node_invoice_routes(
975 vec![&nodes[2], &nodes[3],],
982 #[cfg(feature = "std")]
983 fn test_multi_node_with_only_public_channels_hints_includes_only_phantom_route() {
984 let mut chanmon_cfgs = create_chanmon_cfgs(3);
985 let seed_1 = [42 as u8; 32];
986 let seed_2 = [43 as u8; 32];
987 let cross_node_seed = [44 as u8; 32];
988 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
989 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
990 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
991 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
992 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
994 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
996 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
997 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
998 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
1000 // Hints should include `chan_0_1` from as `nodes[1]` only have private channels, but not
1001 // `chan_0_2` as `nodes[2]` only has public channels.
1002 let mut scid_aliases = HashSet::new();
1003 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1005 match_multi_node_invoice_routes(
1008 vec![&nodes[1], &nodes[2],],
1015 #[cfg(feature = "std")]
1016 fn test_multi_node_with_mixed_public_and_private_channel_hints_includes_only_phantom_route() {
1017 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1018 let seed_1 = [42 as u8; 32];
1019 let seed_2 = [43 as u8; 32];
1020 let cross_node_seed = [44 as u8; 32];
1021 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1022 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1023 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1024 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1025 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1027 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
1028 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
1029 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
1030 let _chan_1_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
1032 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100000, 10001, InitFeatures::known(), InitFeatures::known());
1034 // Hints should include `chan_0_3` from as `nodes[3]` only have private channels, and no
1035 // channels for `nodes[2]` as it contains a mix of public and private channels.
1036 let mut scid_aliases = HashSet::new();
1037 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1039 match_multi_node_invoice_routes(
1042 vec![&nodes[2], &nodes[3],],
1049 #[cfg(feature = "std")]
1050 fn test_multi_node_hints_has_only_highest_inbound_capacity_channel() {
1051 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1052 let seed_1 = [42 as u8; 32];
1053 let seed_2 = [43 as u8; 32];
1054 let cross_node_seed = [44 as u8; 32];
1055 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1056 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1057 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1058 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1059 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1061 let _chan_0_1_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
1062 let chan_0_1_high_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0, InitFeatures::known(), InitFeatures::known());
1063 let _chan_0_1_medium_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1064 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
1066 let mut scid_aliases = HashSet::new();
1067 scid_aliases.insert(chan_0_1_high_inbound_capacity.0.short_channel_id_alias.unwrap());
1068 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1070 match_multi_node_invoice_routes(
1073 vec![&nodes[1], &nodes[2],],
1080 #[cfg(feature = "std")]
1081 fn test_multi_node_channels_inbound_capacity_lower_than_invoice_amt_filtering() {
1082 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1083 let seed_1 = [42 as u8; 32];
1084 let seed_2 = [43 as u8; 32];
1085 let cross_node_seed = [44 as u8; 32];
1086 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1087 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1088 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1089 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1090 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1092 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1093 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
1094 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 200_000, 0, InitFeatures::known(), InitFeatures::known());
1096 // Since the invoice 1 msat above chan_0_3's inbound capacity, it should be filtered out.
1097 let mut scid_aliases_99_000_001_msat = HashSet::new();
1098 scid_aliases_99_000_001_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1099 scid_aliases_99_000_001_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1101 match_multi_node_invoice_routes(
1104 vec![&nodes[2], &nodes[3],],
1105 scid_aliases_99_000_001_msat,
1109 // Since the invoice is exactly at chan_0_3's inbound capacity, it should be included.
1110 let mut scid_aliases_99_000_000_msat = HashSet::new();
1111 scid_aliases_99_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1112 scid_aliases_99_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1113 scid_aliases_99_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1115 match_multi_node_invoice_routes(
1118 vec![&nodes[2], &nodes[3],],
1119 scid_aliases_99_000_000_msat,
1123 // Since the invoice is above all of `nodes[2]` channels' inbound capacity, all of
1124 // `nodes[2]` them should be included.
1125 let mut scid_aliases_300_000_000_msat = HashSet::new();
1126 scid_aliases_300_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1127 scid_aliases_300_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1128 scid_aliases_300_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1130 match_multi_node_invoice_routes(
1133 vec![&nodes[2], &nodes[3],],
1134 scid_aliases_300_000_000_msat,
1138 // Since the no specified amount, all channels should included.
1139 let mut scid_aliases_no_specified_amount = HashSet::new();
1140 scid_aliases_no_specified_amount.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1141 scid_aliases_no_specified_amount.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1142 scid_aliases_no_specified_amount.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1144 match_multi_node_invoice_routes(
1147 vec![&nodes[2], &nodes[3],],
1148 scid_aliases_no_specified_amount,
1153 #[cfg(feature = "std")]
1154 fn match_multi_node_invoice_routes<'a, 'b: 'a, 'c: 'b>(
1155 invoice_amt: Option<u64>,
1156 invoice_node: &Node<'a, 'b, 'c>,
1157 network_multi_nodes: Vec<&Node<'a, 'b, 'c>>,
1158 mut chan_ids_to_match: HashSet<u64>,
1159 nodes_contains_public_channels: bool
1161 let (payment_hash, payment_secret) = invoice_node.node.create_inbound_payment(invoice_amt, 3600).unwrap();
1162 let phantom_route_hints = network_multi_nodes.iter()
1163 .map(|node| node.node.get_phantom_route_hints())
1164 .collect::<Vec<PhantomRouteHints>>();
1165 let phantom_scids = phantom_route_hints.iter()
1166 .map(|route_hint| route_hint.phantom_scid)
1167 .collect::<HashSet<u64>>();
1169 let invoice = ::utils::create_phantom_invoice::<EnforcingSigner, &test_utils::TestKeysInterface>(invoice_amt, "test".to_string(), payment_hash, payment_secret, phantom_route_hints, &invoice_node.keys_manager, Currency::BitcoinTestnet).unwrap();
1171 let invoice_hints = invoice.private_routes();
1173 for hint in invoice_hints {
1174 let hints = &(hint.0).0;
1177 assert!(nodes_contains_public_channels);
1178 let phantom_scid = hints[0].short_channel_id;
1179 assert!(phantom_scids.contains(&phantom_scid));
1182 let hint_short_chan_id = hints[0].short_channel_id;
1183 assert!(chan_ids_to_match.remove(&hint_short_chan_id));
1184 let phantom_scid = hints[1].short_channel_id;
1185 assert!(phantom_scids.contains(&phantom_scid));
1187 _ => panic!("Incorrect hint length generated")
1190 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);