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