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: Deref>(
37 invoice: &Bolt11Invoice, retry_strategy: Retry, channelmanager: C
38 ) -> Result<PaymentId, PaymentError>
39 where C::Target: AChannelManager,
41 let payment_id = PaymentId(invoice.payment_hash().into_inner());
42 pay_invoice_with_id(invoice, payment_id, retry_strategy, channelmanager.get_cm())
46 /// Pays the given [`Bolt11Invoice`] with a custom idempotency key, retrying if needed based on
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.
52 /// You should ensure that the [`Bolt11Invoice::payment_hash`] is unique and the same
53 /// [`PaymentHash`] has never been paid before.
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,
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())
65 /// Pays the given zero-value [`Bolt11Invoice`] using the given amount, retrying if needed based on
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.
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,
79 let payment_id = PaymentId(invoice.payment_hash().into_inner());
80 pay_zero_value_invoice_with_id(invoice, amount_msats, payment_id, retry_strategy,
85 /// Pays the given zero-value [`Bolt11Invoice`] using the given amount and custom idempotency key,
86 /// retrying if needed based on [`Retry`].
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.
91 /// You should ensure that the [`Bolt11Invoice::payment_hash`] is unique and the same
92 /// [`PaymentHash`] has never been paid before.
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,
99 ) -> Result<(), PaymentError>
100 where C::Target: AChannelManager,
102 if invoice.amount_milli_satoshis().is_some() {
103 Err(PaymentError::Invoice("amount unexpected"))
105 pay_invoice_using_amount(invoice, amount_msats, payment_id, retry_strategy,
106 channelmanager.get_cm())
110 fn pay_invoice_using_amount<P: Deref>(
111 invoice: &Bolt11Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
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();
124 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msats);
126 payer.send_payment(payment_hash, recipient_onion, payment_id, route_params, retry_strategy)
129 /// Sends payment probes over all paths of a route that would be used to pay the given invoice.
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,
137 let amount_msat = if let Some(invoice_amount_msat) = invoice.amount_milli_satoshis() {
140 return Err(ProbingError::Invoice("Failed to send probe as no amount was given in the invoice."));
143 let mut payment_params = PaymentParameters::from_node_id(
144 invoice.recover_payee_pub_key(),
145 invoice.min_final_cltv_expiry_delta() as u32,
147 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
148 .with_route_hints(invoice.route_hints())
151 if let Some(features) = invoice.features() {
152 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
154 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
156 channelmanager.get_cm().send_preflight_probes(route_params, liquidity_limit_multiplier)
157 .map_err(ProbingError::Sending)
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.
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,
170 if invoice.amount_milli_satoshis().is_some() {
171 return Err(ProbingError::Invoice("amount unexpected"));
174 let mut payment_params = PaymentParameters::from_node_id(
175 invoice.recover_payee_pub_key(),
176 invoice.min_final_cltv_expiry_delta() as u32,
178 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
179 .with_route_hints(invoice.route_hints())
182 if let Some(features) = invoice.features() {
183 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
185 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
187 channelmanager.get_cm().send_preflight_probes(route_params, liquidity_limit_multiplier)
188 .map_err(ProbingError::Sending)
191 fn expiry_time_from_unix_epoch(invoice: &Bolt11Invoice) -> Duration {
192 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
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),
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),
213 /// A trait defining behavior of a [`Bolt11Invoice`] payer.
215 /// Useful for unit testing internal methods.
217 /// Sends a payment over the Lightning Network using the given [`Route`].
219 /// [`Route`]: lightning::routing::router::Route
221 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
222 payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry
223 ) -> Result<(), PaymentError>;
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>
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,
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)
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};
260 expectations: core::cell::RefCell<VecDeque<Amount>>,
266 expectations: core::cell::RefCell::new(VecDeque::new()),
270 fn expect_send(self, value_msat: Amount) -> Self {
271 self.expectations.borrow_mut().push_back(value_msat);
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);
280 panic!("Unexpected amount: {:?}", actual_value_msats);
285 #[derive(Clone, Debug, PartialEq, Eq)]
286 struct Amount(u64); // msat
288 impl Payer for TestPayer {
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));
298 impl Drop for TestPayer {
300 if std::thread::panicking() {
304 if !self.expectations.borrow().is_empty() {
305 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
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);
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();
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)
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();
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)
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();
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();
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;
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();
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);
381 let payment_preimage = PaymentPreimage([1; 32]);
382 let invoice = invoice(payment_preimage);
383 let amt_msat = 10_000;
385 match pay_zero_value_invoice(&invoice, amt_msat, Retry::Attempts(0), nodes[0].node) {
386 Err(PaymentError::Invoice("amount unexpected")) => {},
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);
402 let payment_metadata = vec![42, 43, 44, 45, 46, 47, 48, 49, 42];
404 let (payment_hash, payment_secret) =
405 nodes[1].node.create_inbound_payment(None, 7200, None).unwrap();
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)
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())
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);
427 expect_pending_htlcs_forwardable!(nodes[1]);
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);
435 _ => panic!("Unexpected event")