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