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