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