1ea7c9712d096c242460215f14a6faf204506306
[rust-lightning] / lightning-invoice / src / utils.rs
1 //! Convenient utilities to create an invoice.
2
3 use {CreationError, Currency, DEFAULT_EXPIRY_TIME, Invoice, InvoiceBuilder, SignOrCreationError};
4 use payment::{Payer, Router};
5
6 use bech32::ToBase32;
7 use bitcoin_hashes::{Hash, sha256};
8 use crate::prelude::*;
9 use lightning::chain;
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;
23 use core::ops::Deref;
24 use core::time::Duration;
25 use sync::Mutex;
26
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.
30 ///
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
39 ///   down
40 ///
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.
44 ///
45 /// Note that the provided `keys_manager`'s `KeysInterface` implementation must support phantom
46 /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
47 /// requirement).
48 ///
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:
54         PaymentSecret, phantom_route_hints: Vec<PhantomRouteHints>, keys_manager: K, network: Currency
55 ) -> Result<Invoice, SignOrCreationError<()>> where K::Target: KeysInterface {
56         if phantom_route_hints.len() == 0 {
57                 return Err(SignOrCreationError::CreationError(CreationError::MissingRouteHints))
58         }
59         let mut invoice = InvoiceBuilder::new(network)
60                 .description(description)
61                 .current_timestamp()
62                 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
63                 .payment_secret(payment_secret)
64                 .min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into());
65         if let Some(amt) = amt_msat {
66                 invoice = invoice.amount_milli_satoshis(amt);
67         }
68
69         for hint in phantom_route_hints {
70                 for channel in &hint.channels {
71                         let short_channel_id = match channel.get_inbound_payment_scid() {
72                                 Some(id) => id,
73                                 None => continue,
74                         };
75                         let forwarding_info = match &channel.counterparty.forwarding_info {
76                                 Some(info) => info.clone(),
77                                 None => continue,
78                         };
79                         invoice = invoice.private_route(RouteHint(vec![
80                                         RouteHintHop {
81                                                 src_node_id: channel.counterparty.node_id,
82                                                 short_channel_id,
83                                                 fees: RoutingFees {
84                                                         base_msat: forwarding_info.fee_base_msat,
85                                                         proportional_millionths: forwarding_info.fee_proportional_millionths,
86                                                 },
87                                                 cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
88                                                 htlc_minimum_msat: None,
89                                                 htlc_maximum_msat: None,
90                                         },
91                                         RouteHintHop {
92                                                 src_node_id: hint.real_node_pubkey,
93                                                 short_channel_id: hint.phantom_scid,
94                                                 fees: RoutingFees {
95                                                         base_msat: 0,
96                                                         proportional_millionths: 0,
97                                                 },
98                                                 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
99                                                 htlc_minimum_msat: None,
100                                                 htlc_maximum_msat: None,
101                                         }])
102                         );
103                 }
104         }
105
106         let raw_invoice = match invoice.build_raw() {
107                 Ok(inv) => inv,
108                 Err(e) => return Err(SignOrCreationError::CreationError(e))
109         };
110         let hrp_str = raw_invoice.hrp.to_string();
111         let hrp_bytes = hrp_str.as_bytes();
112         let data_without_signature = raw_invoice.data.to_base32();
113         let signed_raw_invoice = raw_invoice.sign(|_| keys_manager.sign_invoice(hrp_bytes, &data_without_signature, Recipient::PhantomNode));
114         match signed_raw_invoice {
115                 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
116                 Err(e) => Err(SignOrCreationError::SignError(e))
117         }
118 }
119
120 #[cfg(feature = "std")]
121 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
122 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
123 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
124 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
125 /// that the payment secret is valid when the invoice is paid.
126 pub fn create_invoice_from_channelmanager<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
127         channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
128         amt_msat: Option<u64>, description: String
129 ) -> Result<Invoice, SignOrCreationError<()>>
130 where
131         M::Target: chain::Watch<Signer>,
132         T::Target: BroadcasterInterface,
133         K::Target: KeysInterface<Signer = Signer>,
134         F::Target: FeeEstimator,
135         L::Target: Logger,
136 {
137         use std::time::SystemTime;
138         let duration = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
139                 .expect("for the foreseeable future this shouldn't happen");
140         create_invoice_from_channelmanager_and_duration_since_epoch(
141                 channelmanager,
142                 keys_manager,
143                 network,
144                 amt_msat,
145                 description,
146                 duration
147         )
148 }
149
150 /// See [`create_invoice_from_channelmanager`]
151 /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
152 /// available and the current time is supplied by the caller.
153 pub fn create_invoice_from_channelmanager_and_duration_since_epoch<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
154         channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
155         amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
156 ) -> Result<Invoice, SignOrCreationError<()>>
157 where
158         M::Target: chain::Watch<Signer>,
159         T::Target: BroadcasterInterface,
160         K::Target: KeysInterface<Signer = Signer>,
161         F::Target: FeeEstimator,
162         L::Target: Logger,
163 {
164         let route_hints = filter_channels(channelmanager.list_usable_channels(), amt_msat);
165
166         // `create_inbound_payment` only returns an error if the amount is greater than the total bitcoin
167         // supply.
168         let (payment_hash, payment_secret) = channelmanager.create_inbound_payment(
169                 amt_msat, DEFAULT_EXPIRY_TIME.try_into().unwrap())
170                 .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
171         let our_node_pubkey = channelmanager.get_our_node_id();
172         let mut invoice = InvoiceBuilder::new(network)
173                 .description(description)
174                 .duration_since_epoch(duration_since_epoch)
175                 .payee_pub_key(our_node_pubkey)
176                 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
177                 .payment_secret(payment_secret)
178                 .basic_mpp()
179                 .min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into());
180         if let Some(amt) = amt_msat {
181                 invoice = invoice.amount_milli_satoshis(amt);
182         }
183         for hint in route_hints {
184                 invoice = invoice.private_route(hint);
185         }
186
187         let raw_invoice = match invoice.build_raw() {
188                 Ok(inv) => inv,
189                 Err(e) => return Err(SignOrCreationError::CreationError(e))
190         };
191         let hrp_str = raw_invoice.hrp.to_string();
192         let hrp_bytes = hrp_str.as_bytes();
193         let data_without_signature = raw_invoice.data.to_base32();
194         let signed_raw_invoice = raw_invoice.sign(|_| keys_manager.sign_invoice(hrp_bytes, &data_without_signature, Recipient::Node));
195         match signed_raw_invoice {
196                 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
197                 Err(e) => Err(SignOrCreationError::SignError(e))
198         }
199 }
200
201 /// Filters the `channels` for an invoice, and returns the corresponding `RouteHint`s to include
202 /// in the invoice.
203 ///
204 /// The filtering is based on the following criteria:
205 /// * Only one channel per counterparty node
206 /// * Always select the channel with the highest inbound capacity per counterparty node
207 /// * Filter out channels with a lower inbound capacity than `min_inbound_capacity_msat`, if any
208 /// channel with a higher or equal inbound capacity than `min_inbound_capacity_msat` exists
209 /// * If any public channel exists, the returned `RouteHint`s will be empty, and the sender will
210 /// need to find the path by looking at the public channels instead
211 fn filter_channels(channels: Vec<ChannelDetails>, min_inbound_capacity_msat: Option<u64>) -> Vec<RouteHint>{
212         let mut filtered_channels: HashMap<PublicKey, &ChannelDetails> = HashMap::new();
213         let min_inbound_capacity = min_inbound_capacity_msat.unwrap_or(0);
214         let mut min_capacity_channel_exists = false;
215
216         for channel in channels.iter() {
217                 if channel.get_inbound_payment_scid().is_none() || channel.counterparty.forwarding_info.is_none() {
218                         continue;
219                 }
220
221                 if channel.is_public {
222                         // If any public channel exists, return no hints and let the sender
223                         // look at the public channels instead.
224                         return vec![]
225                 }
226
227                 if channel.inbound_capacity_msat >= min_inbound_capacity {
228                         min_capacity_channel_exists = true;
229                 };
230                 match filtered_channels.entry(channel.counterparty.node_id) {
231                         hash_map::Entry::Occupied(mut entry) => {
232                                 let current_max_capacity = entry.get().inbound_capacity_msat;
233                                 if channel.inbound_capacity_msat < current_max_capacity {
234                                         continue;
235                                 }
236                                 entry.insert(channel);
237                         }
238                         hash_map::Entry::Vacant(entry) => {
239                                 entry.insert(channel);
240                         }
241                 }
242         }
243
244         let route_hint_from_channel = |channel: &ChannelDetails| {
245                 let forwarding_info = channel.counterparty.forwarding_info.as_ref().unwrap();
246                 RouteHint(vec![RouteHintHop {
247                         src_node_id: channel.counterparty.node_id,
248                         short_channel_id: channel.get_inbound_payment_scid().unwrap(),
249                         fees: RoutingFees {
250                                 base_msat: forwarding_info.fee_base_msat,
251                                 proportional_millionths: forwarding_info.fee_proportional_millionths,
252                         },
253                         cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
254                         htlc_minimum_msat: None,
255                         htlc_maximum_msat: None,}])
256         };
257         // If all channels are private, return the route hint for the highest inbound capacity channel
258         // per counterparty node. If channels with an higher inbound capacity than the
259         // min_inbound_capacity exists, filter out the channels with a lower capacity than that.
260         filtered_channels.into_iter()
261                 .filter(|(_counterparty_id, channel)| {
262                         min_capacity_channel_exists && channel.inbound_capacity_msat >= min_inbound_capacity ||
263                         !min_capacity_channel_exists
264                 })
265                 .map(|(_counterparty_id, channel)| route_hint_from_channel(&channel))
266                 .collect::<Vec<RouteHint>>()
267 }
268
269 /// A [`Router`] implemented using [`find_route`].
270 pub struct DefaultRouter<G: Deref<Target = NetworkGraph>, L: Deref> where L::Target: Logger {
271         network_graph: G,
272         logger: L,
273         random_seed_bytes: Mutex<[u8; 32]>,
274 }
275
276 impl<G: Deref<Target = NetworkGraph>, L: Deref> DefaultRouter<G, L> where L::Target: Logger {
277         /// Creates a new router using the given [`NetworkGraph`], a [`Logger`], and a randomness source
278         /// `random_seed_bytes`.
279         pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32]) -> Self {
280                 let random_seed_bytes = Mutex::new(random_seed_bytes);
281                 Self { network_graph, logger, random_seed_bytes }
282         }
283 }
284
285 impl<G: Deref<Target = NetworkGraph>, L: Deref, S: Score> Router<S> for DefaultRouter<G, L>
286 where L::Target: Logger {
287         fn find_route(
288                 &self, payer: &PublicKey, params: &RouteParameters, _payment_hash: &PaymentHash,
289                 first_hops: Option<&[&ChannelDetails]>, scorer: &S
290         ) -> Result<Route, LightningError> {
291                 let random_seed_bytes = {
292                         let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
293                         *locked_random_seed_bytes = sha256::Hash::hash(&*locked_random_seed_bytes).into_inner();
294                         *locked_random_seed_bytes
295                 };
296                 find_route(payer, params, &*self.network_graph, first_hops, &*self.logger, scorer, &random_seed_bytes)
297         }
298 }
299
300 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Payer for ChannelManager<Signer, M, T, K, F, L>
301 where
302         M::Target: chain::Watch<Signer>,
303         T::Target: BroadcasterInterface,
304         K::Target: KeysInterface<Signer = Signer>,
305         F::Target: FeeEstimator,
306         L::Target: Logger,
307 {
308         fn node_id(&self) -> PublicKey {
309                 self.get_our_node_id()
310         }
311
312         fn first_hops(&self) -> Vec<ChannelDetails> {
313                 self.list_usable_channels()
314         }
315
316         fn send_payment(
317                 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
318         ) -> Result<PaymentId, PaymentSendFailure> {
319                 self.send_payment(route, payment_hash, payment_secret)
320         }
321
322         fn send_spontaneous_payment(
323                 &self, route: &Route, payment_preimage: PaymentPreimage,
324         ) -> Result<PaymentId, PaymentSendFailure> {
325                 self.send_spontaneous_payment(route, Some(payment_preimage))
326                         .map(|(_, payment_id)| payment_id)
327         }
328
329         fn retry_payment(
330                 &self, route: &Route, payment_id: PaymentId
331         ) -> Result<(), PaymentSendFailure> {
332                 self.retry_payment(route, payment_id)
333         }
334
335         fn abandon_payment(&self, payment_id: PaymentId) {
336                 self.abandon_payment(payment_id)
337         }
338 }
339
340 #[cfg(test)]
341 mod test {
342         use core::time::Duration;
343         use {Currency, Description, InvoiceDescription};
344         use bitcoin_hashes::Hash;
345         use bitcoin_hashes::sha256::Hash as Sha256;
346         use lightning::chain::keysinterface::PhantomKeysManager;
347         use lightning::ln::{PaymentPreimage, PaymentHash};
348         use lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY;
349         use lightning::ln::functional_test_utils::*;
350         use lightning::ln::features::InitFeatures;
351         use lightning::ln::msgs::ChannelMessageHandler;
352         use lightning::routing::router::{PaymentParameters, RouteParameters, find_route};
353         use lightning::util::enforcing_trait_impls::EnforcingSigner;
354         use lightning::util::events::{MessageSendEvent, MessageSendEventsProvider, Event};
355         use lightning::util::test_utils;
356         use lightning::chain::keysinterface::KeysInterface;
357         use utils::create_invoice_from_channelmanager_and_duration_since_epoch;
358
359         #[test]
360         fn test_from_channelmanager() {
361                 let chanmon_cfgs = create_chanmon_cfgs(2);
362                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
363                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
364                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
365                 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
366                 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
367                         &nodes[1].node, nodes[1].keys_manager, Currency::BitcoinTestnet, Some(10_000), "test".to_string(),
368                         Duration::from_secs(1234567)).unwrap();
369                 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
370                 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
371                 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
372
373                 // Invoice SCIDs should always use inbound SCID aliases over the real channel ID, if one is
374                 // available.
375                 assert_eq!(invoice.route_hints().len(), 1);
376                 assert_eq!(invoice.route_hints()[0].0.len(), 1);
377                 assert_eq!(invoice.route_hints()[0].0[0].short_channel_id,
378                         nodes[1].node.list_usable_channels()[0].inbound_scid_alias.unwrap());
379
380                 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
381                         .with_features(invoice.features().unwrap().clone())
382                         .with_route_hints(invoice.route_hints());
383                 let route_params = RouteParameters {
384                         payment_params,
385                         final_value_msat: invoice.amount_milli_satoshis().unwrap(),
386                         final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
387                 };
388                 let first_hops = nodes[0].node.list_usable_channels();
389                 let network_graph = node_cfgs[0].network_graph;
390                 let logger = test_utils::TestLogger::new();
391                 let scorer = test_utils::TestScorer::with_penalty(0);
392                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
393                 let route = find_route(
394                         &nodes[0].node.get_our_node_id(), &route_params, network_graph,
395                         Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
396                 ).unwrap();
397
398                 let payment_event = {
399                         let mut payment_hash = PaymentHash([0; 32]);
400                         payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
401                         nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
402                         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
403                         assert_eq!(added_monitors.len(), 1);
404                         added_monitors.clear();
405
406                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
407                         assert_eq!(events.len(), 1);
408                         SendEvent::from_event(events.remove(0))
409
410                 };
411                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
412                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
413                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
414                 assert_eq!(added_monitors.len(), 1);
415                 added_monitors.clear();
416                 let events = nodes[1].node.get_and_clear_pending_msg_events();
417                 assert_eq!(events.len(), 2);
418         }
419
420         #[test]
421         #[cfg(feature = "std")]
422         fn test_multi_node_receive() {
423                 do_test_multi_node_receive(true);
424                 do_test_multi_node_receive(false);
425         }
426
427         #[cfg(feature = "std")]
428         fn do_test_multi_node_receive(user_generated_pmt_hash: bool) {
429                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
430                 let seed_1 = [42 as u8; 32];
431                 let seed_2 = [43 as u8; 32];
432                 let cross_node_seed = [44 as u8; 32];
433                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
434                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
435                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
436                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
437                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
438                 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
439                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_0_1.1);
440                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_1.0);
441                 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
442                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
443                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
444
445                 let payment_amt = 10_000;
446                 let (payment_preimage, payment_hash, payment_secret) = {
447                         if user_generated_pmt_hash {
448                                 let payment_preimage = PaymentPreimage([1; 32]);
449                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
450                                 let payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(payment_amt), 3600).unwrap();
451                                 (payment_preimage, payment_hash, payment_secret)
452                         } else {
453                                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(payment_amt), 3600).unwrap();
454                                 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
455                                 (payment_preimage, payment_hash, payment_secret)
456                         }
457                 };
458                 let route_hints = vec![
459                         nodes[1].node.get_phantom_route_hints(),
460                         nodes[2].node.get_phantom_route_hints(),
461                 ];
462                 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();
463
464                 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
465                 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
466                 assert_eq!(invoice.route_hints().len(), 2);
467                 assert!(!invoice.features().unwrap().supports_basic_mpp());
468
469                 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
470                         .with_features(invoice.features().unwrap().clone())
471                         .with_route_hints(invoice.route_hints());
472                 let params = RouteParameters {
473                         payment_params,
474                         final_value_msat: invoice.amount_milli_satoshis().unwrap(),
475                         final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
476                 };
477                 let first_hops = nodes[0].node.list_usable_channels();
478                 let network_graph = node_cfgs[0].network_graph;
479                 let logger = test_utils::TestLogger::new();
480                 let scorer = test_utils::TestScorer::with_penalty(0);
481                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
482                 let route = find_route(
483                         &nodes[0].node.get_our_node_id(), &params, network_graph,
484                         Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
485                 ).unwrap();
486                 let (payment_event, fwd_idx) = {
487                         let mut payment_hash = PaymentHash([0; 32]);
488                         payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
489                         nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
490                         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
491                         assert_eq!(added_monitors.len(), 1);
492                         added_monitors.clear();
493
494                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
495                         assert_eq!(events.len(), 1);
496                         let fwd_idx = match events[0] {
497                                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
498                                         if node_id == nodes[1].node.get_our_node_id() {
499                                                 1
500                                         } else { 2 }
501                                 },
502                                 _ => panic!("Unexpected event")
503                         };
504                         (SendEvent::from_event(events.remove(0)), fwd_idx)
505                 };
506                 nodes[fwd_idx].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
507                 commitment_signed_dance!(nodes[fwd_idx], nodes[0], &payment_event.commitment_msg, false, true);
508
509                 // Note that we have to "forward pending HTLCs" twice before we see the PaymentReceived as
510                 // this "emulates" the payment taking two hops, providing some privacy to make phantom node
511                 // payments "look real" by taking more time.
512                 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
513                 nodes[fwd_idx].node.process_pending_htlc_forwards();
514                 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
515                 nodes[fwd_idx].node.process_pending_htlc_forwards();
516
517                 let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) };
518                 expect_payment_received!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt);
519                 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[fwd_idx])[..]), false, payment_preimage);
520                 let events = nodes[0].node.get_and_clear_pending_events();
521                 assert_eq!(events.len(), 2);
522                 match events[0] {
523                         Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
524                                 assert_eq!(payment_preimage, *ev_preimage);
525                                 assert_eq!(payment_hash, *ev_hash);
526                                 assert_eq!(fee_paid_msat, &Some(0));
527                         },
528                         _ => panic!("Unexpected event")
529                 }
530                 match events[1] {
531                         Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
532                                 assert_eq!(hash, Some(payment_hash));
533                         },
534                         _ => panic!("Unexpected event")
535                 }
536         }
537 }