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 {
121 final_value_msat: amount_msats,
124 payer.send_payment(payment_hash, recipient_onion, payment_id, route_params, retry_strategy)
127 /// Sends payment probes over all paths of a route that would be used to pay the given invoice.
129 /// See [`ChannelManager::send_preflight_probes`] for more information.
130 pub fn preflight_probe_invoice<C: AChannelManager>(
131 invoice: &Bolt11Invoice, channelmanager: &C, liquidity_limit_multiplier: Option<u64>,
132 ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbingError>
134 let amount_msat = if let Some(invoice_amount_msat) = invoice.amount_milli_satoshis() {
137 return Err(ProbingError::Invoice("Failed to send probe as no amount was given in the invoice."));
140 let mut payment_params = PaymentParameters::from_node_id(
141 invoice.recover_payee_pub_key(),
142 invoice.min_final_cltv_expiry_delta() as u32,
144 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
145 .with_route_hints(invoice.route_hints())
148 if let Some(features) = invoice.features() {
149 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
151 let route_params = RouteParameters { payment_params, final_value_msat: amount_msat };
153 channelmanager.get_cm().send_preflight_probes(route_params, liquidity_limit_multiplier)
154 .map_err(ProbingError::Sending)
157 /// Sends payment probes over all paths of a route that would be used to pay the given zero-value
158 /// invoice using the given amount.
160 /// See [`ChannelManager::send_preflight_probes`] for more information.
161 pub fn preflight_probe_zero_value_invoice<C: AChannelManager>(
162 invoice: &Bolt11Invoice, amount_msat: u64, channelmanager: &C,
163 liquidity_limit_multiplier: Option<u64>,
164 ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbingError>
166 if invoice.amount_milli_satoshis().is_some() {
167 return Err(ProbingError::Invoice("amount unexpected"));
170 let mut payment_params = PaymentParameters::from_node_id(
171 invoice.recover_payee_pub_key(),
172 invoice.min_final_cltv_expiry_delta() as u32,
174 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
175 .with_route_hints(invoice.route_hints())
178 if let Some(features) = invoice.features() {
179 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
181 let route_params = RouteParameters { payment_params, final_value_msat: amount_msat };
183 channelmanager.get_cm().send_preflight_probes(route_params, liquidity_limit_multiplier)
184 .map_err(ProbingError::Sending)
187 fn expiry_time_from_unix_epoch(invoice: &Bolt11Invoice) -> Duration {
188 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
191 /// An error that may occur when making a payment.
192 #[derive(Clone, Debug, PartialEq, Eq)]
193 pub enum PaymentError {
194 /// An error resulting from the provided [`Bolt11Invoice`] or payment hash.
195 Invoice(&'static str),
196 /// An error occurring when sending a payment.
197 Sending(RetryableSendFailure),
200 /// An error that may occur when sending a payment probe.
201 #[derive(Clone, Debug, PartialEq, Eq)]
202 pub enum ProbingError {
203 /// An error resulting from the provided [`Bolt11Invoice`].
204 Invoice(&'static str),
205 /// An error occurring when sending a payment probe.
206 Sending(ProbeSendFailure),
209 /// A trait defining behavior of a [`Bolt11Invoice`] payer.
211 /// Useful for unit testing internal methods.
213 /// Sends a payment over the Lightning Network using the given [`Route`].
215 /// [`Route`]: lightning::routing::router::Route
217 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
218 payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry
219 ) -> Result<(), PaymentError>;
222 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>
224 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
225 T::Target: BroadcasterInterface,
226 ES::Target: EntropySource,
227 NS::Target: NodeSigner,
228 SP::Target: SignerProvider,
229 F::Target: FeeEstimator,
234 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
235 payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry
236 ) -> Result<(), PaymentError> {
237 self.send_payment(payment_hash, recipient_onion, payment_id, route_params, retry_strategy)
238 .map_err(PaymentError::Sending)
245 use crate::{InvoiceBuilder, Currency};
246 use bitcoin_hashes::sha256::Hash as Sha256;
247 use lightning::events::Event;
248 use lightning::ln::msgs::ChannelMessageHandler;
249 use lightning::ln::{PaymentPreimage, PaymentSecret};
250 use lightning::ln::functional_test_utils::*;
251 use secp256k1::{SecretKey, Secp256k1};
252 use std::collections::VecDeque;
253 use std::time::{SystemTime, Duration};
256 expectations: core::cell::RefCell<VecDeque<Amount>>,
262 expectations: core::cell::RefCell::new(VecDeque::new()),
266 fn expect_send(self, value_msat: Amount) -> Self {
267 self.expectations.borrow_mut().push_back(value_msat);
271 fn check_value_msats(&self, actual_value_msats: Amount) {
272 let expected_value_msats = self.expectations.borrow_mut().pop_front();
273 if let Some(expected_value_msats) = expected_value_msats {
274 assert_eq!(actual_value_msats, expected_value_msats);
276 panic!("Unexpected amount: {:?}", actual_value_msats);
281 #[derive(Clone, Debug, PartialEq, Eq)]
282 struct Amount(u64); // msat
284 impl Payer for TestPayer {
286 &self, _payment_hash: PaymentHash, _recipient_onion: RecipientOnionFields,
287 _payment_id: PaymentId, route_params: RouteParameters, _retry_strategy: Retry
288 ) -> Result<(), PaymentError> {
289 self.check_value_msats(Amount(route_params.final_value_msat));
294 impl Drop for TestPayer {
296 if std::thread::panicking() {
300 if !self.expectations.borrow().is_empty() {
301 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
306 fn duration_since_epoch() -> Duration {
307 #[cfg(feature = "std")]
308 let duration_since_epoch =
309 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
310 #[cfg(not(feature = "std"))]
311 let duration_since_epoch = Duration::from_secs(1234567);
315 fn invoice(payment_preimage: PaymentPreimage) -> Bolt11Invoice {
316 let payment_hash = Sha256::hash(&payment_preimage.0);
317 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
319 InvoiceBuilder::new(Currency::Bitcoin)
320 .description("test".into())
321 .payment_hash(payment_hash)
322 .payment_secret(PaymentSecret([0; 32]))
323 .duration_since_epoch(duration_since_epoch())
324 .min_final_cltv_expiry_delta(144)
325 .amount_milli_satoshis(128)
326 .build_signed(|hash| {
327 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
332 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Bolt11Invoice {
333 let payment_hash = Sha256::hash(&payment_preimage.0);
334 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
336 InvoiceBuilder::new(Currency::Bitcoin)
337 .description("test".into())
338 .payment_hash(payment_hash)
339 .payment_secret(PaymentSecret([0; 32]))
340 .duration_since_epoch(duration_since_epoch())
341 .min_final_cltv_expiry_delta(144)
342 .build_signed(|hash| {
343 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
350 let payment_id = PaymentId([42; 32]);
351 let payment_preimage = PaymentPreimage([1; 32]);
352 let invoice = invoice(payment_preimage);
353 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
355 let payer = TestPayer::new().expect_send(Amount(final_value_msat));
356 pay_invoice_using_amount(&invoice, final_value_msat, payment_id, Retry::Attempts(0), &payer).unwrap();
360 fn pays_zero_value_invoice() {
361 let payment_id = PaymentId([42; 32]);
362 let payment_preimage = PaymentPreimage([1; 32]);
363 let invoice = zero_value_invoice(payment_preimage);
364 let amt_msat = 10_000;
366 let payer = TestPayer::new().expect_send(Amount(amt_msat));
367 pay_invoice_using_amount(&invoice, amt_msat, payment_id, Retry::Attempts(0), &payer).unwrap();
371 fn fails_paying_zero_value_invoice_with_amount() {
372 let chanmon_cfgs = create_chanmon_cfgs(1);
373 let node_cfgs = create_node_cfgs(1, &chanmon_cfgs);
374 let node_chanmgrs = create_node_chanmgrs(1, &node_cfgs, &[None]);
375 let nodes = create_network(1, &node_cfgs, &node_chanmgrs);
377 let payment_preimage = PaymentPreimage([1; 32]);
378 let invoice = invoice(payment_preimage);
379 let amt_msat = 10_000;
381 match pay_zero_value_invoice(&invoice, amt_msat, Retry::Attempts(0), nodes[0].node) {
382 Err(PaymentError::Invoice("amount unexpected")) => {},
388 #[cfg(feature = "std")]
389 fn payment_metadata_end_to_end() {
390 // Test that a payment metadata read from an invoice passed to `pay_invoice` makes it all
391 // the way out through the `PaymentClaimable` event.
392 let chanmon_cfgs = create_chanmon_cfgs(2);
393 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
394 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
395 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
396 create_announced_chan_between_nodes(&nodes, 0, 1);
398 let payment_metadata = vec![42, 43, 44, 45, 46, 47, 48, 49, 42];
400 let (payment_hash, payment_secret) =
401 nodes[1].node.create_inbound_payment(None, 7200, None).unwrap();
403 let invoice = InvoiceBuilder::new(Currency::Bitcoin)
404 .description("test".into())
405 .payment_hash(Sha256::from_slice(&payment_hash.0).unwrap())
406 .payment_secret(payment_secret)
408 .min_final_cltv_expiry_delta(144)
409 .amount_milli_satoshis(50_000)
410 .payment_metadata(payment_metadata.clone())
411 .build_signed(|hash| {
412 Secp256k1::new().sign_ecdsa_recoverable(hash,
413 &nodes[1].keys_manager.backing.get_node_secret_key())
417 pay_invoice(&invoice, Retry::Attempts(0), nodes[0].node).unwrap();
418 check_added_monitors(&nodes[0], 1);
419 let send_event = SendEvent::from_node(&nodes[0]);
420 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
421 commitment_signed_dance!(nodes[1], nodes[0], &send_event.commitment_msg, false);
423 expect_pending_htlcs_forwardable!(nodes[1]);
425 let mut events = nodes[1].node.get_and_clear_pending_events();
426 assert_eq!(events.len(), 1);
427 match events.pop().unwrap() {
428 Event::PaymentClaimable { onion_fields, .. } => {
429 assert_eq!(Some(payment_metadata), onion_fields.unwrap().payment_metadata);
431 _ => panic!("Unexpected event")