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 crate::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::events::Event;
89 use lightning::ln::channelmanager::{Retry, PaymentId};
90 use lightning::ln::msgs::ChannelMessageHandler;
91 use lightning::ln::PaymentSecret;
92 use lightning::ln::functional_test_utils::*;
93 use lightning::routing::router::Payee;
94 use secp256k1::{SecretKey, PublicKey, Secp256k1};
95 use std::time::{SystemTime, Duration};
97 fn duration_since_epoch() -> Duration {
98 #[cfg(feature = "std")]
99 let duration_since_epoch =
100 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
101 #[cfg(not(feature = "std"))]
102 let duration_since_epoch = Duration::from_secs(1234567);
108 let payment_hash = Sha256::hash(&[0; 32]);
109 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
110 let secp_ctx = Secp256k1::new();
111 let public_key = PublicKey::from_secret_key(&secp_ctx, &private_key);
113 let invoice = InvoiceBuilder::new(Currency::Bitcoin)
114 .description("test".into())
115 .payment_hash(payment_hash)
116 .payment_secret(PaymentSecret([0; 32]))
117 .duration_since_epoch(duration_since_epoch())
118 .min_final_cltv_expiry_delta(144)
119 .amount_milli_satoshis(128)
120 .build_signed(|hash| {
121 secp_ctx.sign_ecdsa_recoverable(hash, &private_key)
125 assert!(payment_parameters_from_zero_amount_invoice(&invoice, 42).is_err());
127 let (hash, onion, params) = payment_parameters_from_invoice(&invoice).unwrap();
128 assert_eq!(&hash.0[..], &payment_hash[..]);
129 assert_eq!(onion.payment_secret, Some(PaymentSecret([0; 32])));
130 assert_eq!(params.final_value_msat, 128);
131 match params.payment_params.payee {
132 Payee::Clear { node_id, .. } => {
133 assert_eq!(node_id, public_key);
140 fn zero_value_invoice_test() {
141 let payment_hash = Sha256::hash(&[0; 32]);
142 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
143 let secp_ctx = Secp256k1::new();
144 let public_key = PublicKey::from_secret_key(&secp_ctx, &private_key);
146 let invoice = InvoiceBuilder::new(Currency::Bitcoin)
147 .description("test".into())
148 .payment_hash(payment_hash)
149 .payment_secret(PaymentSecret([0; 32]))
150 .duration_since_epoch(duration_since_epoch())
151 .min_final_cltv_expiry_delta(144)
152 .build_signed(|hash| {
153 secp_ctx.sign_ecdsa_recoverable(hash, &private_key)
157 assert!(payment_parameters_from_invoice(&invoice).is_err());
159 let (hash, onion, params) = payment_parameters_from_zero_amount_invoice(&invoice, 42).unwrap();
160 assert_eq!(&hash.0[..], &payment_hash[..]);
161 assert_eq!(onion.payment_secret, Some(PaymentSecret([0; 32])));
162 assert_eq!(params.final_value_msat, 42);
163 match params.payment_params.payee {
164 Payee::Clear { node_id, .. } => {
165 assert_eq!(node_id, public_key);
172 #[cfg(feature = "std")]
173 fn payment_metadata_end_to_end() {
174 // Test that a payment metadata read from an invoice passed to `pay_invoice` makes it all
175 // the way out through the `PaymentClaimable` event.
176 let chanmon_cfgs = create_chanmon_cfgs(2);
177 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
178 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
179 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
180 create_announced_chan_between_nodes(&nodes, 0, 1);
182 let payment_metadata = vec![42, 43, 44, 45, 46, 47, 48, 49, 42];
184 let (payment_hash, payment_secret) =
185 nodes[1].node.create_inbound_payment(None, 7200, None).unwrap();
187 let invoice = InvoiceBuilder::new(Currency::Bitcoin)
188 .description("test".into())
189 .payment_hash(Sha256::from_slice(&payment_hash.0).unwrap())
190 .payment_secret(payment_secret)
192 .min_final_cltv_expiry_delta(144)
193 .amount_milli_satoshis(50_000)
194 .payment_metadata(payment_metadata.clone())
195 .build_signed(|hash| {
196 Secp256k1::new().sign_ecdsa_recoverable(hash,
197 &nodes[1].keys_manager.backing.get_node_secret_key())
201 let (hash, onion, params) = payment_parameters_from_invoice(&invoice).unwrap();
202 nodes[0].node.send_payment(hash, onion, PaymentId(hash.0), params, Retry::Attempts(0)).unwrap();
203 check_added_monitors(&nodes[0], 1);
204 let send_event = SendEvent::from_node(&nodes[0]);
205 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
206 commitment_signed_dance!(nodes[1], nodes[0], &send_event.commitment_msg, false);
208 expect_pending_htlcs_forwardable!(nodes[1]);
210 let mut events = nodes[1].node.get_and_clear_pending_events();
211 assert_eq!(events.len(), 1);
212 match events.pop().unwrap() {
213 Event::PaymentClaimable { onion_fields, .. } => {
214 assert_eq!(Some(payment_metadata), onion_fields.unwrap().payment_metadata);
216 _ => panic!("Unexpected event")