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 and sending spontaneous payments.
12 use crate::Bolt11Invoice;
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::{ChannelManager, PaymentId, Retry, RetryableSendFailure, RecipientOnionFields};
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<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
36 invoice: &Bolt11Invoice, retry_strategy: Retry,
37 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>
38 ) -> Result<PaymentId, PaymentError>
40 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
41 T::Target: BroadcasterInterface,
42 ES::Target: EntropySource,
43 NS::Target: NodeSigner,
44 SP::Target: SignerProvider,
45 F::Target: FeeEstimator,
49 let payment_id = PaymentId(invoice.payment_hash().into_inner());
50 pay_invoice_with_id(invoice, payment_id, retry_strategy, channelmanager)
54 /// Pays the given [`Bolt11Invoice`] with a custom idempotency key, retrying if needed based on
57 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
58 /// payment completes or fails, no idempotency guarantees are made.
60 /// You should ensure that the [`Bolt11Invoice::payment_hash`] is unique and the same
61 /// [`PaymentHash`] has never been paid before.
63 /// See [`pay_invoice`] for a variant which uses the [`PaymentHash`] for the idempotency token.
64 pub fn pay_invoice_with_id<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
65 invoice: &Bolt11Invoice, payment_id: PaymentId, retry_strategy: Retry,
66 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>
67 ) -> Result<(), PaymentError>
69 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
70 T::Target: BroadcasterInterface,
71 ES::Target: EntropySource,
72 NS::Target: NodeSigner,
73 SP::Target: SignerProvider,
74 F::Target: FeeEstimator,
78 let amt_msat = invoice.amount_milli_satoshis().ok_or(PaymentError::Invoice("amount missing"))?;
79 pay_invoice_using_amount(invoice, amt_msat, payment_id, retry_strategy, channelmanager)
82 /// Pays the given zero-value [`Bolt11Invoice`] using the given amount, retrying if needed based on
85 /// [`Bolt11Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
86 /// as the payment is still pending. If the payment succeeds, you must ensure that a second payment
87 /// with the same [`PaymentHash`] is never sent.
89 /// If you wish to use a different payment idempotency token, see
90 /// [`pay_zero_value_invoice_with_id`].
91 pub fn pay_zero_value_invoice<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
92 invoice: &Bolt11Invoice, amount_msats: u64, retry_strategy: Retry,
93 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>
94 ) -> Result<PaymentId, PaymentError>
96 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
97 T::Target: BroadcasterInterface,
98 ES::Target: EntropySource,
99 NS::Target: NodeSigner,
100 SP::Target: SignerProvider,
101 F::Target: FeeEstimator,
105 let payment_id = PaymentId(invoice.payment_hash().into_inner());
106 pay_zero_value_invoice_with_id(invoice, amount_msats, payment_id, retry_strategy,
108 .map(|()| payment_id)
111 /// Pays the given zero-value [`Bolt11Invoice`] using the given amount and custom idempotency key,
112 /// retrying if needed based on [`Retry`].
114 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
115 /// payment completes or fails, no idempotency guarantees are made.
117 /// You should ensure that the [`Bolt11Invoice::payment_hash`] is unique and the same
118 /// [`PaymentHash`] has never been paid before.
120 /// See [`pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the
121 /// idempotency token.
122 pub fn pay_zero_value_invoice_with_id<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
123 invoice: &Bolt11Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
124 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>
125 ) -> Result<(), PaymentError>
127 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
128 T::Target: BroadcasterInterface,
129 ES::Target: EntropySource,
130 NS::Target: NodeSigner,
131 SP::Target: SignerProvider,
132 F::Target: FeeEstimator,
136 if invoice.amount_milli_satoshis().is_some() {
137 Err(PaymentError::Invoice("amount unexpected"))
139 pay_invoice_using_amount(invoice, amount_msats, payment_id, retry_strategy,
144 fn pay_invoice_using_amount<P: Deref>(
145 invoice: &Bolt11Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
147 ) -> Result<(), PaymentError> where P::Target: Payer {
148 let payment_hash = PaymentHash((*invoice.payment_hash()).into_inner());
149 let mut recipient_onion = RecipientOnionFields::secret_only(*invoice.payment_secret());
150 recipient_onion.payment_metadata = invoice.payment_metadata().map(|v| v.clone());
151 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(),
152 invoice.min_final_cltv_expiry_delta() as u32)
153 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
154 .with_route_hints(invoice.route_hints()).unwrap();
155 if let Some(features) = invoice.features() {
156 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
158 let route_params = RouteParameters {
160 final_value_msat: amount_msats,
163 payer.send_payment(payment_hash, recipient_onion, payment_id, route_params, retry_strategy)
166 fn expiry_time_from_unix_epoch(invoice: &Bolt11Invoice) -> Duration {
167 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
170 /// An error that may occur when making a payment.
171 #[derive(Clone, Debug, PartialEq, Eq)]
172 pub enum PaymentError {
173 /// An error resulting from the provided [`Bolt11Invoice`] or payment hash.
174 Invoice(&'static str),
175 /// An error occurring when sending a payment.
176 Sending(RetryableSendFailure),
179 /// A trait defining behavior of a [`Bolt11Invoice`] payer.
181 /// Useful for unit testing internal methods.
183 /// Sends a payment over the Lightning Network using the given [`Route`].
185 /// [`Route`]: lightning::routing::router::Route
187 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
188 payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry
189 ) -> Result<(), PaymentError>;
192 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>
194 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
195 T::Target: BroadcasterInterface,
196 ES::Target: EntropySource,
197 NS::Target: NodeSigner,
198 SP::Target: SignerProvider,
199 F::Target: FeeEstimator,
204 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
205 payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry
206 ) -> Result<(), PaymentError> {
207 self.send_payment(payment_hash, recipient_onion, payment_id, route_params, retry_strategy)
208 .map_err(PaymentError::Sending)
215 use crate::{InvoiceBuilder, Currency};
216 use bitcoin_hashes::sha256::Hash as Sha256;
217 use lightning::events::Event;
218 use lightning::ln::msgs::ChannelMessageHandler;
219 use lightning::ln::{PaymentPreimage, PaymentSecret};
220 use lightning::ln::functional_test_utils::*;
221 use secp256k1::{SecretKey, Secp256k1};
222 use std::collections::VecDeque;
223 use std::time::{SystemTime, Duration};
226 expectations: core::cell::RefCell<VecDeque<Amount>>,
232 expectations: core::cell::RefCell::new(VecDeque::new()),
236 fn expect_send(self, value_msat: Amount) -> Self {
237 self.expectations.borrow_mut().push_back(value_msat);
241 fn check_value_msats(&self, actual_value_msats: Amount) {
242 let expected_value_msats = self.expectations.borrow_mut().pop_front();
243 if let Some(expected_value_msats) = expected_value_msats {
244 assert_eq!(actual_value_msats, expected_value_msats);
246 panic!("Unexpected amount: {:?}", actual_value_msats);
251 #[derive(Clone, Debug, PartialEq, Eq)]
252 struct Amount(u64); // msat
254 impl Payer for TestPayer {
256 &self, _payment_hash: PaymentHash, _recipient_onion: RecipientOnionFields,
257 _payment_id: PaymentId, route_params: RouteParameters, _retry_strategy: Retry
258 ) -> Result<(), PaymentError> {
259 self.check_value_msats(Amount(route_params.final_value_msat));
264 impl Drop for TestPayer {
266 if std::thread::panicking() {
270 if !self.expectations.borrow().is_empty() {
271 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
276 fn duration_since_epoch() -> Duration {
277 #[cfg(feature = "std")]
278 let duration_since_epoch =
279 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
280 #[cfg(not(feature = "std"))]
281 let duration_since_epoch = Duration::from_secs(1234567);
285 fn invoice(payment_preimage: PaymentPreimage) -> Bolt11Invoice {
286 let payment_hash = Sha256::hash(&payment_preimage.0);
287 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
289 InvoiceBuilder::new(Currency::Bitcoin)
290 .description("test".into())
291 .payment_hash(payment_hash)
292 .payment_secret(PaymentSecret([0; 32]))
293 .duration_since_epoch(duration_since_epoch())
294 .min_final_cltv_expiry_delta(144)
295 .amount_milli_satoshis(128)
296 .build_signed(|hash| {
297 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
302 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Bolt11Invoice {
303 let payment_hash = Sha256::hash(&payment_preimage.0);
304 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
306 InvoiceBuilder::new(Currency::Bitcoin)
307 .description("test".into())
308 .payment_hash(payment_hash)
309 .payment_secret(PaymentSecret([0; 32]))
310 .duration_since_epoch(duration_since_epoch())
311 .min_final_cltv_expiry_delta(144)
312 .build_signed(|hash| {
313 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
320 let payment_id = PaymentId([42; 32]);
321 let payment_preimage = PaymentPreimage([1; 32]);
322 let invoice = invoice(payment_preimage);
323 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
325 let payer = TestPayer::new().expect_send(Amount(final_value_msat));
326 pay_invoice_using_amount(&invoice, final_value_msat, payment_id, Retry::Attempts(0), &payer).unwrap();
330 fn pays_zero_value_invoice() {
331 let payment_id = PaymentId([42; 32]);
332 let payment_preimage = PaymentPreimage([1; 32]);
333 let invoice = zero_value_invoice(payment_preimage);
334 let amt_msat = 10_000;
336 let payer = TestPayer::new().expect_send(Amount(amt_msat));
337 pay_invoice_using_amount(&invoice, amt_msat, payment_id, Retry::Attempts(0), &payer).unwrap();
341 fn fails_paying_zero_value_invoice_with_amount() {
342 let chanmon_cfgs = create_chanmon_cfgs(1);
343 let node_cfgs = create_node_cfgs(1, &chanmon_cfgs);
344 let node_chanmgrs = create_node_chanmgrs(1, &node_cfgs, &[None]);
345 let nodes = create_network(1, &node_cfgs, &node_chanmgrs);
347 let payment_preimage = PaymentPreimage([1; 32]);
348 let invoice = invoice(payment_preimage);
349 let amt_msat = 10_000;
351 match pay_zero_value_invoice(&invoice, amt_msat, Retry::Attempts(0), nodes[0].node) {
352 Err(PaymentError::Invoice("amount unexpected")) => {},
358 #[cfg(feature = "std")]
359 fn payment_metadata_end_to_end() {
360 // Test that a payment metadata read from an invoice passed to `pay_invoice` makes it all
361 // the way out through the `PaymentClaimable` event.
362 let chanmon_cfgs = create_chanmon_cfgs(2);
363 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
364 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
365 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
366 create_announced_chan_between_nodes(&nodes, 0, 1);
368 let payment_metadata = vec![42, 43, 44, 45, 46, 47, 48, 49, 42];
370 let (payment_hash, payment_secret) =
371 nodes[1].node.create_inbound_payment(None, 7200, None).unwrap();
373 let invoice = InvoiceBuilder::new(Currency::Bitcoin)
374 .description("test".into())
375 .payment_hash(Sha256::from_slice(&payment_hash.0).unwrap())
376 .payment_secret(payment_secret)
378 .min_final_cltv_expiry_delta(144)
379 .amount_milli_satoshis(50_000)
380 .payment_metadata(payment_metadata.clone())
381 .build_signed(|hash| {
382 Secp256k1::new().sign_ecdsa_recoverable(hash,
383 &nodes[1].keys_manager.backing.get_node_secret_key())
387 pay_invoice(&invoice, Retry::Attempts(0), nodes[0].node).unwrap();
388 check_added_monitors(&nodes[0], 1);
389 let send_event = SendEvent::from_node(&nodes[0]);
390 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
391 commitment_signed_dance!(nodes[1], nodes[0], &send_event.commitment_msg, false);
393 expect_pending_htlcs_forwardable!(nodes[1]);
395 let mut events = nodes[1].node.get_and_clear_pending_events();
396 assert_eq!(events.len(), 1);
397 match events.pop().unwrap() {
398 Event::PaymentClaimable { onion_fields, .. } => {
399 assert_eq!(Some(payment_metadata), onion_fields.unwrap().payment_metadata);
401 _ => panic!("Unexpected event")