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