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