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.
14 use bitcoin_hashes::Hash;
17 use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
18 use lightning::chain::keysinterface::{NodeSigner, SignerProvider, EntropySource};
19 use lightning::ln::{PaymentHash, PaymentSecret};
20 use lightning::ln::channelmanager::{ChannelManager, PaymentId, Retry, RetryableSendFailure};
21 use lightning::routing::router::{PaymentParameters, RouteParameters, Router};
22 use lightning::util::logger::Logger;
26 use core::time::Duration;
28 /// Pays the given [`Invoice`], retrying if needed based on [`Retry`].
30 /// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
31 /// as the payment is still pending. Once the payment completes or fails, you must ensure that
32 /// a second payment 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: &Invoice, 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 [`Invoice`] with a custom idempotency key, retrying if needed based on [`Retry`].
56 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
57 /// payment completes or fails, no idempotency guarantees are made.
59 /// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
60 /// has never been paid before.
62 /// See [`pay_invoice`] for a variant which uses the [`PaymentHash`] for the idempotency token.
63 pub fn pay_invoice_with_id<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
64 invoice: &Invoice, payment_id: PaymentId, retry_strategy: Retry,
65 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>
66 ) -> Result<(), PaymentError>
68 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
69 T::Target: BroadcasterInterface,
70 ES::Target: EntropySource,
71 NS::Target: NodeSigner,
72 SP::Target: SignerProvider,
73 F::Target: FeeEstimator,
77 let amt_msat = invoice.amount_milli_satoshis().ok_or(PaymentError::Invoice("amount missing"))?;
78 pay_invoice_using_amount(invoice, amt_msat, payment_id, retry_strategy, channelmanager)
81 /// Pays the given zero-value [`Invoice`] using the given amount, retrying if needed based on
84 /// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
85 /// as the payment is still pending. Once the payment completes or fails, you must ensure that
86 /// a second payment with the same [`PaymentHash`] is never sent.
88 /// If you wish to use a different payment idempotency token, see
89 /// [`pay_zero_value_invoice_with_id`].
90 pub fn pay_zero_value_invoice<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
91 invoice: &Invoice, amount_msats: u64, retry_strategy: Retry,
92 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>
93 ) -> Result<PaymentId, PaymentError>
95 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
96 T::Target: BroadcasterInterface,
97 ES::Target: EntropySource,
98 NS::Target: NodeSigner,
99 SP::Target: SignerProvider,
100 F::Target: FeeEstimator,
104 let payment_id = PaymentId(invoice.payment_hash().into_inner());
105 pay_zero_value_invoice_with_id(invoice, amount_msats, payment_id, retry_strategy,
107 .map(|()| payment_id)
110 /// Pays the given zero-value [`Invoice`] using the given amount and custom idempotency key,
111 /// , retrying if needed based on [`Retry`].
113 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
114 /// payment completes or fails, no idempotency guarantees are made.
116 /// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
117 /// has never been paid before.
119 /// See [`pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the
120 /// idempotency token.
121 pub fn pay_zero_value_invoice_with_id<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
122 invoice: &Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
123 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>
124 ) -> Result<(), PaymentError>
126 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
127 T::Target: BroadcasterInterface,
128 ES::Target: EntropySource,
129 NS::Target: NodeSigner,
130 SP::Target: SignerProvider,
131 F::Target: FeeEstimator,
135 if invoice.amount_milli_satoshis().is_some() {
136 Err(PaymentError::Invoice("amount unexpected"))
138 pay_invoice_using_amount(invoice, amount_msats, payment_id, retry_strategy,
143 fn pay_invoice_using_amount<P: Deref>(
144 invoice: &Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
146 ) -> Result<(), PaymentError> where P::Target: Payer {
147 let payment_hash = PaymentHash((*invoice.payment_hash()).into_inner());
148 let payment_secret = Some(*invoice.payment_secret());
149 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(),
150 invoice.min_final_cltv_expiry_delta() as u32)
151 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
152 .with_route_hints(invoice.route_hints());
153 if let Some(features) = invoice.features() {
154 payment_params = payment_params.with_features(features.clone());
156 let route_params = RouteParameters {
158 final_value_msat: amount_msats,
161 payer.send_payment(payment_hash, &payment_secret, payment_id, route_params, retry_strategy)
164 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
165 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
168 /// An error that may occur when making a payment.
169 #[derive(Clone, Debug)]
170 pub enum PaymentError {
171 /// An error resulting from the provided [`Invoice`] or payment hash.
172 Invoice(&'static str),
173 /// An error occurring when sending a payment.
174 Sending(RetryableSendFailure),
177 /// A trait defining behavior of an [`Invoice`] payer.
179 /// Useful for unit testing internal methods.
181 /// Sends a payment over the Lightning Network using the given [`Route`].
183 /// [`Route`]: lightning::routing::router::Route
185 &self, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
186 payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry
187 ) -> Result<(), PaymentError>;
190 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>
192 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
193 T::Target: BroadcasterInterface,
194 ES::Target: EntropySource,
195 NS::Target: NodeSigner,
196 SP::Target: SignerProvider,
197 F::Target: FeeEstimator,
202 &self, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
203 payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry
204 ) -> Result<(), PaymentError> {
205 self.send_payment_with_retry(payment_hash, payment_secret, payment_id, route_params, retry_strategy)
206 .map_err(PaymentError::Sending)
213 use crate::{InvoiceBuilder, Currency};
214 use bitcoin_hashes::sha256::Hash as Sha256;
215 use lightning::ln::PaymentPreimage;
216 use lightning::ln::functional_test_utils::*;
217 use secp256k1::{SecretKey, Secp256k1};
218 use std::collections::VecDeque;
219 use std::time::{SystemTime, Duration};
222 expectations: core::cell::RefCell<VecDeque<Amount>>,
228 expectations: core::cell::RefCell::new(VecDeque::new()),
232 fn expect_send(self, value_msat: Amount) -> Self {
233 self.expectations.borrow_mut().push_back(value_msat);
237 fn check_value_msats(&self, actual_value_msats: Amount) {
238 let expected_value_msats = self.expectations.borrow_mut().pop_front();
239 if let Some(expected_value_msats) = expected_value_msats {
240 assert_eq!(actual_value_msats, expected_value_msats);
242 panic!("Unexpected amount: {:?}", actual_value_msats);
247 #[derive(Clone, Debug, PartialEq, Eq)]
248 struct Amount(u64); // msat
250 impl Payer for TestPayer {
252 &self, _payment_hash: PaymentHash, _payment_secret: &Option<PaymentSecret>,
253 _payment_id: PaymentId, route_params: RouteParameters, _retry_strategy: Retry
254 ) -> Result<(), PaymentError> {
255 self.check_value_msats(Amount(route_params.final_value_msat));
260 impl Drop for TestPayer {
262 if std::thread::panicking() {
266 if !self.expectations.borrow().is_empty() {
267 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
272 fn duration_since_epoch() -> Duration {
273 #[cfg(feature = "std")]
274 let duration_since_epoch =
275 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
276 #[cfg(not(feature = "std"))]
277 let duration_since_epoch = Duration::from_secs(1234567);
281 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
282 let payment_hash = Sha256::hash(&payment_preimage.0);
283 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
285 InvoiceBuilder::new(Currency::Bitcoin)
286 .description("test".into())
287 .payment_hash(payment_hash)
288 .payment_secret(PaymentSecret([0; 32]))
289 .duration_since_epoch(duration_since_epoch())
290 .min_final_cltv_expiry_delta(144)
291 .amount_milli_satoshis(128)
292 .build_signed(|hash| {
293 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
298 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
299 let payment_hash = Sha256::hash(&payment_preimage.0);
300 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
302 InvoiceBuilder::new(Currency::Bitcoin)
303 .description("test".into())
304 .payment_hash(payment_hash)
305 .payment_secret(PaymentSecret([0; 32]))
306 .duration_since_epoch(duration_since_epoch())
307 .min_final_cltv_expiry_delta(144)
308 .build_signed(|hash| {
309 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
316 let payment_id = PaymentId([42; 32]);
317 let payment_preimage = PaymentPreimage([1; 32]);
318 let invoice = invoice(payment_preimage);
319 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
321 let payer = TestPayer::new().expect_send(Amount(final_value_msat));
322 pay_invoice_using_amount(&invoice, final_value_msat, payment_id, Retry::Attempts(0), &payer).unwrap();
326 fn pays_zero_value_invoice() {
327 let payment_id = PaymentId([42; 32]);
328 let payment_preimage = PaymentPreimage([1; 32]);
329 let invoice = zero_value_invoice(payment_preimage);
330 let amt_msat = 10_000;
332 let payer = TestPayer::new().expect_send(Amount(amt_msat));
333 pay_invoice_using_amount(&invoice, amt_msat, payment_id, Retry::Attempts(0), &payer).unwrap();
337 fn fails_paying_zero_value_invoice_with_amount() {
338 let chanmon_cfgs = create_chanmon_cfgs(1);
339 let node_cfgs = create_node_cfgs(1, &chanmon_cfgs);
340 let node_chanmgrs = create_node_chanmgrs(1, &node_cfgs, &[None]);
341 let nodes = create_network(1, &node_cfgs, &node_chanmgrs);
343 let payment_preimage = PaymentPreimage([1; 32]);
344 let invoice = invoice(payment_preimage);
345 let amt_msat = 10_000;
347 match pay_zero_value_invoice(&invoice, amt_msat, Retry::Attempts(0), nodes[0].node) {
348 Err(PaymentError::Invoice("amount unexpected")) => {},