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, Vec};
14 use bitcoin_hashes::Hash;
17 use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
18 use lightning::sign::{NodeSigner, SignerProvider, EntropySource};
19 use lightning::ln::PaymentHash;
20 use lightning::ln::channelmanager::{AChannelManager, ChannelManager, PaymentId, Retry, RetryableSendFailure, RecipientOnionFields, ProbeSendFailure};
21 use lightning::routing::router::{PaymentParameters, RouteParameters, Router};
22 use lightning::util::logger::Logger;
26 use core::time::Duration;
28 /// Pays the given [`Bolt11Invoice`], retrying if needed based on [`Retry`].
30 /// [`Bolt11Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
31 /// as the payment is still pending. If the payment succeeds, you must ensure that a second payment
32 /// with the same [`PaymentHash`] is never sent.
34 /// If you wish to use a different payment idempotency token, see [`pay_invoice_with_id`].
35 pub fn pay_invoice<C: Deref>(
36 invoice: &Bolt11Invoice, retry_strategy: Retry, channelmanager: C
37 ) -> Result<PaymentId, PaymentError>
38 where C::Target: AChannelManager,
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: Deref>(
56 invoice: &Bolt11Invoice, payment_id: PaymentId, retry_strategy: Retry, channelmanager: C
57 ) -> Result<(), PaymentError>
58 where C::Target: AChannelManager,
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: Deref>(
74 invoice: &Bolt11Invoice, amount_msats: u64, retry_strategy: Retry, channelmanager: C
75 ) -> Result<PaymentId, PaymentError>
76 where C::Target: AChannelManager,
78 let payment_id = PaymentId(invoice.payment_hash().into_inner());
79 pay_zero_value_invoice_with_id(invoice, amount_msats, payment_id, retry_strategy,
84 /// Pays the given zero-value [`Bolt11Invoice`] using the given amount and custom idempotency key,
85 /// retrying if needed based on [`Retry`].
87 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
88 /// payment completes or fails, no idempotency guarantees are made.
90 /// You should ensure that the [`Bolt11Invoice::payment_hash`] is unique and the same
91 /// [`PaymentHash`] has never been paid before.
93 /// See [`pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the
94 /// idempotency token.
95 pub fn pay_zero_value_invoice_with_id<C: Deref>(
96 invoice: &Bolt11Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
98 ) -> Result<(), PaymentError>
99 where C::Target: AChannelManager,
101 if invoice.amount_milli_satoshis().is_some() {
102 Err(PaymentError::Invoice("amount unexpected"))
104 pay_invoice_using_amount(invoice, amount_msats, payment_id, retry_strategy,
105 channelmanager.get_cm())
109 fn pay_invoice_using_amount<P: Deref>(
110 invoice: &Bolt11Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
112 ) -> Result<(), PaymentError> where P::Target: Payer {
113 let payment_hash = PaymentHash((*invoice.payment_hash()).into_inner());
114 let mut recipient_onion = RecipientOnionFields::secret_only(*invoice.payment_secret());
115 recipient_onion.payment_metadata = invoice.payment_metadata().map(|v| v.clone());
116 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(),
117 invoice.min_final_cltv_expiry_delta() as u32)
118 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
119 .with_route_hints(invoice.route_hints()).unwrap();
120 if let Some(features) = invoice.features() {
121 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
123 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msats);
125 payer.send_payment(payment_hash, recipient_onion, payment_id, route_params, retry_strategy)
128 /// Sends payment probes over all paths of a route that would be used to pay the given invoice.
130 /// See [`ChannelManager::send_preflight_probes`] for more information.
131 pub fn preflight_probe_invoice<C: Deref>(
132 invoice: &Bolt11Invoice, channelmanager: C, liquidity_limit_multiplier: Option<u64>,
133 ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbingError>
134 where C::Target: AChannelManager,
136 let amount_msat = if let Some(invoice_amount_msat) = invoice.amount_milli_satoshis() {
139 return Err(ProbingError::Invoice("Failed to send probe as no amount was given in the invoice."));
142 let mut payment_params = PaymentParameters::from_node_id(
143 invoice.recover_payee_pub_key(),
144 invoice.min_final_cltv_expiry_delta() as u32,
146 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
147 .with_route_hints(invoice.route_hints())
150 if let Some(features) = invoice.features() {
151 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
153 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
155 channelmanager.get_cm().send_preflight_probes(route_params, liquidity_limit_multiplier)
156 .map_err(ProbingError::Sending)
159 /// Sends payment probes over all paths of a route that would be used to pay the given zero-value
160 /// invoice using the given amount.
162 /// See [`ChannelManager::send_preflight_probes`] for more information.
163 pub fn preflight_probe_zero_value_invoice<C: Deref>(
164 invoice: &Bolt11Invoice, amount_msat: u64, channelmanager: C,
165 liquidity_limit_multiplier: Option<u64>,
166 ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbingError>
167 where C::Target: AChannelManager,
169 if invoice.amount_milli_satoshis().is_some() {
170 return Err(ProbingError::Invoice("amount unexpected"));
173 let mut payment_params = PaymentParameters::from_node_id(
174 invoice.recover_payee_pub_key(),
175 invoice.min_final_cltv_expiry_delta() as u32,
177 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
178 .with_route_hints(invoice.route_hints())
181 if let Some(features) = invoice.features() {
182 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
184 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
186 channelmanager.get_cm().send_preflight_probes(route_params, liquidity_limit_multiplier)
187 .map_err(ProbingError::Sending)
190 fn expiry_time_from_unix_epoch(invoice: &Bolt11Invoice) -> Duration {
191 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
194 /// An error that may occur when making a payment.
195 #[derive(Clone, Debug, PartialEq, Eq)]
196 pub enum PaymentError {
197 /// An error resulting from the provided [`Bolt11Invoice`] or payment hash.
198 Invoice(&'static str),
199 /// An error occurring when sending a payment.
200 Sending(RetryableSendFailure),
203 /// An error that may occur when sending a payment probe.
204 #[derive(Clone, Debug, PartialEq, Eq)]
205 pub enum ProbingError {
206 /// An error resulting from the provided [`Bolt11Invoice`].
207 Invoice(&'static str),
208 /// An error occurring when sending a payment probe.
209 Sending(ProbeSendFailure),
212 /// A trait defining behavior of a [`Bolt11Invoice`] payer.
214 /// Useful for unit testing internal methods.
216 /// Sends a payment over the Lightning Network using the given [`Route`].
218 /// [`Route`]: lightning::routing::router::Route
220 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
221 payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry
222 ) -> Result<(), PaymentError>;
225 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>
227 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
228 T::Target: BroadcasterInterface,
229 ES::Target: EntropySource,
230 NS::Target: NodeSigner,
231 SP::Target: SignerProvider,
232 F::Target: FeeEstimator,
237 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
238 payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry
239 ) -> Result<(), PaymentError> {
240 self.send_payment(payment_hash, recipient_onion, payment_id, route_params, retry_strategy)
241 .map_err(PaymentError::Sending)
248 use crate::{InvoiceBuilder, Currency};
249 use bitcoin_hashes::sha256::Hash as Sha256;
250 use lightning::events::Event;
251 use lightning::ln::msgs::ChannelMessageHandler;
252 use lightning::ln::{PaymentPreimage, PaymentSecret};
253 use lightning::ln::functional_test_utils::*;
254 use secp256k1::{SecretKey, Secp256k1};
255 use std::collections::VecDeque;
256 use std::time::{SystemTime, Duration};
259 expectations: core::cell::RefCell<VecDeque<Amount>>,
265 expectations: core::cell::RefCell::new(VecDeque::new()),
269 fn expect_send(self, value_msat: Amount) -> Self {
270 self.expectations.borrow_mut().push_back(value_msat);
274 fn check_value_msats(&self, actual_value_msats: Amount) {
275 let expected_value_msats = self.expectations.borrow_mut().pop_front();
276 if let Some(expected_value_msats) = expected_value_msats {
277 assert_eq!(actual_value_msats, expected_value_msats);
279 panic!("Unexpected amount: {:?}", actual_value_msats);
284 #[derive(Clone, Debug, PartialEq, Eq)]
285 struct Amount(u64); // msat
287 impl Payer for TestPayer {
289 &self, _payment_hash: PaymentHash, _recipient_onion: RecipientOnionFields,
290 _payment_id: PaymentId, route_params: RouteParameters, _retry_strategy: Retry
291 ) -> Result<(), PaymentError> {
292 self.check_value_msats(Amount(route_params.final_value_msat));
297 impl Drop for TestPayer {
299 if std::thread::panicking() {
303 if !self.expectations.borrow().is_empty() {
304 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
309 fn duration_since_epoch() -> Duration {
310 #[cfg(feature = "std")]
311 let duration_since_epoch =
312 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
313 #[cfg(not(feature = "std"))]
314 let duration_since_epoch = Duration::from_secs(1234567);
318 fn invoice(payment_preimage: PaymentPreimage) -> Bolt11Invoice {
319 let payment_hash = Sha256::hash(&payment_preimage.0);
320 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
322 InvoiceBuilder::new(Currency::Bitcoin)
323 .description("test".into())
324 .payment_hash(payment_hash)
325 .payment_secret(PaymentSecret([0; 32]))
326 .duration_since_epoch(duration_since_epoch())
327 .min_final_cltv_expiry_delta(144)
328 .amount_milli_satoshis(128)
329 .build_signed(|hash| {
330 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
335 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Bolt11Invoice {
336 let payment_hash = Sha256::hash(&payment_preimage.0);
337 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
339 InvoiceBuilder::new(Currency::Bitcoin)
340 .description("test".into())
341 .payment_hash(payment_hash)
342 .payment_secret(PaymentSecret([0; 32]))
343 .duration_since_epoch(duration_since_epoch())
344 .min_final_cltv_expiry_delta(144)
345 .build_signed(|hash| {
346 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
353 let payment_id = PaymentId([42; 32]);
354 let payment_preimage = PaymentPreimage([1; 32]);
355 let invoice = invoice(payment_preimage);
356 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
358 let payer = TestPayer::new().expect_send(Amount(final_value_msat));
359 pay_invoice_using_amount(&invoice, final_value_msat, payment_id, Retry::Attempts(0), &payer).unwrap();
363 fn pays_zero_value_invoice() {
364 let payment_id = PaymentId([42; 32]);
365 let payment_preimage = PaymentPreimage([1; 32]);
366 let invoice = zero_value_invoice(payment_preimage);
367 let amt_msat = 10_000;
369 let payer = TestPayer::new().expect_send(Amount(amt_msat));
370 pay_invoice_using_amount(&invoice, amt_msat, payment_id, Retry::Attempts(0), &payer).unwrap();
374 fn fails_paying_zero_value_invoice_with_amount() {
375 let chanmon_cfgs = create_chanmon_cfgs(1);
376 let node_cfgs = create_node_cfgs(1, &chanmon_cfgs);
377 let node_chanmgrs = create_node_chanmgrs(1, &node_cfgs, &[None]);
378 let nodes = create_network(1, &node_cfgs, &node_chanmgrs);
380 let payment_preimage = PaymentPreimage([1; 32]);
381 let invoice = invoice(payment_preimage);
382 let amt_msat = 10_000;
384 match pay_zero_value_invoice(&invoice, amt_msat, Retry::Attempts(0), nodes[0].node) {
385 Err(PaymentError::Invoice("amount unexpected")) => {},
391 #[cfg(feature = "std")]
392 fn payment_metadata_end_to_end() {
393 // Test that a payment metadata read from an invoice passed to `pay_invoice` makes it all
394 // the way out through the `PaymentClaimable` event.
395 let chanmon_cfgs = create_chanmon_cfgs(2);
396 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
397 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
398 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
399 create_announced_chan_between_nodes(&nodes, 0, 1);
401 let payment_metadata = vec![42, 43, 44, 45, 46, 47, 48, 49, 42];
403 let (payment_hash, payment_secret) =
404 nodes[1].node.create_inbound_payment(None, 7200, None).unwrap();
406 let invoice = InvoiceBuilder::new(Currency::Bitcoin)
407 .description("test".into())
408 .payment_hash(Sha256::from_slice(&payment_hash.0).unwrap())
409 .payment_secret(payment_secret)
411 .min_final_cltv_expiry_delta(144)
412 .amount_milli_satoshis(50_000)
413 .payment_metadata(payment_metadata.clone())
414 .build_signed(|hash| {
415 Secp256k1::new().sign_ecdsa_recoverable(hash,
416 &nodes[1].keys_manager.backing.get_node_secret_key())
420 pay_invoice(&invoice, Retry::Attempts(0), nodes[0].node).unwrap();
421 check_added_monitors(&nodes[0], 1);
422 let send_event = SendEvent::from_node(&nodes[0]);
423 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
424 commitment_signed_dance!(nodes[1], nodes[0], &send_event.commitment_msg, false);
426 expect_pending_htlcs_forwardable!(nodes[1]);
428 let mut events = nodes[1].node.get_and_clear_pending_events();
429 assert_eq!(events.len(), 1);
430 match events.pop().unwrap() {
431 Event::PaymentClaimable { onion_fields, .. } => {
432 assert_eq!(Some(payment_metadata), onion_fields.unwrap().payment_metadata);
434 _ => panic!("Unexpected event")