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;
13 use bitcoin::hashes::Hash;
15 use lightning::ln::PaymentHash;
16 use lightning::ln::channelmanager::RecipientOnionFields;
17 use lightning::routing::router::{PaymentParameters, RouteParameters};
19 /// Builds the necessary parameters to pay or pre-flight probe the given zero-amount
20 /// [`Bolt11Invoice`] using [`ChannelManager::send_payment`] or
21 /// [`ChannelManager::send_preflight_probes`].
23 /// Prior to paying, you must ensure that the [`Bolt11Invoice::payment_hash`] is unique and the
24 /// same [`PaymentHash`] has never been paid before.
26 /// Will always succeed unless the invoice has an amount specified, in which case
27 /// [`payment_parameters_from_invoice`] should be used.
29 /// [`ChannelManager::send_payment`]: lightning::ln::channelmanager::ChannelManager::send_payment
30 /// [`ChannelManager::send_preflight_probes`]: lightning::ln::channelmanager::ChannelManager::send_preflight_probes
31 pub fn payment_parameters_from_zero_amount_invoice(invoice: &Bolt11Invoice, amount_msat: u64)
32 -> Result<(PaymentHash, RecipientOnionFields, RouteParameters), ()> {
33 if invoice.amount_milli_satoshis().is_some() {
36 Ok(params_from_invoice(invoice, amount_msat))
40 /// Builds the necessary parameters to pay or pre-flight probe the given [`Bolt11Invoice`] using
41 /// [`ChannelManager::send_payment`] or [`ChannelManager::send_preflight_probes`].
43 /// Prior to paying, you must ensure that the [`Bolt11Invoice::payment_hash`] is unique and the
44 /// same [`PaymentHash`] has never been paid before.
46 /// Will always succeed unless the invoice has no amount specified, in which case
47 /// [`payment_parameters_from_zero_amount_invoice`] should be used.
49 /// [`ChannelManager::send_payment`]: lightning::ln::channelmanager::ChannelManager::send_payment
50 /// [`ChannelManager::send_preflight_probes`]: lightning::ln::channelmanager::ChannelManager::send_preflight_probes
51 pub fn payment_parameters_from_invoice(invoice: &Bolt11Invoice)
52 -> Result<(PaymentHash, RecipientOnionFields, RouteParameters), ()> {
53 if let Some(amount_msat) = invoice.amount_milli_satoshis() {
54 Ok(params_from_invoice(invoice, amount_msat))
60 fn params_from_invoice(invoice: &Bolt11Invoice, amount_msat: u64)
61 -> (PaymentHash, RecipientOnionFields, RouteParameters) {
62 let payment_hash = PaymentHash((*invoice.payment_hash()).to_byte_array());
64 let mut recipient_onion = RecipientOnionFields::secret_only(*invoice.payment_secret());
65 recipient_onion.payment_metadata = invoice.payment_metadata().map(|v| v.clone());
67 let mut payment_params = PaymentParameters::from_node_id(
68 invoice.recover_payee_pub_key(),
69 invoice.min_final_cltv_expiry_delta() as u32
71 .with_route_hints(invoice.route_hints()).unwrap();
72 if let Some(expiry) = invoice.expires_at() {
73 payment_params = payment_params.with_expiry_time(expiry.as_secs());
75 if let Some(features) = invoice.features() {
76 payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
79 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
80 (payment_hash, recipient_onion, route_params)
86 use crate::{InvoiceBuilder, Currency};
87 use bitcoin::hashes::sha256::Hash as Sha256;
88 use lightning::ln::PaymentSecret;
89 use lightning::routing::router::Payee;
90 use secp256k1::{SecretKey, PublicKey, Secp256k1};
91 use core::time::Duration;
92 #[cfg(feature = "std")]
93 use std::time::SystemTime;
95 fn duration_since_epoch() -> Duration {
96 #[cfg(feature = "std")]
97 let duration_since_epoch =
98 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
99 #[cfg(not(feature = "std"))]
100 let duration_since_epoch = Duration::from_secs(1234567);
106 let payment_hash = Sha256::hash(&[0; 32]);
107 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
108 let secp_ctx = Secp256k1::new();
109 let public_key = PublicKey::from_secret_key(&secp_ctx, &private_key);
111 let invoice = InvoiceBuilder::new(Currency::Bitcoin)
112 .description("test".into())
113 .payment_hash(payment_hash)
114 .payment_secret(PaymentSecret([0; 32]))
115 .duration_since_epoch(duration_since_epoch())
116 .min_final_cltv_expiry_delta(144)
117 .amount_milli_satoshis(128)
118 .build_signed(|hash| {
119 secp_ctx.sign_ecdsa_recoverable(hash, &private_key)
123 assert!(payment_parameters_from_zero_amount_invoice(&invoice, 42).is_err());
125 let (hash, onion, params) = payment_parameters_from_invoice(&invoice).unwrap();
126 assert_eq!(&hash.0[..], &payment_hash[..]);
127 assert_eq!(onion.payment_secret, Some(PaymentSecret([0; 32])));
128 assert_eq!(params.final_value_msat, 128);
129 match params.payment_params.payee {
130 Payee::Clear { node_id, .. } => {
131 assert_eq!(node_id, public_key);
138 fn zero_value_invoice_test() {
139 let payment_hash = Sha256::hash(&[0; 32]);
140 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
141 let secp_ctx = Secp256k1::new();
142 let public_key = PublicKey::from_secret_key(&secp_ctx, &private_key);
144 let invoice = InvoiceBuilder::new(Currency::Bitcoin)
145 .description("test".into())
146 .payment_hash(payment_hash)
147 .payment_secret(PaymentSecret([0; 32]))
148 .duration_since_epoch(duration_since_epoch())
149 .min_final_cltv_expiry_delta(144)
150 .build_signed(|hash| {
151 secp_ctx.sign_ecdsa_recoverable(hash, &private_key)
155 assert!(payment_parameters_from_invoice(&invoice).is_err());
157 let (hash, onion, params) = payment_parameters_from_zero_amount_invoice(&invoice, 42).unwrap();
158 assert_eq!(&hash.0[..], &payment_hash[..]);
159 assert_eq!(onion.payment_secret, Some(PaymentSecret([0; 32])));
160 assert_eq!(params.final_value_msat, 42);
161 match params.payment_params.payee {
162 Payee::Clear { node_id, .. } => {
163 assert_eq!(node_id, public_key);
170 #[cfg(feature = "std")]
171 fn payment_metadata_end_to_end() {
172 use lightning::events::Event;
173 use lightning::ln::channelmanager::{Retry, PaymentId};
174 use lightning::ln::msgs::ChannelMessageHandler;
175 use lightning::ln::functional_test_utils::*;
176 // Test that a payment metadata read from an invoice passed to `pay_invoice` makes it all
177 // the way out through the `PaymentClaimable` event.
178 let chanmon_cfgs = create_chanmon_cfgs(2);
179 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
180 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
181 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
182 create_announced_chan_between_nodes(&nodes, 0, 1);
184 let payment_metadata = vec![42, 43, 44, 45, 46, 47, 48, 49, 42];
186 let (payment_hash, payment_secret) =
187 nodes[1].node.create_inbound_payment(None, 7200, None).unwrap();
189 let invoice = InvoiceBuilder::new(Currency::Bitcoin)
190 .description("test".into())
191 .payment_hash(Sha256::from_slice(&payment_hash.0).unwrap())
192 .payment_secret(payment_secret)
194 .min_final_cltv_expiry_delta(144)
195 .amount_milli_satoshis(50_000)
196 .payment_metadata(payment_metadata.clone())
197 .build_signed(|hash| {
198 Secp256k1::new().sign_ecdsa_recoverable(hash,
199 &nodes[1].keys_manager.backing.get_node_secret_key())
203 let (hash, onion, params) = payment_parameters_from_invoice(&invoice).unwrap();
204 nodes[0].node.send_payment(hash, onion, PaymentId(hash.0), params, Retry::Attempts(0)).unwrap();
205 check_added_monitors(&nodes[0], 1);
206 let send_event = SendEvent::from_node(&nodes[0]);
207 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
208 commitment_signed_dance!(nodes[1], nodes[0], &send_event.commitment_msg, false);
210 expect_pending_htlcs_forwardable!(nodes[1]);
212 let mut events = nodes[1].node.get_and_clear_pending_events();
213 assert_eq!(events.len(), 1);
214 match events.pop().unwrap() {
215 Event::PaymentClaimable { onion_fields, .. } => {
216 assert_eq!(Some(payment_metadata), onion_fields.unwrap().payment_metadata);
218 _ => panic!("Unexpected event")