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