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: AChannelManager>(
36 invoice: &Bolt11Invoice, retry_strategy: Retry, channelmanager: &C
37 ) -> Result<PaymentId, PaymentError>
39 let payment_id = PaymentId(invoice.payment_hash().into_inner());
40 pay_invoice_with_id(invoice, payment_id, retry_strategy, channelmanager.get_cm())
44 /// Pays the given [`Bolt11Invoice`] with a custom idempotency key, retrying if needed based on
47 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
48 /// payment completes or fails, no idempotency guarantees are made.
50 /// You should ensure that the [`Bolt11Invoice::payment_hash`] is unique and the same
51 /// [`PaymentHash`] has never been paid before.
53 /// See [`pay_invoice`] for a variant which uses the [`PaymentHash`] for the idempotency token.
54 pub fn pay_invoice_with_id<C: AChannelManager>(
55 invoice: &Bolt11Invoice, payment_id: PaymentId, retry_strategy: Retry, channelmanager: &C
56 ) -> Result<(), PaymentError>
58 let amt_msat = invoice.amount_milli_satoshis().ok_or(PaymentError::Invoice("amount missing"))?;
59 pay_invoice_using_amount(invoice, amt_msat, payment_id, retry_strategy, channelmanager.get_cm())
62 /// Pays the given zero-value [`Bolt11Invoice`] using the given amount, retrying if needed based on
65 /// [`Bolt11Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
66 /// as the payment is still pending. If the payment succeeds, you must ensure that a second payment
67 /// with the same [`PaymentHash`] is never sent.
69 /// If you wish to use a different payment idempotency token, see
70 /// [`pay_zero_value_invoice_with_id`].
71 pub fn pay_zero_value_invoice<C: AChannelManager>(
72 invoice: &Bolt11Invoice, amount_msats: u64, retry_strategy: Retry, channelmanager: &C
73 ) -> Result<PaymentId, PaymentError>
75 let payment_id = PaymentId(invoice.payment_hash().into_inner());
76 pay_zero_value_invoice_with_id(invoice, amount_msats, payment_id, retry_strategy,
81 /// Pays the given zero-value [`Bolt11Invoice`] using the given amount and custom idempotency key,
82 /// retrying if needed based on [`Retry`].
84 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
85 /// payment completes or fails, no idempotency guarantees are made.
87 /// You should ensure that the [`Bolt11Invoice::payment_hash`] is unique and the same
88 /// [`PaymentHash`] has never been paid before.
90 /// See [`pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the
91 /// idempotency token.
92 pub fn pay_zero_value_invoice_with_id<C: AChannelManager>(
93 invoice: &Bolt11Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
95 ) -> Result<(), PaymentError>
97 if invoice.amount_milli_satoshis().is_some() {
98 Err(PaymentError::Invoice("amount unexpected"))
100 pay_invoice_using_amount(invoice, amount_msats, payment_id, retry_strategy,
101 channelmanager.get_cm())
105 fn pay_invoice_using_amount<P: Deref>(
106 invoice: &Bolt11Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
108 ) -> Result<(), PaymentError> where P::Target: Payer {
109 let payment_hash = PaymentHash((*invoice.payment_hash()).into_inner());
110 let mut recipient_onion = RecipientOnionFields::secret_only(*invoice.payment_secret());
111 recipient_onion.payment_metadata = invoice.payment_metadata().map(|v| v.clone());
112 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(),
113 invoice.min_final_cltv_expiry_delta() as u32)
114 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
115 .with_route_hints(invoice.route_hints()).unwrap();
116 if let Some(features) = invoice.features() {
117 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
119 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msats);
121 payer.send_payment(payment_hash, recipient_onion, payment_id, route_params, retry_strategy)
124 /// Sends payment probes over all paths of a route that would be used to pay the given invoice.
126 /// See [`ChannelManager::send_preflight_probes`] for more information.
127 pub fn preflight_probe_invoice<C: AChannelManager>(
128 invoice: &Bolt11Invoice, channelmanager: &C, liquidity_limit_multiplier: Option<u64>,
129 ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbingError>
131 let amount_msat = if let Some(invoice_amount_msat) = invoice.amount_milli_satoshis() {
134 return Err(ProbingError::Invoice("Failed to send probe as no amount was given in the invoice."));
137 let mut payment_params = PaymentParameters::from_node_id(
138 invoice.recover_payee_pub_key(),
139 invoice.min_final_cltv_expiry_delta() as u32,
141 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
142 .with_route_hints(invoice.route_hints())
145 if let Some(features) = invoice.features() {
146 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
148 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
150 channelmanager.get_cm().send_preflight_probes(route_params, liquidity_limit_multiplier)
151 .map_err(ProbingError::Sending)
154 /// Sends payment probes over all paths of a route that would be used to pay the given zero-value
155 /// invoice using the given amount.
157 /// See [`ChannelManager::send_preflight_probes`] for more information.
158 pub fn preflight_probe_zero_value_invoice<C: AChannelManager>(
159 invoice: &Bolt11Invoice, amount_msat: u64, channelmanager: &C,
160 liquidity_limit_multiplier: Option<u64>,
161 ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbingError>
163 if invoice.amount_milli_satoshis().is_some() {
164 return Err(ProbingError::Invoice("amount unexpected"));
167 let mut payment_params = PaymentParameters::from_node_id(
168 invoice.recover_payee_pub_key(),
169 invoice.min_final_cltv_expiry_delta() as u32,
171 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
172 .with_route_hints(invoice.route_hints())
175 if let Some(features) = invoice.features() {
176 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
178 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
180 channelmanager.get_cm().send_preflight_probes(route_params, liquidity_limit_multiplier)
181 .map_err(ProbingError::Sending)
184 fn expiry_time_from_unix_epoch(invoice: &Bolt11Invoice) -> Duration {
185 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
188 /// An error that may occur when making a payment.
189 #[derive(Clone, Debug, PartialEq, Eq)]
190 pub enum PaymentError {
191 /// An error resulting from the provided [`Bolt11Invoice`] or payment hash.
192 Invoice(&'static str),
193 /// An error occurring when sending a payment.
194 Sending(RetryableSendFailure),
197 /// An error that may occur when sending a payment probe.
198 #[derive(Clone, Debug, PartialEq, Eq)]
199 pub enum ProbingError {
200 /// An error resulting from the provided [`Bolt11Invoice`].
201 Invoice(&'static str),
202 /// An error occurring when sending a payment probe.
203 Sending(ProbeSendFailure),
206 /// A trait defining behavior of a [`Bolt11Invoice`] payer.
208 /// Useful for unit testing internal methods.
210 /// Sends a payment over the Lightning Network using the given [`Route`].
212 /// [`Route`]: lightning::routing::router::Route
214 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
215 payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry
216 ) -> Result<(), PaymentError>;
219 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>
221 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
222 T::Target: BroadcasterInterface,
223 ES::Target: EntropySource,
224 NS::Target: NodeSigner,
225 SP::Target: SignerProvider,
226 F::Target: FeeEstimator,
231 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
232 payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry
233 ) -> Result<(), PaymentError> {
234 self.send_payment(payment_hash, recipient_onion, payment_id, route_params, retry_strategy)
235 .map_err(PaymentError::Sending)
242 use crate::{InvoiceBuilder, Currency};
243 use bitcoin_hashes::sha256::Hash as Sha256;
244 use lightning::events::Event;
245 use lightning::ln::msgs::ChannelMessageHandler;
246 use lightning::ln::{PaymentPreimage, PaymentSecret};
247 use lightning::ln::functional_test_utils::*;
248 use secp256k1::{SecretKey, Secp256k1};
249 use std::collections::VecDeque;
250 use std::time::{SystemTime, Duration};
253 expectations: core::cell::RefCell<VecDeque<Amount>>,
259 expectations: core::cell::RefCell::new(VecDeque::new()),
263 fn expect_send(self, value_msat: Amount) -> Self {
264 self.expectations.borrow_mut().push_back(value_msat);
268 fn check_value_msats(&self, actual_value_msats: Amount) {
269 let expected_value_msats = self.expectations.borrow_mut().pop_front();
270 if let Some(expected_value_msats) = expected_value_msats {
271 assert_eq!(actual_value_msats, expected_value_msats);
273 panic!("Unexpected amount: {:?}", actual_value_msats);
278 #[derive(Clone, Debug, PartialEq, Eq)]
279 struct Amount(u64); // msat
281 impl Payer for TestPayer {
283 &self, _payment_hash: PaymentHash, _recipient_onion: RecipientOnionFields,
284 _payment_id: PaymentId, route_params: RouteParameters, _retry_strategy: Retry
285 ) -> Result<(), PaymentError> {
286 self.check_value_msats(Amount(route_params.final_value_msat));
291 impl Drop for TestPayer {
293 if std::thread::panicking() {
297 if !self.expectations.borrow().is_empty() {
298 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
303 fn duration_since_epoch() -> Duration {
304 #[cfg(feature = "std")]
305 let duration_since_epoch =
306 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
307 #[cfg(not(feature = "std"))]
308 let duration_since_epoch = Duration::from_secs(1234567);
312 fn invoice(payment_preimage: PaymentPreimage) -> Bolt11Invoice {
313 let payment_hash = Sha256::hash(&payment_preimage.0);
314 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
316 InvoiceBuilder::new(Currency::Bitcoin)
317 .description("test".into())
318 .payment_hash(payment_hash)
319 .payment_secret(PaymentSecret([0; 32]))
320 .duration_since_epoch(duration_since_epoch())
321 .min_final_cltv_expiry_delta(144)
322 .amount_milli_satoshis(128)
323 .build_signed(|hash| {
324 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
329 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Bolt11Invoice {
330 let payment_hash = Sha256::hash(&payment_preimage.0);
331 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
333 InvoiceBuilder::new(Currency::Bitcoin)
334 .description("test".into())
335 .payment_hash(payment_hash)
336 .payment_secret(PaymentSecret([0; 32]))
337 .duration_since_epoch(duration_since_epoch())
338 .min_final_cltv_expiry_delta(144)
339 .build_signed(|hash| {
340 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
347 let payment_id = PaymentId([42; 32]);
348 let payment_preimage = PaymentPreimage([1; 32]);
349 let invoice = invoice(payment_preimage);
350 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
352 let payer = TestPayer::new().expect_send(Amount(final_value_msat));
353 pay_invoice_using_amount(&invoice, final_value_msat, payment_id, Retry::Attempts(0), &payer).unwrap();
357 fn pays_zero_value_invoice() {
358 let payment_id = PaymentId([42; 32]);
359 let payment_preimage = PaymentPreimage([1; 32]);
360 let invoice = zero_value_invoice(payment_preimage);
361 let amt_msat = 10_000;
363 let payer = TestPayer::new().expect_send(Amount(amt_msat));
364 pay_invoice_using_amount(&invoice, amt_msat, payment_id, Retry::Attempts(0), &payer).unwrap();
368 fn fails_paying_zero_value_invoice_with_amount() {
369 let chanmon_cfgs = create_chanmon_cfgs(1);
370 let node_cfgs = create_node_cfgs(1, &chanmon_cfgs);
371 let node_chanmgrs = create_node_chanmgrs(1, &node_cfgs, &[None]);
372 let nodes = create_network(1, &node_cfgs, &node_chanmgrs);
374 let payment_preimage = PaymentPreimage([1; 32]);
375 let invoice = invoice(payment_preimage);
376 let amt_msat = 10_000;
378 match pay_zero_value_invoice(&invoice, amt_msat, Retry::Attempts(0), nodes[0].node) {
379 Err(PaymentError::Invoice("amount unexpected")) => {},
385 #[cfg(feature = "std")]
386 fn payment_metadata_end_to_end() {
387 // Test that a payment metadata read from an invoice passed to `pay_invoice` makes it all
388 // the way out through the `PaymentClaimable` event.
389 let chanmon_cfgs = create_chanmon_cfgs(2);
390 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
391 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
392 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
393 create_announced_chan_between_nodes(&nodes, 0, 1);
395 let payment_metadata = vec![42, 43, 44, 45, 46, 47, 48, 49, 42];
397 let (payment_hash, payment_secret) =
398 nodes[1].node.create_inbound_payment(None, 7200, None).unwrap();
400 let invoice = InvoiceBuilder::new(Currency::Bitcoin)
401 .description("test".into())
402 .payment_hash(Sha256::from_slice(&payment_hash.0).unwrap())
403 .payment_secret(payment_secret)
405 .min_final_cltv_expiry_delta(144)
406 .amount_milli_satoshis(50_000)
407 .payment_metadata(payment_metadata.clone())
408 .build_signed(|hash| {
409 Secp256k1::new().sign_ecdsa_recoverable(hash,
410 &nodes[1].keys_manager.backing.get_node_secret_key())
414 pay_invoice(&invoice, Retry::Attempts(0), nodes[0].node).unwrap();
415 check_added_monitors(&nodes[0], 1);
416 let send_event = SendEvent::from_node(&nodes[0]);
417 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
418 commitment_signed_dance!(nodes[1], nodes[0], &send_event.commitment_msg, false);
420 expect_pending_htlcs_forwardable!(nodes[1]);
422 let mut events = nodes[1].node.get_and_clear_pending_events();
423 assert_eq!(events.len(), 1);
424 match events.pop().unwrap() {
425 Event::PaymentClaimable { onion_fields, .. } => {
426 assert_eq!(Some(payment_metadata), onion_fields.unwrap().payment_metadata);
428 _ => panic!("Unexpected event")