Use `crate::prelude::*` to load `Vec`, rather than `crate::Vec`
[rust-lightning] / lightning-invoice / src / payment.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Convenient utilities for paying Lightning invoices.
11
12 use crate::Bolt11Invoice;
13 use crate::prelude::*;
14
15 use bitcoin_hashes::Hash;
16
17 use lightning::chain;
18 use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
19 use lightning::sign::{NodeSigner, SignerProvider, EntropySource};
20 use lightning::ln::PaymentHash;
21 use lightning::ln::channelmanager::{AChannelManager, ChannelManager, PaymentId, Retry, RetryableSendFailure, RecipientOnionFields, ProbeSendFailure};
22 use lightning::routing::router::{PaymentParameters, RouteParameters, Router};
23 use lightning::util::logger::Logger;
24
25 use core::fmt::Debug;
26 use core::ops::Deref;
27 use core::time::Duration;
28
29 /// Pays the given [`Bolt11Invoice`], retrying if needed based on [`Retry`].
30 ///
31 /// [`Bolt11Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
32 /// as the payment is still pending. If the payment succeeds, you must ensure that a second payment
33 /// with the same [`PaymentHash`] is never sent.
34 ///
35 /// If you wish to use a different payment idempotency token, see [`pay_invoice_with_id`].
36 pub fn pay_invoice<C: AChannelManager>(
37         invoice: &Bolt11Invoice, retry_strategy: Retry, channelmanager: &C
38 ) -> Result<PaymentId, PaymentError>
39 {
40         let payment_id = PaymentId(invoice.payment_hash().into_inner());
41         pay_invoice_with_id(invoice, payment_id, retry_strategy, channelmanager.get_cm())
42                 .map(|()| payment_id)
43 }
44
45 /// Pays the given [`Bolt11Invoice`] with a custom idempotency key, retrying if needed based on
46 /// [`Retry`].
47 ///
48 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
49 /// payment completes or fails, no idempotency guarantees are made.
50 ///
51 /// You should ensure that the [`Bolt11Invoice::payment_hash`] is unique and the same
52 /// [`PaymentHash`] has never been paid before.
53 ///
54 /// See [`pay_invoice`] for a variant which uses the [`PaymentHash`] for the idempotency token.
55 pub fn pay_invoice_with_id<C: AChannelManager>(
56         invoice: &Bolt11Invoice, payment_id: PaymentId, retry_strategy: Retry, channelmanager: &C
57 ) -> Result<(), PaymentError>
58 {
59         let amt_msat = invoice.amount_milli_satoshis().ok_or(PaymentError::Invoice("amount missing"))?;
60         pay_invoice_using_amount(invoice, amt_msat, payment_id, retry_strategy, channelmanager.get_cm())
61 }
62
63 /// Pays the given zero-value [`Bolt11Invoice`] using the given amount, retrying if needed based on
64 /// [`Retry`].
65 ///
66 /// [`Bolt11Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
67 /// as the payment is still pending. If the payment succeeds, you must ensure that a second payment
68 /// with the same [`PaymentHash`] is never sent.
69 ///
70 /// If you wish to use a different payment idempotency token, see
71 /// [`pay_zero_value_invoice_with_id`].
72 pub fn pay_zero_value_invoice<C: AChannelManager>(
73         invoice: &Bolt11Invoice, amount_msats: u64, retry_strategy: Retry, channelmanager: &C
74 ) -> Result<PaymentId, PaymentError>
75 {
76         let payment_id = PaymentId(invoice.payment_hash().into_inner());
77         pay_zero_value_invoice_with_id(invoice, amount_msats, payment_id, retry_strategy,
78                 channelmanager)
79                 .map(|()| payment_id)
80 }
81
82 /// Pays the given zero-value [`Bolt11Invoice`] using the given amount and custom idempotency key,
83 /// retrying if needed based on [`Retry`].
84 ///
85 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
86 /// payment completes or fails, no idempotency guarantees are made.
87 ///
88 /// You should ensure that the [`Bolt11Invoice::payment_hash`] is unique and the same
89 /// [`PaymentHash`] has never been paid before.
90 ///
91 /// See [`pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the
92 /// idempotency token.
93 pub fn pay_zero_value_invoice_with_id<C: AChannelManager>(
94         invoice: &Bolt11Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
95         channelmanager: &C
96 ) -> Result<(), PaymentError>
97 {
98         if invoice.amount_milli_satoshis().is_some() {
99                 Err(PaymentError::Invoice("amount unexpected"))
100         } else {
101                 pay_invoice_using_amount(invoice, amount_msats, payment_id, retry_strategy,
102                         channelmanager.get_cm())
103         }
104 }
105
106 fn pay_invoice_using_amount<P: Deref>(
107         invoice: &Bolt11Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
108         payer: P
109 ) -> Result<(), PaymentError> where P::Target: Payer {
110         let payment_hash = PaymentHash((*invoice.payment_hash()).into_inner());
111         let mut recipient_onion = RecipientOnionFields::secret_only(*invoice.payment_secret());
112         recipient_onion.payment_metadata = invoice.payment_metadata().map(|v| v.clone());
113         let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(),
114                 invoice.min_final_cltv_expiry_delta() as u32)
115                 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
116                 .with_route_hints(invoice.route_hints()).unwrap();
117         if let Some(features) = invoice.features() {
118                 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
119         }
120         let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msats);
121
122         payer.send_payment(payment_hash, recipient_onion, payment_id, route_params, retry_strategy)
123 }
124
125 /// Sends payment probes over all paths of a route that would be used to pay the given invoice.
126 ///
127 /// See [`ChannelManager::send_preflight_probes`] for more information.
128 pub fn preflight_probe_invoice<C: AChannelManager>(
129         invoice: &Bolt11Invoice, channelmanager: &C, liquidity_limit_multiplier: Option<u64>,
130 ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbingError>
131 {
132         let amount_msat = if let Some(invoice_amount_msat) = invoice.amount_milli_satoshis() {
133                 invoice_amount_msat
134         } else {
135                 return Err(ProbingError::Invoice("Failed to send probe as no amount was given in the invoice."));
136         };
137
138         let mut payment_params = PaymentParameters::from_node_id(
139                 invoice.recover_payee_pub_key(),
140                 invoice.min_final_cltv_expiry_delta() as u32,
141         )
142         .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
143         .with_route_hints(invoice.route_hints())
144         .unwrap();
145
146         if let Some(features) = invoice.features() {
147                 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
148         }
149         let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
150
151         channelmanager.get_cm().send_preflight_probes(route_params, liquidity_limit_multiplier)
152                 .map_err(ProbingError::Sending)
153 }
154
155 /// Sends payment probes over all paths of a route that would be used to pay the given zero-value
156 /// invoice using the given amount.
157 ///
158 /// See [`ChannelManager::send_preflight_probes`] for more information.
159 pub fn preflight_probe_zero_value_invoice<C: AChannelManager>(
160         invoice: &Bolt11Invoice, amount_msat: u64, channelmanager: &C,
161         liquidity_limit_multiplier: Option<u64>,
162 ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbingError>
163 {
164         if invoice.amount_milli_satoshis().is_some() {
165                 return Err(ProbingError::Invoice("amount unexpected"));
166         }
167
168         let mut payment_params = PaymentParameters::from_node_id(
169                 invoice.recover_payee_pub_key(),
170                 invoice.min_final_cltv_expiry_delta() as u32,
171         )
172         .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
173         .with_route_hints(invoice.route_hints())
174         .unwrap();
175
176         if let Some(features) = invoice.features() {
177                 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
178         }
179         let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
180
181         channelmanager.get_cm().send_preflight_probes(route_params, liquidity_limit_multiplier)
182                 .map_err(ProbingError::Sending)
183 }
184
185 fn expiry_time_from_unix_epoch(invoice: &Bolt11Invoice) -> Duration {
186         invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
187 }
188
189 /// An error that may occur when making a payment.
190 #[derive(Clone, Debug, PartialEq, Eq)]
191 pub enum PaymentError {
192         /// An error resulting from the provided [`Bolt11Invoice`] or payment hash.
193         Invoice(&'static str),
194         /// An error occurring when sending a payment.
195         Sending(RetryableSendFailure),
196 }
197
198 /// An error that may occur when sending a payment probe.
199 #[derive(Clone, Debug, PartialEq, Eq)]
200 pub enum ProbingError {
201         /// An error resulting from the provided [`Bolt11Invoice`].
202         Invoice(&'static str),
203         /// An error occurring when sending a payment probe.
204         Sending(ProbeSendFailure),
205 }
206
207 /// A trait defining behavior of a [`Bolt11Invoice`] payer.
208 ///
209 /// Useful for unit testing internal methods.
210 trait Payer {
211         /// Sends a payment over the Lightning Network using the given [`Route`].
212         ///
213         /// [`Route`]: lightning::routing::router::Route
214         fn send_payment(
215                 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
216                 payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry
217         ) -> Result<(), PaymentError>;
218 }
219
220 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> Payer for ChannelManager<M, T, ES, NS, SP, F, R, L>
221 where
222                 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
223                 T::Target: BroadcasterInterface,
224                 ES::Target: EntropySource,
225                 NS::Target: NodeSigner,
226                 SP::Target: SignerProvider,
227                 F::Target: FeeEstimator,
228                 R::Target: Router,
229                 L::Target: Logger,
230 {
231         fn send_payment(
232                 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
233                 payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry
234         ) -> Result<(), PaymentError> {
235                 self.send_payment(payment_hash, recipient_onion, payment_id, route_params, retry_strategy)
236                         .map_err(PaymentError::Sending)
237         }
238 }
239
240 #[cfg(test)]
241 mod tests {
242         use super::*;
243         use crate::{InvoiceBuilder, Currency};
244         use bitcoin_hashes::sha256::Hash as Sha256;
245         use lightning::events::Event;
246         use lightning::ln::msgs::ChannelMessageHandler;
247         use lightning::ln::{PaymentPreimage, PaymentSecret};
248         use lightning::ln::functional_test_utils::*;
249         use secp256k1::{SecretKey, Secp256k1};
250         use std::collections::VecDeque;
251         use std::time::{SystemTime, Duration};
252
253         struct TestPayer {
254                 expectations: core::cell::RefCell<VecDeque<Amount>>,
255         }
256
257         impl TestPayer {
258                 fn new() -> Self {
259                         Self {
260                                 expectations: core::cell::RefCell::new(VecDeque::new()),
261                         }
262                 }
263
264                 fn expect_send(self, value_msat: Amount) -> Self {
265                         self.expectations.borrow_mut().push_back(value_msat);
266                         self
267                 }
268
269                 fn check_value_msats(&self, actual_value_msats: Amount) {
270                         let expected_value_msats = self.expectations.borrow_mut().pop_front();
271                         if let Some(expected_value_msats) = expected_value_msats {
272                                 assert_eq!(actual_value_msats, expected_value_msats);
273                         } else {
274                                 panic!("Unexpected amount: {:?}", actual_value_msats);
275                         }
276                 }
277         }
278
279         #[derive(Clone, Debug, PartialEq, Eq)]
280         struct Amount(u64); // msat
281
282         impl Payer for TestPayer {
283                 fn send_payment(
284                         &self, _payment_hash: PaymentHash, _recipient_onion: RecipientOnionFields,
285                         _payment_id: PaymentId, route_params: RouteParameters, _retry_strategy: Retry
286                 ) -> Result<(), PaymentError> {
287                         self.check_value_msats(Amount(route_params.final_value_msat));
288                         Ok(())
289                 }
290         }
291
292         impl Drop for TestPayer {
293                 fn drop(&mut self) {
294                         if std::thread::panicking() {
295                                 return;
296                         }
297
298                         if !self.expectations.borrow().is_empty() {
299                                 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
300                         }
301                 }
302         }
303
304         fn duration_since_epoch() -> Duration {
305                 #[cfg(feature = "std")]
306                 let duration_since_epoch =
307                         SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
308                 #[cfg(not(feature = "std"))]
309                 let duration_since_epoch = Duration::from_secs(1234567);
310                 duration_since_epoch
311         }
312
313         fn invoice(payment_preimage: PaymentPreimage) -> Bolt11Invoice {
314                 let payment_hash = Sha256::hash(&payment_preimage.0);
315                 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
316
317                 InvoiceBuilder::new(Currency::Bitcoin)
318                         .description("test".into())
319                         .payment_hash(payment_hash)
320                         .payment_secret(PaymentSecret([0; 32]))
321                         .duration_since_epoch(duration_since_epoch())
322                         .min_final_cltv_expiry_delta(144)
323                         .amount_milli_satoshis(128)
324                         .build_signed(|hash| {
325                                 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
326                         })
327                         .unwrap()
328         }
329
330         fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Bolt11Invoice {
331                 let payment_hash = Sha256::hash(&payment_preimage.0);
332                 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
333
334                 InvoiceBuilder::new(Currency::Bitcoin)
335                         .description("test".into())
336                         .payment_hash(payment_hash)
337                         .payment_secret(PaymentSecret([0; 32]))
338                         .duration_since_epoch(duration_since_epoch())
339                         .min_final_cltv_expiry_delta(144)
340                         .build_signed(|hash| {
341                                 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
342                         })
343                 .unwrap()
344         }
345
346         #[test]
347         fn pays_invoice() {
348                 let payment_id = PaymentId([42; 32]);
349                 let payment_preimage = PaymentPreimage([1; 32]);
350                 let invoice = invoice(payment_preimage);
351                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
352
353                 let payer = TestPayer::new().expect_send(Amount(final_value_msat));
354                 pay_invoice_using_amount(&invoice, final_value_msat, payment_id, Retry::Attempts(0), &payer).unwrap();
355         }
356
357         #[test]
358         fn pays_zero_value_invoice() {
359                 let payment_id = PaymentId([42; 32]);
360                 let payment_preimage = PaymentPreimage([1; 32]);
361                 let invoice = zero_value_invoice(payment_preimage);
362                 let amt_msat = 10_000;
363
364                 let payer = TestPayer::new().expect_send(Amount(amt_msat));
365                 pay_invoice_using_amount(&invoice, amt_msat, payment_id, Retry::Attempts(0), &payer).unwrap();
366         }
367
368         #[test]
369         fn fails_paying_zero_value_invoice_with_amount() {
370                 let chanmon_cfgs = create_chanmon_cfgs(1);
371                 let node_cfgs = create_node_cfgs(1, &chanmon_cfgs);
372                 let node_chanmgrs = create_node_chanmgrs(1, &node_cfgs, &[None]);
373                 let nodes = create_network(1, &node_cfgs, &node_chanmgrs);
374
375                 let payment_preimage = PaymentPreimage([1; 32]);
376                 let invoice = invoice(payment_preimage);
377                 let amt_msat = 10_000;
378
379                 match pay_zero_value_invoice(&invoice, amt_msat, Retry::Attempts(0), nodes[0].node) {
380                         Err(PaymentError::Invoice("amount unexpected")) => {},
381                         _ => panic!()
382                 }
383         }
384
385         #[test]
386         #[cfg(feature = "std")]
387         fn payment_metadata_end_to_end() {
388                 // Test that a payment metadata read from an invoice passed to `pay_invoice` makes it all
389                 // the way out through the `PaymentClaimable` event.
390                 let chanmon_cfgs = create_chanmon_cfgs(2);
391                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
392                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
393                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
394                 create_announced_chan_between_nodes(&nodes, 0, 1);
395
396                 let payment_metadata = vec![42, 43, 44, 45, 46, 47, 48, 49, 42];
397
398                 let (payment_hash, payment_secret) =
399                         nodes[1].node.create_inbound_payment(None, 7200, None).unwrap();
400
401                 let invoice = InvoiceBuilder::new(Currency::Bitcoin)
402                         .description("test".into())
403                         .payment_hash(Sha256::from_slice(&payment_hash.0).unwrap())
404                         .payment_secret(payment_secret)
405                         .current_timestamp()
406                         .min_final_cltv_expiry_delta(144)
407                         .amount_milli_satoshis(50_000)
408                         .payment_metadata(payment_metadata.clone())
409                         .build_signed(|hash| {
410                                 Secp256k1::new().sign_ecdsa_recoverable(hash,
411                                         &nodes[1].keys_manager.backing.get_node_secret_key())
412                         })
413                         .unwrap();
414
415                 pay_invoice(&invoice, Retry::Attempts(0), nodes[0].node).unwrap();
416                 check_added_monitors(&nodes[0], 1);
417                 let send_event = SendEvent::from_node(&nodes[0]);
418                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
419                 commitment_signed_dance!(nodes[1], nodes[0], &send_event.commitment_msg, false);
420
421                 expect_pending_htlcs_forwardable!(nodes[1]);
422
423                 let mut events = nodes[1].node.get_and_clear_pending_events();
424                 assert_eq!(events.len(), 1);
425                 match events.pop().unwrap() {
426                         Event::PaymentClaimable { onion_fields, .. } => {
427                                 assert_eq!(Some(payment_metadata), onion_fields.unwrap().payment_metadata);
428                         },
429                         _ => panic!("Unexpected event")
430                 }
431         }
432 }