1 //! Convenient utilities to create an invoice.
3 use {CreationError, Currency, DEFAULT_EXPIRY_TIME, Invoice, InvoiceBuilder, SignOrCreationError};
4 use payment::{Payer, Router};
7 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:
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))
59 let mut invoice = InvoiceBuilder::new(network)
60 .description(description)
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);
69 for hint in phantom_route_hints {
70 for channel in &hint.channels {
71 let short_channel_id = match channel.get_inbound_payment_scid() {
75 let forwarding_info = match &channel.counterparty.forwarding_info {
76 Some(info) => info.clone(),
79 invoice = invoice.private_route(RouteHint(vec![
81 src_node_id: channel.counterparty.node_id,
84 base_msat: forwarding_info.fee_base_msat,
85 proportional_millionths: forwarding_info.fee_proportional_millionths,
87 cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
88 htlc_minimum_msat: None,
89 htlc_maximum_msat: None,
92 src_node_id: hint.real_node_pubkey,
93 short_channel_id: hint.phantom_scid,
96 proportional_millionths: 0,
98 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
99 htlc_minimum_msat: None,
100 htlc_maximum_msat: None,
106 let raw_invoice = match invoice.build_raw() {
108 Err(e) => return Err(SignOrCreationError::CreationError(e))
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))
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<()>>
131 M::Target: chain::Watch<Signer>,
132 T::Target: BroadcasterInterface,
133 K::Target: KeysInterface<Signer = Signer>,
134 F::Target: FeeEstimator,
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(
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<()>>
158 M::Target: chain::Watch<Signer>,
159 T::Target: BroadcasterInterface,
160 K::Target: KeysInterface<Signer = Signer>,
161 F::Target: FeeEstimator,
164 // Marshall route hints.
165 let our_channels = channelmanager.list_usable_channels();
166 let mut route_hints = vec![];
167 for channel in our_channels {
168 let short_channel_id = match channel.get_inbound_payment_scid() {
172 let forwarding_info = match channel.counterparty.forwarding_info {
176 route_hints.push(RouteHint(vec![RouteHintHop {
177 src_node_id: channel.counterparty.node_id,
180 base_msat: forwarding_info.fee_base_msat,
181 proportional_millionths: forwarding_info.fee_proportional_millionths,
183 cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
184 htlc_minimum_msat: None,
185 htlc_maximum_msat: None,
189 // `create_inbound_payment` only returns an error if the amount is greater than the total bitcoin
191 let (payment_hash, payment_secret) = channelmanager.create_inbound_payment(
192 amt_msat, DEFAULT_EXPIRY_TIME.try_into().unwrap())
193 .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
194 let our_node_pubkey = channelmanager.get_our_node_id();
195 let mut invoice = InvoiceBuilder::new(network)
196 .description(description)
197 .duration_since_epoch(duration_since_epoch)
198 .payee_pub_key(our_node_pubkey)
199 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
200 .payment_secret(payment_secret)
202 .min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into());
203 if let Some(amt) = amt_msat {
204 invoice = invoice.amount_milli_satoshis(amt);
206 for hint in route_hints {
207 invoice = invoice.private_route(hint);
210 let raw_invoice = match invoice.build_raw() {
212 Err(e) => return Err(SignOrCreationError::CreationError(e))
214 let hrp_str = raw_invoice.hrp.to_string();
215 let hrp_bytes = hrp_str.as_bytes();
216 let data_without_signature = raw_invoice.data.to_base32();
217 let signed_raw_invoice = raw_invoice.sign(|_| keys_manager.sign_invoice(hrp_bytes, &data_without_signature, Recipient::Node));
218 match signed_raw_invoice {
219 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
220 Err(e) => Err(SignOrCreationError::SignError(e))
224 /// A [`Router`] implemented using [`find_route`].
225 pub struct DefaultRouter<G: Deref<Target = NetworkGraph>, L: Deref> where L::Target: Logger {
228 random_seed_bytes: Mutex<[u8; 32]>,
231 impl<G: Deref<Target = NetworkGraph>, L: Deref> DefaultRouter<G, L> where L::Target: Logger {
232 /// Creates a new router using the given [`NetworkGraph`], a [`Logger`], and a randomness source
233 /// `random_seed_bytes`.
234 pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32]) -> Self {
235 let random_seed_bytes = Mutex::new(random_seed_bytes);
236 Self { network_graph, logger, random_seed_bytes }
240 impl<G: Deref<Target = NetworkGraph>, L: Deref, S: Score> Router<S> for DefaultRouter<G, L>
241 where L::Target: Logger {
243 &self, payer: &PublicKey, params: &RouteParameters, _payment_hash: &PaymentHash,
244 first_hops: Option<&[&ChannelDetails]>, scorer: &S
245 ) -> Result<Route, LightningError> {
246 let random_seed_bytes = {
247 let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
248 *locked_random_seed_bytes = sha256::Hash::hash(&*locked_random_seed_bytes).into_inner();
249 *locked_random_seed_bytes
251 find_route(payer, params, &*self.network_graph, first_hops, &*self.logger, scorer, &random_seed_bytes)
255 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Payer for ChannelManager<Signer, M, T, K, F, L>
257 M::Target: chain::Watch<Signer>,
258 T::Target: BroadcasterInterface,
259 K::Target: KeysInterface<Signer = Signer>,
260 F::Target: FeeEstimator,
263 fn node_id(&self) -> PublicKey {
264 self.get_our_node_id()
267 fn first_hops(&self) -> Vec<ChannelDetails> {
268 self.list_usable_channels()
272 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
273 ) -> Result<PaymentId, PaymentSendFailure> {
274 self.send_payment(route, payment_hash, payment_secret)
277 fn send_spontaneous_payment(
278 &self, route: &Route, payment_preimage: PaymentPreimage,
279 ) -> Result<PaymentId, PaymentSendFailure> {
280 self.send_spontaneous_payment(route, Some(payment_preimage))
281 .map(|(_, payment_id)| payment_id)
285 &self, route: &Route, payment_id: PaymentId
286 ) -> Result<(), PaymentSendFailure> {
287 self.retry_payment(route, payment_id)
290 fn abandon_payment(&self, payment_id: PaymentId) {
291 self.abandon_payment(payment_id)
297 use core::time::Duration;
298 use {Currency, Description, InvoiceDescription};
299 use bitcoin_hashes::Hash;
300 use bitcoin_hashes::sha256::Hash as Sha256;
301 use lightning::chain::keysinterface::PhantomKeysManager;
302 use lightning::ln::{PaymentPreimage, PaymentHash};
303 use lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY;
304 use lightning::ln::functional_test_utils::*;
305 use lightning::ln::features::InitFeatures;
306 use lightning::ln::msgs::ChannelMessageHandler;
307 use lightning::routing::router::{PaymentParameters, RouteParameters, find_route};
308 use lightning::util::enforcing_trait_impls::EnforcingSigner;
309 use lightning::util::events::{MessageSendEvent, MessageSendEventsProvider, Event};
310 use lightning::util::test_utils;
311 use lightning::chain::keysinterface::KeysInterface;
312 use utils::create_invoice_from_channelmanager_and_duration_since_epoch;
315 fn test_from_channelmanager() {
316 let chanmon_cfgs = create_chanmon_cfgs(2);
317 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
318 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
319 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
320 let _chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
321 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
322 &nodes[1].node, nodes[1].keys_manager, Currency::BitcoinTestnet, Some(10_000), "test".to_string(),
323 Duration::from_secs(1234567)).unwrap();
324 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
325 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
326 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
328 // Invoice SCIDs should always use inbound SCID aliases over the real channel ID, if one is
330 assert_eq!(invoice.route_hints().len(), 1);
331 assert_eq!(invoice.route_hints()[0].0.len(), 1);
332 assert_eq!(invoice.route_hints()[0].0[0].short_channel_id,
333 nodes[1].node.list_usable_channels()[0].inbound_scid_alias.unwrap());
335 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
336 .with_features(invoice.features().unwrap().clone())
337 .with_route_hints(invoice.route_hints());
338 let route_params = RouteParameters {
340 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
341 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
343 let first_hops = nodes[0].node.list_usable_channels();
344 let network_graph = node_cfgs[0].network_graph;
345 let logger = test_utils::TestLogger::new();
346 let scorer = test_utils::TestScorer::with_penalty(0);
347 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
348 let route = find_route(
349 &nodes[0].node.get_our_node_id(), &route_params, network_graph,
350 Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
353 let payment_event = {
354 let mut payment_hash = PaymentHash([0; 32]);
355 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
356 nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
357 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
358 assert_eq!(added_monitors.len(), 1);
359 added_monitors.clear();
361 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
362 assert_eq!(events.len(), 1);
363 SendEvent::from_event(events.remove(0))
366 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
367 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
368 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
369 assert_eq!(added_monitors.len(), 1);
370 added_monitors.clear();
371 let events = nodes[1].node.get_and_clear_pending_msg_events();
372 assert_eq!(events.len(), 2);
376 #[cfg(feature = "std")]
377 fn test_multi_node_receive() {
378 do_test_multi_node_receive(true);
379 do_test_multi_node_receive(false);
382 #[cfg(feature = "std")]
383 fn do_test_multi_node_receive(user_generated_pmt_hash: bool) {
384 let mut chanmon_cfgs = create_chanmon_cfgs(3);
385 let seed_1 = [42 as u8; 32];
386 let seed_2 = [43 as u8; 32];
387 let cross_node_seed = [44 as u8; 32];
388 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
389 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
390 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
391 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
392 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
393 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
394 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_0_1.1);
395 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_1.0);
396 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
397 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
398 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
400 let payment_amt = 10_000;
401 let (payment_preimage, payment_hash, payment_secret) = {
402 if user_generated_pmt_hash {
403 let payment_preimage = PaymentPreimage([1; 32]);
404 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
405 let payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(payment_amt), 3600).unwrap();
406 (payment_preimage, payment_hash, payment_secret)
408 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(payment_amt), 3600).unwrap();
409 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
410 (payment_preimage, payment_hash, payment_secret)
413 let route_hints = vec![
414 nodes[1].node.get_phantom_route_hints(),
415 nodes[2].node.get_phantom_route_hints(),
417 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();
419 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
420 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
421 assert_eq!(invoice.route_hints().len(), 2);
422 assert!(!invoice.features().unwrap().supports_basic_mpp());
424 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
425 .with_features(invoice.features().unwrap().clone())
426 .with_route_hints(invoice.route_hints());
427 let params = RouteParameters {
429 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
430 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
432 let first_hops = nodes[0].node.list_usable_channels();
433 let network_graph = node_cfgs[0].network_graph;
434 let logger = test_utils::TestLogger::new();
435 let scorer = test_utils::TestScorer::with_penalty(0);
436 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
437 let route = find_route(
438 &nodes[0].node.get_our_node_id(), ¶ms, network_graph,
439 Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
441 let (payment_event, fwd_idx) = {
442 let mut payment_hash = PaymentHash([0; 32]);
443 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
444 nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
445 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
446 assert_eq!(added_monitors.len(), 1);
447 added_monitors.clear();
449 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
450 assert_eq!(events.len(), 1);
451 let fwd_idx = match events[0] {
452 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
453 if node_id == nodes[1].node.get_our_node_id() {
457 _ => panic!("Unexpected event")
459 (SendEvent::from_event(events.remove(0)), fwd_idx)
461 nodes[fwd_idx].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
462 commitment_signed_dance!(nodes[fwd_idx], nodes[0], &payment_event.commitment_msg, false, true);
464 // Note that we have to "forward pending HTLCs" twice before we see the PaymentReceived as
465 // this "emulates" the payment taking two hops, providing some privacy to make phantom node
466 // payments "look real" by taking more time.
467 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
468 nodes[fwd_idx].node.process_pending_htlc_forwards();
469 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
470 nodes[fwd_idx].node.process_pending_htlc_forwards();
472 let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) };
473 expect_payment_received!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt);
474 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[fwd_idx])[..]), false, payment_preimage);
475 let events = nodes[0].node.get_and_clear_pending_events();
476 assert_eq!(events.len(), 2);
478 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
479 assert_eq!(payment_preimage, *ev_preimage);
480 assert_eq!(payment_hash, *ev_hash);
481 assert_eq!(fee_paid_msat, &Some(0));
483 _ => panic!("Unexpected event")
486 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
487 assert_eq!(hash, Some(payment_hash));
489 _ => panic!("Unexpected event")