lightning/ln/
bolt11_payment.rs

1// This file is Copyright its original authors, visible in version control
2// history.
3//
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
8// licenses.
9
10//! Convenient utilities for paying Lightning invoices.
11
12use bitcoin::hashes::Hash;
13use lightning_invoice::Bolt11Invoice;
14
15use crate::ln::channelmanager::RecipientOnionFields;
16use crate::routing::router::{PaymentParameters, RouteParameters};
17use crate::types::payment::PaymentHash;
18
19/// Builds the necessary parameters to pay or pre-flight probe the given variable-amount
20/// (also known as 'zero-amount') [`Bolt11Invoice`] using
21/// [`ChannelManager::send_payment`] or [`ChannelManager::send_preflight_probes`].
22///
23/// Prior to paying, you must ensure that the [`Bolt11Invoice::payment_hash`] is unique and the
24/// same [`PaymentHash`] has never been paid before.
25///
26/// Will always succeed unless the invoice has an amount specified, in which case
27/// [`payment_parameters_from_invoice`] should be used.
28///
29/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
30/// [`ChannelManager::send_preflight_probes`]: crate::ln::channelmanager::ChannelManager::send_preflight_probes
31pub fn payment_parameters_from_variable_amount_invoice(
32	invoice: &Bolt11Invoice, amount_msat: u64,
33) -> Result<(PaymentHash, RecipientOnionFields, RouteParameters), ()> {
34	if invoice.amount_milli_satoshis().is_some() {
35		Err(())
36	} else {
37		Ok(params_from_invoice(invoice, amount_msat))
38	}
39}
40
41/// Builds the necessary parameters to pay or pre-flight probe the given [`Bolt11Invoice`] using
42/// [`ChannelManager::send_payment`] or [`ChannelManager::send_preflight_probes`].
43///
44/// Prior to paying, you must ensure that the [`Bolt11Invoice::payment_hash`] is unique and the
45/// same [`PaymentHash`] has never been paid before.
46///
47/// Will always succeed unless the invoice has no amount specified, in which case
48/// [`payment_parameters_from_variable_amount_invoice`] should be used.
49///
50/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
51/// [`ChannelManager::send_preflight_probes`]: crate::ln::channelmanager::ChannelManager::send_preflight_probes
52pub fn payment_parameters_from_invoice(
53	invoice: &Bolt11Invoice,
54) -> Result<(PaymentHash, RecipientOnionFields, RouteParameters), ()> {
55	if let Some(amount_msat) = invoice.amount_milli_satoshis() {
56		Ok(params_from_invoice(invoice, amount_msat))
57	} else {
58		Err(())
59	}
60}
61
62fn params_from_invoice(
63	invoice: &Bolt11Invoice, amount_msat: u64,
64) -> (PaymentHash, RecipientOnionFields, RouteParameters) {
65	let payment_hash = PaymentHash((*invoice.payment_hash()).to_byte_array());
66
67	let mut recipient_onion = RecipientOnionFields::secret_only(*invoice.payment_secret());
68	recipient_onion.payment_metadata = invoice.payment_metadata().map(|v| v.clone());
69
70	let mut payment_params = PaymentParameters::from_node_id(
71		invoice.recover_payee_pub_key(),
72		invoice.min_final_cltv_expiry_delta() as u32,
73	)
74	.with_route_hints(invoice.route_hints())
75	.unwrap();
76	if let Some(expiry) = invoice.expires_at() {
77		payment_params = payment_params.with_expiry_time(expiry.as_secs());
78	}
79	if let Some(features) = invoice.features() {
80		payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
81	}
82
83	let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
84	(payment_hash, recipient_onion, route_params)
85}
86
87#[cfg(test)]
88mod tests {
89	use super::*;
90	use crate::routing::router::Payee;
91	use crate::types::payment::PaymentSecret;
92	use bitcoin::hashes::sha256::Hash as Sha256;
93	use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
94	use lightning_invoice::{Currency, InvoiceBuilder};
95	use std::time::SystemTime;
96
97	#[test]
98	fn invoice_test() {
99		let payment_hash = Sha256::hash(&[0; 32]);
100		let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
101		let secp_ctx = Secp256k1::new();
102		let public_key = PublicKey::from_secret_key(&secp_ctx, &private_key);
103
104		let timestamp = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
105		let invoice = InvoiceBuilder::new(Currency::Bitcoin)
106			.description("test".into())
107			.payment_hash(payment_hash)
108			.payment_secret(PaymentSecret([0; 32]))
109			.duration_since_epoch(timestamp)
110			.min_final_cltv_expiry_delta(144)
111			.amount_milli_satoshis(128)
112			.build_signed(|hash| secp_ctx.sign_ecdsa_recoverable(hash, &private_key))
113			.unwrap();
114
115		assert!(payment_parameters_from_variable_amount_invoice(&invoice, 42).is_err());
116
117		let (hash, onion, params) = payment_parameters_from_invoice(&invoice).unwrap();
118		assert_eq!(&hash.0[..], &payment_hash[..]);
119		assert_eq!(onion.payment_secret, Some(PaymentSecret([0; 32])));
120		assert_eq!(params.final_value_msat, 128);
121		match params.payment_params.payee {
122			Payee::Clear { node_id, .. } => {
123				assert_eq!(node_id, public_key);
124			},
125			_ => panic!(),
126		}
127	}
128
129	#[test]
130	fn zero_value_invoice_test() {
131		let payment_hash = Sha256::hash(&[0; 32]);
132		let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
133		let secp_ctx = Secp256k1::new();
134		let public_key = PublicKey::from_secret_key(&secp_ctx, &private_key);
135
136		let timestamp = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
137		let invoice = InvoiceBuilder::new(Currency::Bitcoin)
138			.description("test".into())
139			.payment_hash(payment_hash)
140			.payment_secret(PaymentSecret([0; 32]))
141			.duration_since_epoch(timestamp)
142			.min_final_cltv_expiry_delta(144)
143			.build_signed(|hash| secp_ctx.sign_ecdsa_recoverable(hash, &private_key))
144			.unwrap();
145
146		assert!(payment_parameters_from_invoice(&invoice).is_err());
147
148		let (hash, onion, params) =
149			payment_parameters_from_variable_amount_invoice(&invoice, 42).unwrap();
150		assert_eq!(&hash.0[..], &payment_hash[..]);
151		assert_eq!(onion.payment_secret, Some(PaymentSecret([0; 32])));
152		assert_eq!(params.final_value_msat, 42);
153		match params.payment_params.payee {
154			Payee::Clear { node_id, .. } => {
155				assert_eq!(node_id, public_key);
156			},
157			_ => panic!(),
158		}
159	}
160
161	#[test]
162	fn payment_metadata_end_to_end() {
163		use crate::events::Event;
164		use crate::ln::channelmanager::{PaymentId, Retry};
165		use crate::ln::functional_test_utils::*;
166		use crate::ln::msgs::ChannelMessageHandler;
167
168		// Test that a payment metadata read from an invoice passed to `pay_invoice` makes it all
169		// the way out through the `PaymentClaimable` event.
170		let chanmon_cfgs = create_chanmon_cfgs(2);
171		let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
172		let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
173		let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
174		create_announced_chan_between_nodes(&nodes, 0, 1);
175
176		let payment_metadata = vec![42, 43, 44, 45, 46, 47, 48, 49, 42];
177
178		let (payment_hash, payment_secret) =
179			nodes[1].node.create_inbound_payment(None, 7200, None).unwrap();
180
181		let secp_ctx = Secp256k1::new();
182		let node_secret = nodes[1].keys_manager.backing.get_node_secret_key();
183		let timestamp = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
184		let invoice = InvoiceBuilder::new(Currency::Bitcoin)
185			.description("test".into())
186			.payment_hash(Sha256::from_slice(&payment_hash.0).unwrap())
187			.payment_secret(payment_secret)
188			.duration_since_epoch(timestamp)
189			.min_final_cltv_expiry_delta(144)
190			.amount_milli_satoshis(50_000)
191			.payment_metadata(payment_metadata.clone())
192			.build_signed(|hash| secp_ctx.sign_ecdsa_recoverable(hash, &node_secret))
193			.unwrap();
194
195		let (hash, onion, params) = payment_parameters_from_invoice(&invoice).unwrap();
196		nodes[0]
197			.node
198			.send_payment(hash, onion, PaymentId(hash.0), params, Retry::Attempts(0))
199			.unwrap();
200		check_added_monitors(&nodes[0], 1);
201		let send_event = SendEvent::from_node(&nodes[0]);
202		nodes[1].node.handle_update_add_htlc(nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
203		commitment_signed_dance!(nodes[1], nodes[0], &send_event.commitment_msg, false);
204
205		expect_pending_htlcs_forwardable!(nodes[1]);
206
207		let mut events = nodes[1].node.get_and_clear_pending_events();
208		assert_eq!(events.len(), 1);
209		match events.pop().unwrap() {
210			Event::PaymentClaimable { onion_fields, .. } => {
211				assert_eq!(Some(payment_metadata), onion_fields.unwrap().payment_metadata);
212			},
213			_ => panic!("Unexpected event"),
214		}
215	}
216}