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