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, Retry, RetryableSendFailure, RecipientOnionFields, ProbeSendFailure};
22 use lightning::routing::router::{PaymentParameters, RouteParameters, Router};
23 use lightning::util::logger::Logger;
27 use core::time::Duration;
29 /// Pays the given [`Bolt11Invoice`], retrying if needed based on [`Retry`].
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.
35 /// If you wish to use a different payment idempotency token, see [`pay_invoice_with_id`].
36 pub fn pay_invoice<C: AChannelManager>(
37 invoice: &Bolt11Invoice, retry_strategy: Retry, channelmanager: &C
38 ) -> Result<PaymentId, PaymentError>
40 let payment_id = PaymentId(invoice.payment_hash().into_inner());
41 pay_invoice_with_id(invoice, payment_id, retry_strategy, channelmanager.get_cm())
45 /// Pays the given [`Bolt11Invoice`] with a custom idempotency key, retrying if needed based on
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.
51 /// You should ensure that the [`Bolt11Invoice::payment_hash`] is unique and the same
52 /// [`PaymentHash`] has never been paid before.
54 /// See [`pay_invoice`] for a variant which uses the [`PaymentHash`] for the idempotency token.
55 pub fn pay_invoice_with_id<C: AChannelManager>(
56 invoice: &Bolt11Invoice, payment_id: PaymentId, retry_strategy: Retry, channelmanager: &C
57 ) -> Result<(), PaymentError>
59 let amt_msat = invoice.amount_milli_satoshis().ok_or(PaymentError::Invoice("amount missing"))?;
60 pay_invoice_using_amount(invoice, amt_msat, payment_id, retry_strategy, channelmanager.get_cm())
63 /// Pays the given zero-value [`Bolt11Invoice`] using the given amount, retrying if needed based on
66 /// [`Bolt11Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
67 /// as the payment is still pending. If the payment succeeds, you must ensure that a second payment
68 /// with the same [`PaymentHash`] is never sent.
70 /// If you wish to use a different payment idempotency token, see
71 /// [`pay_zero_value_invoice_with_id`].
72 pub fn pay_zero_value_invoice<C: AChannelManager>(
73 invoice: &Bolt11Invoice, amount_msats: u64, retry_strategy: Retry, channelmanager: &C
74 ) -> Result<PaymentId, PaymentError>
76 let payment_id = PaymentId(invoice.payment_hash().into_inner());
77 pay_zero_value_invoice_with_id(invoice, amount_msats, payment_id, retry_strategy,
82 /// Pays the given zero-value [`Bolt11Invoice`] using the given amount and custom idempotency key,
83 /// retrying if needed based on [`Retry`].
85 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
86 /// payment completes or fails, no idempotency guarantees are made.
88 /// You should ensure that the [`Bolt11Invoice::payment_hash`] is unique and the same
89 /// [`PaymentHash`] has never been paid before.
91 /// See [`pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the
92 /// idempotency token.
93 pub fn pay_zero_value_invoice_with_id<C: AChannelManager>(
94 invoice: &Bolt11Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
96 ) -> Result<(), PaymentError>
98 if invoice.amount_milli_satoshis().is_some() {
99 Err(PaymentError::Invoice("amount unexpected"))
101 pay_invoice_using_amount(invoice, amount_msats, payment_id, retry_strategy,
102 channelmanager.get_cm())
106 fn pay_invoice_using_amount<P: Deref>(
107 invoice: &Bolt11Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
109 ) -> Result<(), PaymentError> where P::Target: Payer {
110 let payment_hash = PaymentHash((*invoice.payment_hash()).into_inner());
111 let mut recipient_onion = RecipientOnionFields::secret_only(*invoice.payment_secret());
112 recipient_onion.payment_metadata = invoice.payment_metadata().map(|v| v.clone());
113 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(),
114 invoice.min_final_cltv_expiry_delta() as u32)
115 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
116 .with_route_hints(invoice.route_hints()).unwrap();
117 if let Some(features) = invoice.features() {
118 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
120 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msats);
122 payer.send_payment(payment_hash, recipient_onion, payment_id, route_params, retry_strategy)
125 /// Sends payment probes over all paths of a route that would be used to pay the given invoice.
127 /// See [`ChannelManager::send_preflight_probes`] for more information.
128 pub fn preflight_probe_invoice<C: AChannelManager>(
129 invoice: &Bolt11Invoice, channelmanager: &C, liquidity_limit_multiplier: Option<u64>,
130 ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbingError>
132 let amount_msat = if let Some(invoice_amount_msat) = invoice.amount_milli_satoshis() {
135 return Err(ProbingError::Invoice("Failed to send probe as no amount was given in the invoice."));
138 let mut payment_params = PaymentParameters::from_node_id(
139 invoice.recover_payee_pub_key(),
140 invoice.min_final_cltv_expiry_delta() as u32,
142 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
143 .with_route_hints(invoice.route_hints())
146 if let Some(features) = invoice.features() {
147 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
149 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
151 channelmanager.get_cm().send_preflight_probes(route_params, liquidity_limit_multiplier)
152 .map_err(ProbingError::Sending)
155 /// Sends payment probes over all paths of a route that would be used to pay the given zero-value
156 /// invoice using the given amount.
158 /// See [`ChannelManager::send_preflight_probes`] for more information.
159 pub fn preflight_probe_zero_value_invoice<C: AChannelManager>(
160 invoice: &Bolt11Invoice, amount_msat: u64, channelmanager: &C,
161 liquidity_limit_multiplier: Option<u64>,
162 ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbingError>
164 if invoice.amount_milli_satoshis().is_some() {
165 return Err(ProbingError::Invoice("amount unexpected"));
168 let mut payment_params = PaymentParameters::from_node_id(
169 invoice.recover_payee_pub_key(),
170 invoice.min_final_cltv_expiry_delta() as u32,
172 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
173 .with_route_hints(invoice.route_hints())
176 if let Some(features) = invoice.features() {
177 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
179 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
181 channelmanager.get_cm().send_preflight_probes(route_params, liquidity_limit_multiplier)
182 .map_err(ProbingError::Sending)
185 fn expiry_time_from_unix_epoch(invoice: &Bolt11Invoice) -> Duration {
186 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
189 /// An error that may occur when making a payment.
190 #[derive(Clone, Debug, PartialEq, Eq)]
191 pub enum PaymentError {
192 /// An error resulting from the provided [`Bolt11Invoice`] or payment hash.
193 Invoice(&'static str),
194 /// An error occurring when sending a payment.
195 Sending(RetryableSendFailure),
198 /// An error that may occur when sending a payment probe.
199 #[derive(Clone, Debug, PartialEq, Eq)]
200 pub enum ProbingError {
201 /// An error resulting from the provided [`Bolt11Invoice`].
202 Invoice(&'static str),
203 /// An error occurring when sending a payment probe.
204 Sending(ProbeSendFailure),
207 /// A trait defining behavior of a [`Bolt11Invoice`] payer.
209 /// Useful for unit testing internal methods.
211 /// Sends a payment over the Lightning Network using the given [`Route`].
213 /// [`Route`]: lightning::routing::router::Route
215 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
216 payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry
217 ) -> Result<(), PaymentError>;
220 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>
222 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
223 T::Target: BroadcasterInterface,
224 ES::Target: EntropySource,
225 NS::Target: NodeSigner,
226 SP::Target: SignerProvider,
227 F::Target: FeeEstimator,
232 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
233 payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry
234 ) -> Result<(), PaymentError> {
235 self.send_payment(payment_hash, recipient_onion, payment_id, route_params, retry_strategy)
236 .map_err(PaymentError::Sending)
243 use crate::{InvoiceBuilder, Currency};
244 use bitcoin_hashes::sha256::Hash as Sha256;
245 use lightning::events::Event;
246 use lightning::ln::msgs::ChannelMessageHandler;
247 use lightning::ln::{PaymentPreimage, PaymentSecret};
248 use lightning::ln::functional_test_utils::*;
249 use secp256k1::{SecretKey, Secp256k1};
250 use std::collections::VecDeque;
251 use std::time::{SystemTime, Duration};
254 expectations: core::cell::RefCell<VecDeque<Amount>>,
260 expectations: core::cell::RefCell::new(VecDeque::new()),
264 fn expect_send(self, value_msat: Amount) -> Self {
265 self.expectations.borrow_mut().push_back(value_msat);
269 fn check_value_msats(&self, actual_value_msats: Amount) {
270 let expected_value_msats = self.expectations.borrow_mut().pop_front();
271 if let Some(expected_value_msats) = expected_value_msats {
272 assert_eq!(actual_value_msats, expected_value_msats);
274 panic!("Unexpected amount: {:?}", actual_value_msats);
279 #[derive(Clone, Debug, PartialEq, Eq)]
280 struct Amount(u64); // msat
282 impl Payer for TestPayer {
284 &self, _payment_hash: PaymentHash, _recipient_onion: RecipientOnionFields,
285 _payment_id: PaymentId, route_params: RouteParameters, _retry_strategy: Retry
286 ) -> Result<(), PaymentError> {
287 self.check_value_msats(Amount(route_params.final_value_msat));
292 impl Drop for TestPayer {
294 if std::thread::panicking() {
298 if !self.expectations.borrow().is_empty() {
299 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
304 fn duration_since_epoch() -> Duration {
305 #[cfg(feature = "std")]
306 let duration_since_epoch =
307 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
308 #[cfg(not(feature = "std"))]
309 let duration_since_epoch = Duration::from_secs(1234567);
313 fn invoice(payment_preimage: PaymentPreimage) -> Bolt11Invoice {
314 let payment_hash = Sha256::hash(&payment_preimage.0);
315 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
317 InvoiceBuilder::new(Currency::Bitcoin)
318 .description("test".into())
319 .payment_hash(payment_hash)
320 .payment_secret(PaymentSecret([0; 32]))
321 .duration_since_epoch(duration_since_epoch())
322 .min_final_cltv_expiry_delta(144)
323 .amount_milli_satoshis(128)
324 .build_signed(|hash| {
325 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
330 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Bolt11Invoice {
331 let payment_hash = Sha256::hash(&payment_preimage.0);
332 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
334 InvoiceBuilder::new(Currency::Bitcoin)
335 .description("test".into())
336 .payment_hash(payment_hash)
337 .payment_secret(PaymentSecret([0; 32]))
338 .duration_since_epoch(duration_since_epoch())
339 .min_final_cltv_expiry_delta(144)
340 .build_signed(|hash| {
341 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
348 let payment_id = PaymentId([42; 32]);
349 let payment_preimage = PaymentPreimage([1; 32]);
350 let invoice = invoice(payment_preimage);
351 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
353 let payer = TestPayer::new().expect_send(Amount(final_value_msat));
354 pay_invoice_using_amount(&invoice, final_value_msat, payment_id, Retry::Attempts(0), &payer).unwrap();
358 fn pays_zero_value_invoice() {
359 let payment_id = PaymentId([42; 32]);
360 let payment_preimage = PaymentPreimage([1; 32]);
361 let invoice = zero_value_invoice(payment_preimage);
362 let amt_msat = 10_000;
364 let payer = TestPayer::new().expect_send(Amount(amt_msat));
365 pay_invoice_using_amount(&invoice, amt_msat, payment_id, Retry::Attempts(0), &payer).unwrap();
369 fn fails_paying_zero_value_invoice_with_amount() {
370 let chanmon_cfgs = create_chanmon_cfgs(1);
371 let node_cfgs = create_node_cfgs(1, &chanmon_cfgs);
372 let node_chanmgrs = create_node_chanmgrs(1, &node_cfgs, &[None]);
373 let nodes = create_network(1, &node_cfgs, &node_chanmgrs);
375 let payment_preimage = PaymentPreimage([1; 32]);
376 let invoice = invoice(payment_preimage);
377 let amt_msat = 10_000;
379 match pay_zero_value_invoice(&invoice, amt_msat, Retry::Attempts(0), nodes[0].node) {
380 Err(PaymentError::Invoice("amount unexpected")) => {},
386 #[cfg(feature = "std")]
387 fn payment_metadata_end_to_end() {
388 // Test that a payment metadata read from an invoice passed to `pay_invoice` makes it all
389 // the way out through the `PaymentClaimable` event.
390 let chanmon_cfgs = create_chanmon_cfgs(2);
391 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
392 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
393 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
394 create_announced_chan_between_nodes(&nodes, 0, 1);
396 let payment_metadata = vec![42, 43, 44, 45, 46, 47, 48, 49, 42];
398 let (payment_hash, payment_secret) =
399 nodes[1].node.create_inbound_payment(None, 7200, None).unwrap();
401 let invoice = InvoiceBuilder::new(Currency::Bitcoin)
402 .description("test".into())
403 .payment_hash(Sha256::from_slice(&payment_hash.0).unwrap())
404 .payment_secret(payment_secret)
406 .min_final_cltv_expiry_delta(144)
407 .amount_milli_satoshis(50_000)
408 .payment_metadata(payment_metadata.clone())
409 .build_signed(|hash| {
410 Secp256k1::new().sign_ecdsa_recoverable(hash,
411 &nodes[1].keys_manager.backing.get_node_secret_key())
415 pay_invoice(&invoice, Retry::Attempts(0), nodes[0].node).unwrap();
416 check_added_monitors(&nodes[0], 1);
417 let send_event = SendEvent::from_node(&nodes[0]);
418 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
419 commitment_signed_dance!(nodes[1], nodes[0], &send_event.commitment_msg, false);
421 expect_pending_htlcs_forwardable!(nodes[1]);
423 let mut events = nodes[1].node.get_and_clear_pending_events();
424 assert_eq!(events.len(), 1);
425 match events.pop().unwrap() {
426 Event::PaymentClaimable { onion_fields, .. } => {
427 assert_eq!(Some(payment_metadata), onion_fields.unwrap().payment_metadata);
429 _ => panic!("Unexpected event")