]> git.bitcoin.ninja Git - rust-lightning/blob - lightning-invoice/src/utils.rs
d489cc69e3eff8760d7b3acbc139e28adc751b80
[rust-lightning] / lightning-invoice / src / utils.rs
1 //! Convenient utilities to create an invoice.
2
3 use {Currency, DEFAULT_EXPIRY_TIME, Invoice, InvoiceBuilder, SignOrCreationError, RawInvoice};
4 use payment::{Payer, Router};
5
6 use bech32::ToBase32;
7 use bitcoin_hashes::Hash;
8 use lightning::chain;
9 use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
10 use lightning::chain::keysinterface::{Sign, KeysInterface};
11 use lightning::ln::{PaymentHash, PaymentSecret};
12 use lightning::ln::channelmanager::{ChannelDetails, ChannelManager, PaymentId, PaymentSendFailure, MIN_FINAL_CLTV_EXPIRY};
13 use lightning::ln::msgs::LightningError;
14 use lightning::routing;
15 use lightning::routing::network_graph::{NetworkGraph, RoutingFees};
16 use lightning::routing::router::{Route, RouteHint, RouteHintHop, RouteParameters, find_route};
17 use lightning::util::logger::Logger;
18 use secp256k1::key::PublicKey;
19 use std::convert::TryInto;
20 use std::ops::Deref;
21
22 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
23 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
24 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
25 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
26 /// that the payment secret is valid when the invoice is paid.
27 pub fn create_invoice_from_channelmanager<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
28         channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
29         amt_msat: Option<u64>, description: String
30 ) -> Result<Invoice, SignOrCreationError<()>>
31 where
32         M::Target: chain::Watch<Signer>,
33         T::Target: BroadcasterInterface,
34         K::Target: KeysInterface<Signer = Signer>,
35         F::Target: FeeEstimator,
36         L::Target: Logger,
37 {
38         // Marshall route hints.
39         let our_channels = channelmanager.list_usable_channels();
40         let mut route_hints = vec![];
41         for channel in our_channels {
42                 let short_channel_id = match channel.short_channel_id {
43                         Some(id) => id,
44                         None => continue,
45                 };
46                 let forwarding_info = match channel.counterparty.forwarding_info {
47                         Some(info) => info,
48                         None => continue,
49                 };
50                 route_hints.push(RouteHint(vec![RouteHintHop {
51                         src_node_id: channel.counterparty.node_id,
52                         short_channel_id,
53                         fees: RoutingFees {
54                                 base_msat: forwarding_info.fee_base_msat,
55                                 proportional_millionths: forwarding_info.fee_proportional_millionths,
56                         },
57                         cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
58                         htlc_minimum_msat: None,
59                         htlc_maximum_msat: None,
60                 }]));
61         }
62
63         let (payment_hash, payment_secret) = channelmanager.create_inbound_payment(
64                 amt_msat,
65                 DEFAULT_EXPIRY_TIME.try_into().unwrap(),
66                 0,
67         );
68         let our_node_pubkey = channelmanager.get_our_node_id();
69         let mut invoice = InvoiceBuilder::new(network)
70                 .description(description)
71                 .current_timestamp()
72                 .payee_pub_key(our_node_pubkey)
73                 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
74                 .payment_secret(payment_secret)
75                 .basic_mpp()
76                 .min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into());
77         if let Some(amt) = amt_msat {
78                 invoice = invoice.amount_milli_satoshis(amt);
79         }
80         for hint in route_hints {
81                 invoice = invoice.private_route(hint);
82         }
83
84         let raw_invoice = match invoice.build_raw() {
85                 Ok(inv) => inv,
86                 Err(e) => return Err(SignOrCreationError::CreationError(e))
87         };
88         let hrp_str = raw_invoice.hrp.to_string();
89         let hrp_bytes = hrp_str.as_bytes();
90         let data_without_signature = raw_invoice.data.to_base32();
91         let invoice_preimage = RawInvoice::construct_invoice_preimage(hrp_bytes, &data_without_signature);
92         let signed_raw_invoice = raw_invoice.sign(|_| keys_manager.sign_invoice(invoice_preimage));
93         match signed_raw_invoice {
94                 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
95                 Err(e) => Err(SignOrCreationError::SignError(e))
96         }
97 }
98
99 /// A [`Router`] implemented using [`find_route`].
100 pub struct DefaultRouter<G, L: Deref> where G: Deref<Target = NetworkGraph>, L::Target: Logger {
101         network_graph: G,
102         logger: L,
103 }
104
105 impl<G, L: Deref> DefaultRouter<G, L> where G: Deref<Target = NetworkGraph>, L::Target: Logger {
106         /// Creates a new router using the given [`NetworkGraph`] and  [`Logger`].
107         pub fn new(network_graph: G, logger: L) -> Self {
108                 Self { network_graph, logger }
109         }
110 }
111
112 impl<G, L: Deref, S: routing::Score> Router<S> for DefaultRouter<G, L>
113 where G: Deref<Target = NetworkGraph>, L::Target: Logger {
114         fn find_route(
115                 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&ChannelDetails]>,
116                 scorer: &S
117         ) -> Result<Route, LightningError> {
118                 find_route(payer, params, &*self.network_graph, first_hops, &*self.logger, scorer)
119         }
120 }
121
122 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Payer for ChannelManager<Signer, M, T, K, F, L>
123 where
124         M::Target: chain::Watch<Signer>,
125         T::Target: BroadcasterInterface,
126         K::Target: KeysInterface<Signer = Signer>,
127         F::Target: FeeEstimator,
128         L::Target: Logger,
129 {
130         fn node_id(&self) -> PublicKey {
131                 self.get_our_node_id()
132         }
133
134         fn first_hops(&self) -> Vec<ChannelDetails> {
135                 self.list_usable_channels()
136         }
137
138         fn send_payment(
139                 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
140         ) -> Result<PaymentId, PaymentSendFailure> {
141                 self.send_payment(route, payment_hash, payment_secret)
142         }
143
144         fn retry_payment(
145                 &self, route: &Route, payment_id: PaymentId
146         ) -> Result<(), PaymentSendFailure> {
147                 self.retry_payment(route, payment_id)
148         }
149 }
150
151 #[cfg(test)]
152 mod test {
153         use {Currency, Description, InvoiceDescription};
154         use lightning::ln::PaymentHash;
155         use lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY;
156         use lightning::ln::functional_test_utils::*;
157         use lightning::ln::features::InitFeatures;
158         use lightning::ln::msgs::ChannelMessageHandler;
159         use lightning::routing::router::{Payee, RouteParameters, find_route};
160         use lightning::routing::scorer::Scorer;
161         use lightning::util::events::MessageSendEventsProvider;
162         use lightning::util::test_utils;
163         #[test]
164         fn test_from_channelmanager() {
165                 let chanmon_cfgs = create_chanmon_cfgs(2);
166                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
167                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
168                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
169                 let _chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
170                 let invoice = ::utils::create_invoice_from_channelmanager(&nodes[1].node, nodes[1].keys_manager, Currency::BitcoinTestnet, Some(10_000), "test".to_string()).unwrap();
171                 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
172                 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
173                 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
174
175                 let payee = Payee::new(invoice.recover_payee_pub_key())
176                         .with_features(invoice.features().unwrap().clone())
177                         .with_route_hints(invoice.route_hints());
178                 let params = RouteParameters {
179                         payee,
180                         final_value_msat: invoice.amount_milli_satoshis().unwrap(),
181                         final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
182                 };
183                 let first_hops = nodes[0].node.list_usable_channels();
184                 let network_graph = node_cfgs[0].network_graph;
185                 let logger = test_utils::TestLogger::new();
186                 let scorer = Scorer::with_fixed_penalty(0);
187                 let route = find_route(
188                         &nodes[0].node.get_our_node_id(), &params, network_graph,
189                         Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer,
190                 ).unwrap();
191
192                 let payment_event = {
193                         let mut payment_hash = PaymentHash([0; 32]);
194                         payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
195                         nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
196                         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
197                         assert_eq!(added_monitors.len(), 1);
198                         added_monitors.clear();
199
200                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
201                         assert_eq!(events.len(), 1);
202                         SendEvent::from_event(events.remove(0))
203
204                 };
205                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
206                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
207                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
208                 assert_eq!(added_monitors.len(), 1);
209                 added_monitors.clear();
210                 let events = nodes[1].node.get_and_clear_pending_msg_events();
211                 assert_eq!(events.len(), 2);
212         }
213 }