70df3c4553134bbe675253af349520521924a6bb
[rust-lightning] / lightning-invoice / src / utils.rs
1 //! Convenient utilities to create an invoice.
2 use {Currency, Invoice, InvoiceBuilder, SignOrCreationError, RawInvoice};
3 use bech32::ToBase32;
4 use bitcoin_hashes::Hash;
5 use lightning::chain;
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::RouteHintHop;
11 use lightning::util::logger::Logger;
12 use std::ops::Deref;
13
14 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
15 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
16 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
17 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
18 /// that the payment secret is valid when the invoice is paid.
19 pub fn create_invoice_from_channelmanager<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
20         channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
21         amt_msat: Option<u64>, description: String
22 ) -> Result<Invoice, SignOrCreationError<()>>
23 where
24         M::Target: chain::Watch<Signer>,
25         T::Target: BroadcasterInterface,
26         K::Target: KeysInterface<Signer = Signer>,
27         F::Target: FeeEstimator,
28         L::Target: Logger,
29 {
30         // Marshall route hints.
31         let our_channels = channelmanager.list_usable_channels();
32         let mut route_hints = vec![];
33         for channel in our_channels {
34                 let short_channel_id = match channel.short_channel_id {
35                         Some(id) => id,
36                         None => continue,
37                 };
38                 let forwarding_info = match channel.counterparty_forwarding_info {
39                         Some(info) => info,
40                         None => continue,
41                 };
42                 route_hints.push(vec![RouteHintHop {
43                         src_node_id: channel.remote_network_id,
44                         short_channel_id,
45                         fees: RoutingFees {
46                                 base_msat: forwarding_info.fee_base_msat,
47                                 proportional_millionths: forwarding_info.fee_proportional_millionths,
48                         },
49                         cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
50                         htlc_minimum_msat: None,
51                         htlc_maximum_msat: None,
52                 }]);
53         }
54
55         let (payment_hash, payment_secret) = channelmanager.create_inbound_payment(
56                 amt_msat,
57                 7200, // default invoice expiry is 2 hours
58                 0,
59         );
60         let our_node_pubkey = channelmanager.get_our_node_id();
61         let mut invoice = InvoiceBuilder::new(network)
62                 .description(description)
63                 .current_timestamp()
64                 .payee_pub_key(our_node_pubkey)
65                 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
66                 .payment_secret(payment_secret)
67                 .basic_mpp()
68                 .min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into());
69         if let Some(amt) = amt_msat {
70                 invoice = invoice.amount_pico_btc(amt * 10);
71         }
72         for hint in route_hints.drain(..) {
73                 invoice = invoice.route(hint);
74         }
75
76         let raw_invoice = match invoice.build_raw() {
77                 Ok(inv) => inv,
78                 Err(e) => return Err(SignOrCreationError::CreationError(e))
79         };
80         let hrp_str = raw_invoice.hrp.to_string();
81         let hrp_bytes = hrp_str.as_bytes();
82         let data_without_signature = raw_invoice.data.to_base32();
83         let invoice_preimage = RawInvoice::construct_invoice_preimage(hrp_bytes, &data_without_signature);
84         let signed_raw_invoice = raw_invoice.sign(|_| keys_manager.sign_invoice(invoice_preimage));
85         match signed_raw_invoice {
86                 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
87                 Err(e) => Err(SignOrCreationError::SignError(e))
88         }
89 }
90
91 #[cfg(test)]
92 mod test {
93         use {Currency, Description, InvoiceDescription};
94         use lightning::ln::PaymentHash;
95         use lightning::ln::functional_test_utils::*;
96         use lightning::ln::features::InitFeatures;
97         use lightning::ln::msgs::ChannelMessageHandler;
98         use lightning::routing::router;
99         use lightning::util::events::MessageSendEventsProvider;
100         use lightning::util::test_utils;
101         #[test]
102         fn test_from_channelmanager() {
103                 let chanmon_cfgs = create_chanmon_cfgs(2);
104                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
105                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
106                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
107                 let _chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
108                 let invoice = ::utils::create_invoice_from_channelmanager(&nodes[1].node, nodes[1].keys_manager, Currency::BitcoinTestnet, Some(10_000), "test".to_string()).unwrap();
109                 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
110                 assert_eq!(invoice.min_final_cltv_expiry(), 9);
111                 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
112
113                 let mut route_hints = invoice.routes().clone();
114                 let mut last_hops = Vec::new();
115                 for hint in route_hints.drain(..) {
116                         last_hops.push(hint[hint.len() - 1].clone());
117                 }
118                 let amt_msat = invoice.amount_pico_btc().unwrap() / 10;
119
120                 let first_hops = nodes[0].node.list_usable_channels();
121                 let network_graph = nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
122                 let logger = test_utils::TestLogger::new();
123                 let route = router::get_route(
124                         &nodes[0].node.get_our_node_id(),
125                         &network_graph,
126                         &invoice.recover_payee_pub_key(),
127                         Some(invoice.features().unwrap().clone()),
128                         Some(&first_hops.iter().collect::<Vec<_>>()),
129                         &last_hops.iter().collect::<Vec<_>>(),
130                         amt_msat,
131                         invoice.min_final_cltv_expiry() as u32,
132                         &logger,
133                 ).unwrap();
134
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().unwrap().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();
142
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))
146
147                 };
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);
155         }
156 }