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