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: AChannelManager>(
38 invoice: &Bolt11Invoice, retry_strategy: Retry, channelmanager: &C
39 ) -> Result<PaymentId, PaymentError>
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: AChannelManager>(
57 invoice: &Bolt11Invoice, payment_id: PaymentId, retry_strategy: Retry, channelmanager: &C
58 ) -> Result<(), PaymentError>
60 let amt_msat = invoice.amount_milli_satoshis().ok_or(PaymentError::Invoice("amount missing"))?;
61 pay_invoice_using_amount(invoice, amt_msat, payment_id, retry_strategy, channelmanager.get_cm())
64 /// Pays the given zero-value [`Bolt11Invoice`] using the given amount, retrying if needed based on
67 /// [`Bolt11Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
68 /// as the payment is still pending. If the payment succeeds, you must ensure that a second payment
69 /// with the same [`PaymentHash`] is never sent.
71 /// If you wish to use a different payment idempotency token, see
72 /// [`pay_zero_value_invoice_with_id`].
73 pub fn pay_zero_value_invoice<C: AChannelManager>(
74 invoice: &Bolt11Invoice, amount_msats: u64, retry_strategy: Retry, channelmanager: &C
75 ) -> Result<PaymentId, PaymentError>
77 let payment_id = PaymentId(invoice.payment_hash().into_inner());
78 pay_zero_value_invoice_with_id(invoice, amount_msats, payment_id, retry_strategy,
83 /// Pays the given zero-value [`Bolt11Invoice`] using the given amount and custom idempotency key,
84 /// retrying if needed based on [`Retry`].
86 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
87 /// payment completes or fails, no idempotency guarantees are made.
89 /// You should ensure that the [`Bolt11Invoice::payment_hash`] is unique and the same
90 /// [`PaymentHash`] has never been paid before.
92 /// See [`pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the
93 /// idempotency token.
94 pub fn pay_zero_value_invoice_with_id<C: AChannelManager>(
95 invoice: &Bolt11Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
97 ) -> Result<(), PaymentError>
99 if invoice.amount_milli_satoshis().is_some() {
100 Err(PaymentError::Invoice("amount unexpected"))
102 pay_invoice_using_amount(invoice, amount_msats, payment_id, retry_strategy,
103 channelmanager.get_cm())
107 fn pay_invoice_using_amount<P: Deref>(
108 invoice: &Bolt11Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
110 ) -> Result<(), PaymentError> where P::Target: Payer {
111 let payment_hash = PaymentHash((*invoice.payment_hash()).into_inner());
112 let mut recipient_onion = RecipientOnionFields::secret_only(*invoice.payment_secret());
113 recipient_onion.payment_metadata = invoice.payment_metadata().map(|v| v.clone());
114 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(),
115 invoice.min_final_cltv_expiry_delta() as u32)
116 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
117 .with_route_hints(invoice.route_hints()).unwrap();
118 if let Some(features) = invoice.features() {
119 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
121 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msats);
123 payer.send_payment(payment_hash, recipient_onion, payment_id, route_params, retry_strategy)
126 /// Sends payment probes over all paths of a route that would be used to pay the given invoice.
128 /// See [`ChannelManager::send_preflight_probes`] for more information.
129 pub fn preflight_probe_invoice<C: AChannelManager>(
130 invoice: &Bolt11Invoice, channelmanager: &C, liquidity_limit_multiplier: Option<u64>,
131 ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbingError>
133 let amount_msat = if let Some(invoice_amount_msat) = invoice.amount_milli_satoshis() {
136 return Err(ProbingError::Invoice("Failed to send probe as no amount was given in the invoice."));
139 let mut payment_params = PaymentParameters::from_node_id(
140 invoice.recover_payee_pub_key(),
141 invoice.min_final_cltv_expiry_delta() as u32,
143 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
144 .with_route_hints(invoice.route_hints())
147 if let Some(features) = invoice.features() {
148 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
150 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
152 channelmanager.get_cm().send_preflight_probes(route_params, liquidity_limit_multiplier)
153 .map_err(ProbingError::Sending)
156 /// Sends payment probes over all paths of a route that would be used to pay the given zero-value
157 /// invoice using the given amount.
159 /// See [`ChannelManager::send_preflight_probes`] for more information.
160 pub fn preflight_probe_zero_value_invoice<C: AChannelManager>(
161 invoice: &Bolt11Invoice, amount_msat: u64, channelmanager: &C,
162 liquidity_limit_multiplier: Option<u64>,
163 ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbingError>
165 if invoice.amount_milli_satoshis().is_some() {
166 return Err(ProbingError::Invoice("amount unexpected"));
169 let mut payment_params = PaymentParameters::from_node_id(
170 invoice.recover_payee_pub_key(),
171 invoice.min_final_cltv_expiry_delta() as u32,
173 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
174 .with_route_hints(invoice.route_hints())
177 if let Some(features) = invoice.features() {
178 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
180 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
182 channelmanager.get_cm().send_preflight_probes(route_params, liquidity_limit_multiplier)
183 .map_err(ProbingError::Sending)
186 fn expiry_time_from_unix_epoch(invoice: &Bolt11Invoice) -> Duration {
187 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
190 /// An error that may occur when making a payment.
191 #[derive(Clone, Debug, PartialEq, Eq)]
192 pub enum PaymentError {
193 /// An error resulting from the provided [`Bolt11Invoice`] or payment hash.
194 Invoice(&'static str),
195 /// An error occurring when sending a payment.
196 Sending(RetryableSendFailure),
199 /// An error that may occur when sending a payment probe.
200 #[derive(Clone, Debug, PartialEq, Eq)]
201 pub enum ProbingError {
202 /// An error resulting from the provided [`Bolt11Invoice`].
203 Invoice(&'static str),
204 /// An error occurring when sending a payment probe.
205 Sending(ProbeSendFailure),
208 /// A trait defining behavior of a [`Bolt11Invoice`] payer.
210 /// Useful for unit testing internal methods.
212 /// Sends a payment over the Lightning Network using the given [`Route`].
214 /// [`Route`]: lightning::routing::router::Route
216 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
217 payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry
218 ) -> Result<(), PaymentError>;
221 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 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
224 T::Target: BroadcasterInterface,
225 ES::Target: EntropySource,
226 NS::Target: NodeSigner,
227 SP::Target: SignerProvider,
228 F::Target: FeeEstimator,
233 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
234 payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry
235 ) -> Result<(), PaymentError> {
236 self.send_payment(payment_hash, recipient_onion, payment_id, route_params, retry_strategy)
237 .map_err(PaymentError::Sending)
244 use crate::{InvoiceBuilder, Currency};
245 use bitcoin_hashes::sha256::Hash as Sha256;
246 use lightning::events::Event;
247 use lightning::ln::msgs::ChannelMessageHandler;
248 use lightning::ln::{PaymentPreimage, PaymentSecret};
249 use lightning::ln::functional_test_utils::*;
250 use secp256k1::{SecretKey, Secp256k1};
251 use std::collections::VecDeque;
252 use std::time::{SystemTime, Duration};
255 expectations: core::cell::RefCell<VecDeque<Amount>>,
261 expectations: core::cell::RefCell::new(VecDeque::new()),
265 fn expect_send(self, value_msat: Amount) -> Self {
266 self.expectations.borrow_mut().push_back(value_msat);
270 fn check_value_msats(&self, actual_value_msats: Amount) {
271 let expected_value_msats = self.expectations.borrow_mut().pop_front();
272 if let Some(expected_value_msats) = expected_value_msats {
273 assert_eq!(actual_value_msats, expected_value_msats);
275 panic!("Unexpected amount: {:?}", actual_value_msats);
280 #[derive(Clone, Debug, PartialEq, Eq)]
281 struct Amount(u64); // msat
283 impl Payer for TestPayer {
285 &self, _payment_hash: PaymentHash, _recipient_onion: RecipientOnionFields,
286 _payment_id: PaymentId, route_params: RouteParameters, _retry_strategy: Retry
287 ) -> Result<(), PaymentError> {
288 self.check_value_msats(Amount(route_params.final_value_msat));
293 impl Drop for TestPayer {
295 if std::thread::panicking() {
299 if !self.expectations.borrow().is_empty() {
300 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
305 fn duration_since_epoch() -> Duration {
306 #[cfg(feature = "std")]
307 let duration_since_epoch =
308 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
309 #[cfg(not(feature = "std"))]
310 let duration_since_epoch = Duration::from_secs(1234567);
314 fn invoice(payment_preimage: PaymentPreimage) -> Bolt11Invoice {
315 let payment_hash = Sha256::hash(&payment_preimage.0);
316 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
318 InvoiceBuilder::new(Currency::Bitcoin)
319 .description("test".into())
320 .payment_hash(payment_hash)
321 .payment_secret(PaymentSecret([0; 32]))
322 .duration_since_epoch(duration_since_epoch())
323 .min_final_cltv_expiry_delta(144)
324 .amount_milli_satoshis(128)
325 .build_signed(|hash| {
326 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
331 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Bolt11Invoice {
332 let payment_hash = Sha256::hash(&payment_preimage.0);
333 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
335 InvoiceBuilder::new(Currency::Bitcoin)
336 .description("test".into())
337 .payment_hash(payment_hash)
338 .payment_secret(PaymentSecret([0; 32]))
339 .duration_since_epoch(duration_since_epoch())
340 .min_final_cltv_expiry_delta(144)
341 .build_signed(|hash| {
342 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
349 let payment_id = PaymentId([42; 32]);
350 let payment_preimage = PaymentPreimage([1; 32]);
351 let invoice = invoice(payment_preimage);
352 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
354 let payer = TestPayer::new().expect_send(Amount(final_value_msat));
355 pay_invoice_using_amount(&invoice, final_value_msat, payment_id, Retry::Attempts(0), &payer).unwrap();
359 fn pays_zero_value_invoice() {
360 let payment_id = PaymentId([42; 32]);
361 let payment_preimage = PaymentPreimage([1; 32]);
362 let invoice = zero_value_invoice(payment_preimage);
363 let amt_msat = 10_000;
365 let payer = TestPayer::new().expect_send(Amount(amt_msat));
366 pay_invoice_using_amount(&invoice, amt_msat, payment_id, Retry::Attempts(0), &payer).unwrap();
370 fn fails_paying_zero_value_invoice_with_amount() {
371 let chanmon_cfgs = create_chanmon_cfgs(1);
372 let node_cfgs = create_node_cfgs(1, &chanmon_cfgs);
373 let node_chanmgrs = create_node_chanmgrs(1, &node_cfgs, &[None]);
374 let nodes = create_network(1, &node_cfgs, &node_chanmgrs);
376 let payment_preimage = PaymentPreimage([1; 32]);
377 let invoice = invoice(payment_preimage);
378 let amt_msat = 10_000;
380 match pay_zero_value_invoice(&invoice, amt_msat, Retry::Attempts(0), nodes[0].node) {
381 Err(PaymentError::Invoice("amount unexpected")) => {},
387 #[cfg(feature = "std")]
388 fn payment_metadata_end_to_end() {
389 // Test that a payment metadata read from an invoice passed to `pay_invoice` makes it all
390 // the way out through the `PaymentClaimable` event.
391 let chanmon_cfgs = create_chanmon_cfgs(2);
392 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
393 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
394 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
395 create_announced_chan_between_nodes(&nodes, 0, 1);
397 let payment_metadata = vec![42, 43, 44, 45, 46, 47, 48, 49, 42];
399 let (payment_hash, payment_secret) =
400 nodes[1].node.create_inbound_payment(None, 7200, None).unwrap();
402 let invoice = InvoiceBuilder::new(Currency::Bitcoin)
403 .description("test".into())
404 .payment_hash(Sha256::from_slice(&payment_hash.0).unwrap())
405 .payment_secret(payment_secret)
407 .min_final_cltv_expiry_delta(144)
408 .amount_milli_satoshis(50_000)
409 .payment_metadata(payment_metadata.clone())
410 .build_signed(|hash| {
411 Secp256k1::new().sign_ecdsa_recoverable(hash,
412 &nodes[1].keys_manager.backing.get_node_secret_key())
416 pay_invoice(&invoice, Retry::Attempts(0), nodes[0].node).unwrap();
417 check_added_monitors(&nodes[0], 1);
418 let send_event = SendEvent::from_node(&nodes[0]);
419 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
420 commitment_signed_dance!(nodes[1], nodes[0], &send_event.commitment_msg, false);
422 expect_pending_htlcs_forwardable!(nodes[1]);
424 let mut events = nodes[1].node.get_and_clear_pending_events();
425 assert_eq!(events.len(), 1);
426 match events.pop().unwrap() {
427 Event::PaymentClaimable { onion_fields, .. } => {
428 assert_eq!(Some(payment_metadata), onion_fields.unwrap().payment_metadata);
430 _ => panic!("Unexpected event")