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.short_channel_id {
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.short_channel_id {
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 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
329 .with_features(invoice.features().unwrap().clone())
330 .with_route_hints(invoice.route_hints());
331 let route_params = RouteParameters {
333 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
334 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
336 let first_hops = nodes[0].node.list_usable_channels();
337 let network_graph = node_cfgs[0].network_graph;
338 let logger = test_utils::TestLogger::new();
339 let scorer = test_utils::TestScorer::with_penalty(0);
340 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
341 let route = find_route(
342 &nodes[0].node.get_our_node_id(), &route_params, network_graph,
343 Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
346 let payment_event = {
347 let mut payment_hash = PaymentHash([0; 32]);
348 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
349 nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
350 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
351 assert_eq!(added_monitors.len(), 1);
352 added_monitors.clear();
354 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
355 assert_eq!(events.len(), 1);
356 SendEvent::from_event(events.remove(0))
359 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
360 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
361 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
362 assert_eq!(added_monitors.len(), 1);
363 added_monitors.clear();
364 let events = nodes[1].node.get_and_clear_pending_msg_events();
365 assert_eq!(events.len(), 2);
369 #[cfg(feature = "std")]
370 fn test_multi_node_receive() {
371 do_test_multi_node_receive(true);
372 do_test_multi_node_receive(false);
375 #[cfg(feature = "std")]
376 fn do_test_multi_node_receive(user_generated_pmt_hash: bool) {
377 let mut chanmon_cfgs = create_chanmon_cfgs(3);
378 let seed_1 = [42 as u8; 32];
379 let seed_2 = [43 as u8; 32];
380 let cross_node_seed = [44 as u8; 32];
381 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
382 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
383 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
384 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
385 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
386 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
387 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_0_1.1);
388 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_1.0);
389 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
390 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
391 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
393 let payment_amt = 10_000;
394 let (payment_preimage, payment_hash, payment_secret) = {
395 if user_generated_pmt_hash {
396 let payment_preimage = PaymentPreimage([1; 32]);
397 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
398 let payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(payment_amt), 3600).unwrap();
399 (payment_preimage, payment_hash, payment_secret)
401 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(payment_amt), 3600).unwrap();
402 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
403 (payment_preimage, payment_hash, payment_secret)
406 let route_hints = vec![
407 nodes[1].node.get_phantom_route_hints(),
408 nodes[2].node.get_phantom_route_hints(),
410 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();
412 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
413 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
414 assert_eq!(invoice.route_hints().len(), 2);
415 assert!(!invoice.features().unwrap().supports_basic_mpp());
417 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
418 .with_features(invoice.features().unwrap().clone())
419 .with_route_hints(invoice.route_hints());
420 let params = RouteParameters {
422 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
423 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
425 let first_hops = nodes[0].node.list_usable_channels();
426 let network_graph = node_cfgs[0].network_graph;
427 let logger = test_utils::TestLogger::new();
428 let scorer = test_utils::TestScorer::with_penalty(0);
429 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
430 let route = find_route(
431 &nodes[0].node.get_our_node_id(), ¶ms, network_graph,
432 Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
434 let (payment_event, fwd_idx) = {
435 let mut payment_hash = PaymentHash([0; 32]);
436 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
437 nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
438 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
439 assert_eq!(added_monitors.len(), 1);
440 added_monitors.clear();
442 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
443 assert_eq!(events.len(), 1);
444 let fwd_idx = match events[0] {
445 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
446 if node_id == nodes[1].node.get_our_node_id() {
450 _ => panic!("Unexpected event")
452 (SendEvent::from_event(events.remove(0)), fwd_idx)
454 nodes[fwd_idx].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
455 commitment_signed_dance!(nodes[fwd_idx], nodes[0], &payment_event.commitment_msg, false, true);
457 // Note that we have to "forward pending HTLCs" twice before we see the PaymentReceived as
458 // this "emulates" the payment taking two hops, providing some privacy to make phantom node
459 // payments "look real" by taking more time.
460 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
461 nodes[fwd_idx].node.process_pending_htlc_forwards();
462 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
463 nodes[fwd_idx].node.process_pending_htlc_forwards();
465 let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) };
466 expect_payment_received!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt);
467 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[fwd_idx])[..]), false, payment_preimage);
468 let events = nodes[0].node.get_and_clear_pending_events();
469 assert_eq!(events.len(), 2);
471 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
472 assert_eq!(payment_preimage, *ev_preimage);
473 assert_eq!(payment_hash, *ev_hash);
474 assert_eq!(fee_paid_msat, &Some(0));
476 _ => panic!("Unexpected event")
479 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
480 assert_eq!(hash, Some(payment_hash));
482 _ => panic!("Unexpected event")