1 // This file is Copyright its original authors, visible in version control
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
10 //! Convenient utilities for paying Lightning invoices.
12 use crate::Bolt11Invoice;
13 use crate::prelude::*;
15 use bitcoin_hashes::Hash;
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};
22 use lightning::ln::outbound_payment::{ProbeSendFailure, RecipientOnionFields, RetryableSendFailure, Retry};
23 use lightning::routing::router::{PaymentParameters, RouteParameters, Router};
24 use lightning::util::logger::Logger;
28 use core::time::Duration;
30 /// Pays the given [`Bolt11Invoice`], retrying if needed based on [`Retry`].
32 /// [`Bolt11Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
33 /// as the payment is still pending. If the payment succeeds, you must ensure that a second payment
34 /// with the same [`PaymentHash`] is never sent.
36 /// If you wish to use a different payment idempotency token, see [`pay_invoice_with_id`].
37 pub fn pay_invoice<C: Deref>(
38 invoice: &Bolt11Invoice, retry_strategy: Retry, channelmanager: C
39 ) -> Result<PaymentId, PaymentError>
40 where C::Target: AChannelManager,
42 let payment_id = PaymentId(invoice.payment_hash().into_inner());
43 pay_invoice_with_id(invoice, payment_id, retry_strategy, channelmanager.get_cm())
47 /// Pays the given [`Bolt11Invoice`] with a custom idempotency key, retrying if needed based on
50 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
51 /// payment completes or fails, no idempotency guarantees are made.
53 /// You should ensure that the [`Bolt11Invoice::payment_hash`] is unique and the same
54 /// [`PaymentHash`] has never been paid before.
56 /// See [`pay_invoice`] for a variant which uses the [`PaymentHash`] for the idempotency token.
57 pub fn pay_invoice_with_id<C: Deref>(
58 invoice: &Bolt11Invoice, payment_id: PaymentId, retry_strategy: Retry, channelmanager: C
59 ) -> Result<(), PaymentError>
60 where C::Target: AChannelManager,
62 let amt_msat = invoice.amount_milli_satoshis().ok_or(PaymentError::Invoice("amount missing"))?;
63 pay_invoice_using_amount(invoice, amt_msat, payment_id, retry_strategy, channelmanager.get_cm())
66 /// Pays the given zero-value [`Bolt11Invoice`] using the given amount, retrying if needed based on
69 /// [`Bolt11Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
70 /// as the payment is still pending. If the payment succeeds, you must ensure that a second payment
71 /// with the same [`PaymentHash`] is never sent.
73 /// If you wish to use a different payment idempotency token, see
74 /// [`pay_zero_value_invoice_with_id`].
75 pub fn pay_zero_value_invoice<C: Deref>(
76 invoice: &Bolt11Invoice, amount_msats: u64, retry_strategy: Retry, channelmanager: C
77 ) -> Result<PaymentId, PaymentError>
78 where C::Target: AChannelManager,
80 let payment_id = PaymentId(invoice.payment_hash().into_inner());
81 pay_zero_value_invoice_with_id(invoice, amount_msats, payment_id, retry_strategy,
86 /// Pays the given zero-value [`Bolt11Invoice`] using the given amount and custom idempotency key,
87 /// retrying if needed based on [`Retry`].
89 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
90 /// payment completes or fails, no idempotency guarantees are made.
92 /// You should ensure that the [`Bolt11Invoice::payment_hash`] is unique and the same
93 /// [`PaymentHash`] has never been paid before.
95 /// See [`pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the
96 /// idempotency token.
97 pub fn pay_zero_value_invoice_with_id<C: Deref>(
98 invoice: &Bolt11Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
100 ) -> Result<(), PaymentError>
101 where C::Target: AChannelManager,
103 if invoice.amount_milli_satoshis().is_some() {
104 Err(PaymentError::Invoice("amount unexpected"))
106 pay_invoice_using_amount(invoice, amount_msats, payment_id, retry_strategy,
107 channelmanager.get_cm())
111 fn pay_invoice_using_amount<P: Deref>(
112 invoice: &Bolt11Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
114 ) -> Result<(), PaymentError> where P::Target: Payer {
115 let payment_hash = PaymentHash((*invoice.payment_hash()).into_inner());
116 let mut recipient_onion = RecipientOnionFields::secret_only(*invoice.payment_secret());
117 recipient_onion.payment_metadata = invoice.payment_metadata().map(|v| v.clone());
118 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(),
119 invoice.min_final_cltv_expiry_delta() as u32)
120 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
121 .with_route_hints(invoice.route_hints()).unwrap();
122 if let Some(features) = invoice.features() {
123 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
125 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msats);
127 payer.send_payment(payment_hash, recipient_onion, payment_id, route_params, retry_strategy)
130 /// Sends payment probes over all paths of a route that would be used to pay the given invoice.
132 /// See [`ChannelManager::send_preflight_probes`] for more information.
133 pub fn preflight_probe_invoice<C: Deref>(
134 invoice: &Bolt11Invoice, channelmanager: C, liquidity_limit_multiplier: Option<u64>,
135 ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbingError>
136 where C::Target: AChannelManager,
138 let amount_msat = if let Some(invoice_amount_msat) = invoice.amount_milli_satoshis() {
141 return Err(ProbingError::Invoice("Failed to send probe as no amount was given in the invoice."));
144 let mut payment_params = PaymentParameters::from_node_id(
145 invoice.recover_payee_pub_key(),
146 invoice.min_final_cltv_expiry_delta() as u32,
148 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
149 .with_route_hints(invoice.route_hints())
152 if let Some(features) = invoice.features() {
153 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
155 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
157 channelmanager.get_cm().send_preflight_probes(route_params, liquidity_limit_multiplier)
158 .map_err(ProbingError::Sending)
161 /// Sends payment probes over all paths of a route that would be used to pay the given zero-value
162 /// invoice using the given amount.
164 /// See [`ChannelManager::send_preflight_probes`] for more information.
165 pub fn preflight_probe_zero_value_invoice<C: Deref>(
166 invoice: &Bolt11Invoice, amount_msat: u64, channelmanager: C,
167 liquidity_limit_multiplier: Option<u64>,
168 ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbingError>
169 where C::Target: AChannelManager,
171 if invoice.amount_milli_satoshis().is_some() {
172 return Err(ProbingError::Invoice("amount unexpected"));
175 let mut payment_params = PaymentParameters::from_node_id(
176 invoice.recover_payee_pub_key(),
177 invoice.min_final_cltv_expiry_delta() as u32,
179 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
180 .with_route_hints(invoice.route_hints())
183 if let Some(features) = invoice.features() {
184 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
186 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
188 channelmanager.get_cm().send_preflight_probes(route_params, liquidity_limit_multiplier)
189 .map_err(ProbingError::Sending)
192 fn expiry_time_from_unix_epoch(invoice: &Bolt11Invoice) -> Duration {
193 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
196 /// An error that may occur when making a payment.
197 #[derive(Clone, Debug, PartialEq, Eq)]
198 pub enum PaymentError {
199 /// An error resulting from the provided [`Bolt11Invoice`] or payment hash.
200 Invoice(&'static str),
201 /// An error occurring when sending a payment.
202 Sending(RetryableSendFailure),
205 /// An error that may occur when sending a payment probe.
206 #[derive(Clone, Debug, PartialEq, Eq)]
207 pub enum ProbingError {
208 /// An error resulting from the provided [`Bolt11Invoice`].
209 Invoice(&'static str),
210 /// An error occurring when sending a payment probe.
211 Sending(ProbeSendFailure),
214 /// A trait defining behavior of a [`Bolt11Invoice`] payer.
216 /// Useful for unit testing internal methods.
218 /// Sends a payment over the Lightning Network using the given [`Route`].
220 /// [`Route`]: lightning::routing::router::Route
222 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
223 payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry
224 ) -> Result<(), PaymentError>;
227 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>
229 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
230 T::Target: BroadcasterInterface,
231 ES::Target: EntropySource,
232 NS::Target: NodeSigner,
233 SP::Target: SignerProvider,
234 F::Target: FeeEstimator,
239 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
240 payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry
241 ) -> Result<(), PaymentError> {
242 self.send_payment(payment_hash, recipient_onion, payment_id, route_params, retry_strategy)
243 .map_err(PaymentError::Sending)
250 use crate::{InvoiceBuilder, Currency};
251 use bitcoin_hashes::sha256::Hash as Sha256;
252 use lightning::events::Event;
253 use lightning::ln::msgs::ChannelMessageHandler;
254 use lightning::ln::{PaymentPreimage, PaymentSecret};
255 use lightning::ln::functional_test_utils::*;
256 use secp256k1::{SecretKey, Secp256k1};
257 use std::collections::VecDeque;
258 use std::time::{SystemTime, Duration};
261 expectations: core::cell::RefCell<VecDeque<Amount>>,
267 expectations: core::cell::RefCell::new(VecDeque::new()),
271 fn expect_send(self, value_msat: Amount) -> Self {
272 self.expectations.borrow_mut().push_back(value_msat);
276 fn check_value_msats(&self, actual_value_msats: Amount) {
277 let expected_value_msats = self.expectations.borrow_mut().pop_front();
278 if let Some(expected_value_msats) = expected_value_msats {
279 assert_eq!(actual_value_msats, expected_value_msats);
281 panic!("Unexpected amount: {:?}", actual_value_msats);
286 #[derive(Clone, Debug, PartialEq, Eq)]
287 struct Amount(u64); // msat
289 impl Payer for TestPayer {
291 &self, _payment_hash: PaymentHash, _recipient_onion: RecipientOnionFields,
292 _payment_id: PaymentId, route_params: RouteParameters, _retry_strategy: Retry
293 ) -> Result<(), PaymentError> {
294 self.check_value_msats(Amount(route_params.final_value_msat));
299 impl Drop for TestPayer {
301 if std::thread::panicking() {
305 if !self.expectations.borrow().is_empty() {
306 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
311 fn duration_since_epoch() -> Duration {
312 #[cfg(feature = "std")]
313 let duration_since_epoch =
314 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
315 #[cfg(not(feature = "std"))]
316 let duration_since_epoch = Duration::from_secs(1234567);
320 fn invoice(payment_preimage: PaymentPreimage) -> Bolt11Invoice {
321 let payment_hash = Sha256::hash(&payment_preimage.0);
322 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
324 InvoiceBuilder::new(Currency::Bitcoin)
325 .description("test".into())
326 .payment_hash(payment_hash)
327 .payment_secret(PaymentSecret([0; 32]))
328 .duration_since_epoch(duration_since_epoch())
329 .min_final_cltv_expiry_delta(144)
330 .amount_milli_satoshis(128)
331 .build_signed(|hash| {
332 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
337 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Bolt11Invoice {
338 let payment_hash = Sha256::hash(&payment_preimage.0);
339 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
341 InvoiceBuilder::new(Currency::Bitcoin)
342 .description("test".into())
343 .payment_hash(payment_hash)
344 .payment_secret(PaymentSecret([0; 32]))
345 .duration_since_epoch(duration_since_epoch())
346 .min_final_cltv_expiry_delta(144)
347 .build_signed(|hash| {
348 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
355 let payment_id = PaymentId([42; 32]);
356 let payment_preimage = PaymentPreimage([1; 32]);
357 let invoice = invoice(payment_preimage);
358 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
360 let payer = TestPayer::new().expect_send(Amount(final_value_msat));
361 pay_invoice_using_amount(&invoice, final_value_msat, payment_id, Retry::Attempts(0), &payer).unwrap();
365 fn pays_zero_value_invoice() {
366 let payment_id = PaymentId([42; 32]);
367 let payment_preimage = PaymentPreimage([1; 32]);
368 let invoice = zero_value_invoice(payment_preimage);
369 let amt_msat = 10_000;
371 let payer = TestPayer::new().expect_send(Amount(amt_msat));
372 pay_invoice_using_amount(&invoice, amt_msat, payment_id, Retry::Attempts(0), &payer).unwrap();
376 fn fails_paying_zero_value_invoice_with_amount() {
377 let chanmon_cfgs = create_chanmon_cfgs(1);
378 let node_cfgs = create_node_cfgs(1, &chanmon_cfgs);
379 let node_chanmgrs = create_node_chanmgrs(1, &node_cfgs, &[None]);
380 let nodes = create_network(1, &node_cfgs, &node_chanmgrs);
382 let payment_preimage = PaymentPreimage([1; 32]);
383 let invoice = invoice(payment_preimage);
384 let amt_msat = 10_000;
386 match pay_zero_value_invoice(&invoice, amt_msat, Retry::Attempts(0), nodes[0].node) {
387 Err(PaymentError::Invoice("amount unexpected")) => {},
393 #[cfg(feature = "std")]
394 fn payment_metadata_end_to_end() {
395 // Test that a payment metadata read from an invoice passed to `pay_invoice` makes it all
396 // the way out through the `PaymentClaimable` event.
397 let chanmon_cfgs = create_chanmon_cfgs(2);
398 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
399 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
400 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
401 create_announced_chan_between_nodes(&nodes, 0, 1);
403 let payment_metadata = vec![42, 43, 44, 45, 46, 47, 48, 49, 42];
405 let (payment_hash, payment_secret) =
406 nodes[1].node.create_inbound_payment(None, 7200, None).unwrap();
408 let invoice = InvoiceBuilder::new(Currency::Bitcoin)
409 .description("test".into())
410 .payment_hash(Sha256::from_slice(&payment_hash.0).unwrap())
411 .payment_secret(payment_secret)
413 .min_final_cltv_expiry_delta(144)
414 .amount_milli_satoshis(50_000)
415 .payment_metadata(payment_metadata.clone())
416 .build_signed(|hash| {
417 Secp256k1::new().sign_ecdsa_recoverable(hash,
418 &nodes[1].keys_manager.backing.get_node_secret_key())
422 pay_invoice(&invoice, Retry::Attempts(0), nodes[0].node).unwrap();
423 check_added_monitors(&nodes[0], 1);
424 let send_event = SendEvent::from_node(&nodes[0]);
425 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
426 commitment_signed_dance!(nodes[1], nodes[0], &send_event.commitment_msg, false);
428 expect_pending_htlcs_forwardable!(nodes[1]);
430 let mut events = nodes[1].node.get_and_clear_pending_events();
431 assert_eq!(events.len(), 1);
432 match events.pop().unwrap() {
433 Event::PaymentClaimable { onion_fields, .. } => {
434 assert_eq!(Some(payment_metadata), onion_fields.unwrap().payment_metadata);
436 _ => panic!("Unexpected event")