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;
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;
26 #[cfg(feature = "std")]
27 /// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice."
28 /// See [`PhantomKeysManager`] for more information on phantom node payments.
30 /// `phantom_route_hints` parameter:
31 /// * Contains channel info for all nodes participating in the phantom invoice
32 /// * Entries are retrieved from a call to [`ChannelManager::get_phantom_route_hints`] on each
33 /// participating node
34 /// * It is fine to cache `phantom_route_hints` and reuse it across invoices, as long as the data is
35 /// updated when a channel becomes disabled or closes
36 /// * Note that if too many channels are included in [`PhantomRouteHints::channels`], the invoice
37 /// may be too long for QR code scanning. To fix this, `PhantomRouteHints::channels` may be pared
40 /// `payment_hash` and `payment_secret` come from [`ChannelManager::create_inbound_payment`] or
41 /// [`ChannelManager::create_inbound_payment_for_hash`]. These values can be retrieved from any
42 /// participating node.
44 /// Note that the provided `keys_manager`'s `KeysInterface` implementation must support phantom
45 /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
48 /// [`PhantomKeysManager`]: lightning::chain::keysinterface::PhantomKeysManager
49 /// [`ChannelManager::get_phantom_route_hints`]: lightning::ln::channelmanager::ChannelManager::get_phantom_route_hints
50 /// [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels
51 pub fn create_phantom_invoice<Signer: Sign, K: Deref>(
52 amt_msat: Option<u64>, description: String, payment_hash: PaymentHash, payment_secret:
53 PaymentSecret, phantom_route_hints: Vec<PhantomRouteHints>, keys_manager: K, network: Currency
54 ) -> Result<Invoice, SignOrCreationError<()>> where K::Target: KeysInterface {
55 if phantom_route_hints.len() == 0 {
56 return Err(SignOrCreationError::CreationError(CreationError::MissingRouteHints))
58 let mut invoice = InvoiceBuilder::new(network)
59 .description(description)
61 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
62 .payment_secret(payment_secret)
63 .min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into());
64 if let Some(amt) = amt_msat {
65 invoice = invoice.amount_milli_satoshis(amt);
68 for hint in phantom_route_hints {
69 for channel in &hint.channels {
70 let short_channel_id = match channel.short_channel_id {
74 let forwarding_info = match &channel.counterparty.forwarding_info {
75 Some(info) => info.clone(),
78 invoice = invoice.private_route(RouteHint(vec![
80 src_node_id: channel.counterparty.node_id,
83 base_msat: forwarding_info.fee_base_msat,
84 proportional_millionths: forwarding_info.fee_proportional_millionths,
86 cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
87 htlc_minimum_msat: None,
88 htlc_maximum_msat: None,
91 src_node_id: hint.real_node_pubkey,
92 short_channel_id: hint.phantom_scid,
95 proportional_millionths: 0,
97 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
98 htlc_minimum_msat: None,
99 htlc_maximum_msat: None,
105 let raw_invoice = match invoice.build_raw() {
107 Err(e) => return Err(SignOrCreationError::CreationError(e))
109 let hrp_str = raw_invoice.hrp.to_string();
110 let hrp_bytes = hrp_str.as_bytes();
111 let data_without_signature = raw_invoice.data.to_base32();
112 let signed_raw_invoice = raw_invoice.sign(|_| keys_manager.sign_invoice(hrp_bytes, &data_without_signature, Recipient::PhantomNode));
113 match signed_raw_invoice {
114 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
115 Err(e) => Err(SignOrCreationError::SignError(e))
119 #[cfg(feature = "std")]
120 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
121 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
122 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
123 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
124 /// that the payment secret is valid when the invoice is paid.
125 pub fn create_invoice_from_channelmanager<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
126 channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
127 amt_msat: Option<u64>, description: String
128 ) -> Result<Invoice, SignOrCreationError<()>>
130 M::Target: chain::Watch<Signer>,
131 T::Target: BroadcasterInterface,
132 K::Target: KeysInterface<Signer = Signer>,
133 F::Target: FeeEstimator,
136 use std::time::SystemTime;
137 let duration = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
138 .expect("for the foreseeable future this shouldn't happen");
139 create_invoice_from_channelmanager_and_duration_since_epoch(
149 /// See [`create_invoice_from_channelmanager`]
150 /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
151 /// available and the current time is supplied by the caller.
152 pub fn create_invoice_from_channelmanager_and_duration_since_epoch<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
153 channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
154 amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
155 ) -> Result<Invoice, SignOrCreationError<()>>
157 M::Target: chain::Watch<Signer>,
158 T::Target: BroadcasterInterface,
159 K::Target: KeysInterface<Signer = Signer>,
160 F::Target: FeeEstimator,
163 // Marshall route hints.
164 let our_channels = channelmanager.list_usable_channels();
165 let mut route_hints = vec![];
166 for channel in our_channels {
167 let short_channel_id = match channel.short_channel_id {
171 let forwarding_info = match channel.counterparty.forwarding_info {
175 route_hints.push(RouteHint(vec![RouteHintHop {
176 src_node_id: channel.counterparty.node_id,
179 base_msat: forwarding_info.fee_base_msat,
180 proportional_millionths: forwarding_info.fee_proportional_millionths,
182 cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
183 htlc_minimum_msat: None,
184 htlc_maximum_msat: None,
188 // `create_inbound_payment` only returns an error if the amount is greater than the total bitcoin
190 let (payment_hash, payment_secret) = channelmanager.create_inbound_payment(
191 amt_msat, DEFAULT_EXPIRY_TIME.try_into().unwrap())
192 .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
193 let our_node_pubkey = channelmanager.get_our_node_id();
194 let mut invoice = InvoiceBuilder::new(network)
195 .description(description)
196 .duration_since_epoch(duration_since_epoch)
197 .payee_pub_key(our_node_pubkey)
198 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
199 .payment_secret(payment_secret)
201 .min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into());
202 if let Some(amt) = amt_msat {
203 invoice = invoice.amount_milli_satoshis(amt);
205 for hint in route_hints {
206 invoice = invoice.private_route(hint);
209 let raw_invoice = match invoice.build_raw() {
211 Err(e) => return Err(SignOrCreationError::CreationError(e))
213 let hrp_str = raw_invoice.hrp.to_string();
214 let hrp_bytes = hrp_str.as_bytes();
215 let data_without_signature = raw_invoice.data.to_base32();
216 let signed_raw_invoice = raw_invoice.sign(|_| keys_manager.sign_invoice(hrp_bytes, &data_without_signature, Recipient::Node));
217 match signed_raw_invoice {
218 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
219 Err(e) => Err(SignOrCreationError::SignError(e))
223 /// A [`Router`] implemented using [`find_route`].
224 pub struct DefaultRouter<G: Deref<Target = NetworkGraph>, L: Deref> where L::Target: Logger {
229 impl<G: Deref<Target = NetworkGraph>, L: Deref> DefaultRouter<G, L> where L::Target: Logger {
230 /// Creates a new router using the given [`NetworkGraph`] and [`Logger`].
231 pub fn new(network_graph: G, logger: L) -> Self {
232 Self { network_graph, logger }
236 impl<G: Deref<Target = NetworkGraph>, L: Deref, S: Score> Router<S> for DefaultRouter<G, L>
237 where L::Target: Logger {
239 &self, payer: &PublicKey, params: &RouteParameters, _payment_hash: &PaymentHash,
240 first_hops: Option<&[&ChannelDetails]>, scorer: &S
241 ) -> Result<Route, LightningError> {
242 find_route(payer, params, &*self.network_graph, first_hops, &*self.logger, scorer)
246 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Payer for ChannelManager<Signer, M, T, K, F, L>
248 M::Target: chain::Watch<Signer>,
249 T::Target: BroadcasterInterface,
250 K::Target: KeysInterface<Signer = Signer>,
251 F::Target: FeeEstimator,
254 fn node_id(&self) -> PublicKey {
255 self.get_our_node_id()
258 fn first_hops(&self) -> Vec<ChannelDetails> {
259 self.list_usable_channels()
263 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
264 ) -> Result<PaymentId, PaymentSendFailure> {
265 self.send_payment(route, payment_hash, payment_secret)
268 fn send_spontaneous_payment(
269 &self, route: &Route, payment_preimage: PaymentPreimage,
270 ) -> Result<PaymentId, PaymentSendFailure> {
271 self.send_spontaneous_payment(route, Some(payment_preimage))
272 .map(|(_, payment_id)| payment_id)
276 &self, route: &Route, payment_id: PaymentId
277 ) -> Result<(), PaymentSendFailure> {
278 self.retry_payment(route, payment_id)
281 fn abandon_payment(&self, payment_id: PaymentId) {
282 self.abandon_payment(payment_id)
288 use core::time::Duration;
289 use {Currency, Description, InvoiceDescription};
290 use bitcoin_hashes::Hash;
291 use bitcoin_hashes::sha256::Hash as Sha256;
292 use lightning::chain::keysinterface::PhantomKeysManager;
293 use lightning::ln::{PaymentPreimage, PaymentHash};
294 use lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY;
295 use lightning::ln::functional_test_utils::*;
296 use lightning::ln::features::InitFeatures;
297 use lightning::ln::msgs::ChannelMessageHandler;
298 use lightning::routing::router::{PaymentParameters, RouteParameters, find_route};
299 use lightning::util::enforcing_trait_impls::EnforcingSigner;
300 use lightning::util::events::{MessageSendEvent, MessageSendEventsProvider, Event};
301 use lightning::util::test_utils;
302 use utils::create_invoice_from_channelmanager_and_duration_since_epoch;
305 fn test_from_channelmanager() {
306 let chanmon_cfgs = create_chanmon_cfgs(2);
307 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
308 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
309 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
310 let _chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
311 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
312 &nodes[1].node, nodes[1].keys_manager, Currency::BitcoinTestnet, Some(10_000), "test".to_string(),
313 Duration::from_secs(1234567)).unwrap();
314 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
315 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
316 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
318 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
319 .with_features(invoice.features().unwrap().clone())
320 .with_route_hints(invoice.route_hints());
321 let route_params = RouteParameters {
323 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
324 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
326 let first_hops = nodes[0].node.list_usable_channels();
327 let network_graph = node_cfgs[0].network_graph;
328 let logger = test_utils::TestLogger::new();
329 let scorer = test_utils::TestScorer::with_penalty(0);
330 let route = find_route(
331 &nodes[0].node.get_our_node_id(), &route_params, network_graph,
332 Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer,
335 let payment_event = {
336 let mut payment_hash = PaymentHash([0; 32]);
337 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
338 nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
339 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
340 assert_eq!(added_monitors.len(), 1);
341 added_monitors.clear();
343 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
344 assert_eq!(events.len(), 1);
345 SendEvent::from_event(events.remove(0))
348 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
349 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
350 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
351 assert_eq!(added_monitors.len(), 1);
352 added_monitors.clear();
353 let events = nodes[1].node.get_and_clear_pending_msg_events();
354 assert_eq!(events.len(), 2);
358 #[cfg(feature = "std")]
359 fn test_multi_node_receive() {
360 do_test_multi_node_receive(true);
361 do_test_multi_node_receive(false);
364 #[cfg(feature = "std")]
365 fn do_test_multi_node_receive(user_generated_pmt_hash: bool) {
366 let mut chanmon_cfgs = create_chanmon_cfgs(3);
367 let seed_1 = [42 as u8; 32];
368 let seed_2 = [43 as u8; 32];
369 let cross_node_seed = [44 as u8; 32];
370 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
371 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
372 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
373 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
374 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
375 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
376 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_0_1.1);
377 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_1.0);
378 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
379 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
380 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
382 let payment_amt = 10_000;
383 let (payment_preimage, payment_hash, payment_secret) = {
384 if user_generated_pmt_hash {
385 let payment_preimage = PaymentPreimage([1; 32]);
386 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
387 let payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(payment_amt), 3600).unwrap();
388 (payment_preimage, payment_hash, payment_secret)
390 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(payment_amt), 3600).unwrap();
391 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
392 (payment_preimage, payment_hash, payment_secret)
395 let route_hints = vec![
396 nodes[1].node.get_phantom_route_hints(),
397 nodes[2].node.get_phantom_route_hints(),
399 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();
401 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
402 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
403 assert_eq!(invoice.route_hints().len(), 2);
404 assert!(!invoice.features().unwrap().supports_basic_mpp());
406 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
407 .with_features(invoice.features().unwrap().clone())
408 .with_route_hints(invoice.route_hints());
409 let params = RouteParameters {
411 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
412 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
414 let first_hops = nodes[0].node.list_usable_channels();
415 let network_graph = node_cfgs[0].network_graph;
416 let logger = test_utils::TestLogger::new();
417 let scorer = test_utils::TestScorer::with_penalty(0);
418 let route = find_route(
419 &nodes[0].node.get_our_node_id(), ¶ms, network_graph,
420 Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer,
422 let (payment_event, fwd_idx) = {
423 let mut payment_hash = PaymentHash([0; 32]);
424 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
425 nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
426 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
427 assert_eq!(added_monitors.len(), 1);
428 added_monitors.clear();
430 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
431 assert_eq!(events.len(), 1);
432 let fwd_idx = match events[0] {
433 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
434 if node_id == nodes[1].node.get_our_node_id() {
438 _ => panic!("Unexpected event")
440 (SendEvent::from_event(events.remove(0)), fwd_idx)
442 nodes[fwd_idx].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
443 commitment_signed_dance!(nodes[fwd_idx], nodes[0], &payment_event.commitment_msg, false, true);
445 // Note that we have to "forward pending HTLCs" twice before we see the PaymentReceived as
446 // this "emulates" the payment taking two hops, providing some privacy to make phantom node
447 // payments "look real" by taking more time.
448 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
449 nodes[fwd_idx].node.process_pending_htlc_forwards();
450 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
451 nodes[fwd_idx].node.process_pending_htlc_forwards();
453 let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) };
454 expect_payment_received!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt);
455 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[fwd_idx])[..]), false, payment_preimage);
456 let events = nodes[0].node.get_and_clear_pending_events();
457 assert_eq!(events.len(), 2);
459 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
460 assert_eq!(payment_preimage, *ev_preimage);
461 assert_eq!(payment_hash, *ev_hash);
462 assert_eq!(fee_paid_msat, &Some(0));
464 _ => panic!("Unexpected event")
467 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
468 assert_eq!(hash, Some(payment_hash));
470 _ => panic!("Unexpected event")