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