1 //! Convenient utilities to create an invoice.
2 use {Currency, DEFAULT_EXPIRY_TIME, Invoice, InvoiceBuilder, SignOrCreationError, RawInvoice};
4 use bitcoin_hashes::Hash;
6 use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
7 use lightning::chain::keysinterface::{Sign, KeysInterface};
8 use lightning::ln::channelmanager::{ChannelManager, MIN_FINAL_CLTV_EXPIRY};
9 use lightning::routing::network_graph::RoutingFees;
10 use lightning::routing::router::{RouteHint, RouteHintHop};
11 use lightning::util::logger::Logger;
12 use std::convert::TryInto;
15 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
16 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
17 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
18 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
19 /// that the payment secret is valid when the invoice is paid.
20 pub fn create_invoice_from_channelmanager<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
21 channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
22 amt_msat: Option<u64>, description: String
23 ) -> Result<Invoice, SignOrCreationError<()>>
25 M::Target: chain::Watch<Signer>,
26 T::Target: BroadcasterInterface,
27 K::Target: KeysInterface<Signer = Signer>,
28 F::Target: FeeEstimator,
31 // Marshall route hints.
32 let our_channels = channelmanager.list_usable_channels();
33 let mut route_hints = vec![];
34 for channel in our_channels {
35 let short_channel_id = match channel.short_channel_id {
39 let forwarding_info = match channel.counterparty.forwarding_info {
43 route_hints.push(RouteHint(vec![RouteHintHop {
44 src_node_id: channel.counterparty.node_id,
47 base_msat: forwarding_info.fee_base_msat,
48 proportional_millionths: forwarding_info.fee_proportional_millionths,
50 cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
51 htlc_minimum_msat: None,
52 htlc_maximum_msat: None,
56 let (payment_hash, payment_secret) = channelmanager.create_inbound_payment(
58 DEFAULT_EXPIRY_TIME.try_into().unwrap(),
61 let our_node_pubkey = channelmanager.get_our_node_id();
62 let mut invoice = InvoiceBuilder::new(network)
63 .description(description)
65 .payee_pub_key(our_node_pubkey)
66 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
67 .payment_secret(payment_secret)
69 .min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into());
70 if let Some(amt) = amt_msat {
71 invoice = invoice.amount_milli_satoshis(amt);
73 for hint in route_hints {
74 invoice = invoice.private_route(hint);
77 let raw_invoice = match invoice.build_raw() {
79 Err(e) => return Err(SignOrCreationError::CreationError(e))
81 let hrp_str = raw_invoice.hrp.to_string();
82 let hrp_bytes = hrp_str.as_bytes();
83 let data_without_signature = raw_invoice.data.to_base32();
84 let invoice_preimage = RawInvoice::construct_invoice_preimage(hrp_bytes, &data_without_signature);
85 let signed_raw_invoice = raw_invoice.sign(|_| keys_manager.sign_invoice(invoice_preimage));
86 match signed_raw_invoice {
87 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
88 Err(e) => Err(SignOrCreationError::SignError(e))
94 use {Currency, Description, InvoiceDescription};
95 use lightning::ln::PaymentHash;
96 use lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY;
97 use lightning::ln::functional_test_utils::*;
98 use lightning::ln::features::InitFeatures;
99 use lightning::ln::msgs::ChannelMessageHandler;
100 use lightning::routing::router;
101 use lightning::routing::scorer::Scorer;
102 use lightning::util::events::MessageSendEventsProvider;
103 use lightning::util::test_utils;
105 fn test_from_channelmanager() {
106 let chanmon_cfgs = create_chanmon_cfgs(2);
107 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
108 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
109 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
110 let _chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
111 let invoice = ::utils::create_invoice_from_channelmanager(&nodes[1].node, nodes[1].keys_manager, Currency::BitcoinTestnet, Some(10_000), "test".to_string()).unwrap();
112 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
113 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
114 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
116 let amt_msat = invoice.amount_pico_btc().unwrap() / 10;
117 let first_hops = nodes[0].node.list_usable_channels();
118 let last_hops = invoice.route_hints();
119 let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
120 let logger = test_utils::TestLogger::new();
121 let scorer = Scorer::new(0);
122 let route = router::get_route(
123 &nodes[0].node.get_our_node_id(),
125 &invoice.recover_payee_pub_key(),
126 Some(invoice.features().unwrap().clone()),
127 Some(&first_hops.iter().collect::<Vec<_>>()),
130 invoice.min_final_cltv_expiry() as u32,
135 let payment_event = {
136 let mut payment_hash = PaymentHash([0; 32]);
137 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
138 nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
139 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
140 assert_eq!(added_monitors.len(), 1);
141 added_monitors.clear();
143 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
144 assert_eq!(events.len(), 1);
145 SendEvent::from_event(events.remove(0))
148 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
149 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
150 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
151 assert_eq!(added_monitors.len(), 1);
152 added_monitors.clear();
153 let events = nodes[1].node.get_and_clear_pending_msg_events();
154 assert_eq!(events.len(), 2);