KeysInterface::sign_invoice: indicate whether invoice is a phantom
[rust-lightning] / lightning-invoice / src / utils.rs
1 //! Convenient utilities to create an invoice.
2
3 use {CreationError, Currency, DEFAULT_EXPIRY_TIME, Invoice, InvoiceBuilder, SignOrCreationError};
4 use payment::{Payer, Router};
5
6 use bech32::ToBase32;
7 use bitcoin_hashes::Hash;
8 use crate::prelude::*;
9 use lightning::chain;
10 use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
11 use lightning::chain::keysinterface::{Recipient, KeysInterface, Sign};
12 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
13 use lightning::ln::channelmanager::{ChannelDetails, ChannelManager, PaymentId, PaymentSendFailure, MIN_FINAL_CLTV_EXPIRY};
14 use lightning::ln::msgs::LightningError;
15 use lightning::routing::scoring::Score;
16 use lightning::routing::network_graph::{NetworkGraph, RoutingFees};
17 use lightning::routing::router::{Route, RouteHint, RouteHintHop, RouteParameters, find_route};
18 use lightning::util::logger::Logger;
19 use secp256k1::key::PublicKey;
20 use core::convert::TryInto;
21 use core::ops::Deref;
22 use core::time::Duration;
23
24 #[cfg(feature = "std")]
25 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
26 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
27 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
28 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
29 /// that the payment secret is valid when the invoice is paid.
30 pub fn create_invoice_from_channelmanager<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
31         channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
32         amt_msat: Option<u64>, description: String
33 ) -> Result<Invoice, SignOrCreationError<()>>
34 where
35         M::Target: chain::Watch<Signer>,
36         T::Target: BroadcasterInterface,
37         K::Target: KeysInterface<Signer = Signer>,
38         F::Target: FeeEstimator,
39         L::Target: Logger,
40 {
41         use std::time::SystemTime;
42         let duration = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
43                 .expect("for the foreseeable future this shouldn't happen");
44         create_invoice_from_channelmanager_and_duration_since_epoch(
45                 channelmanager,
46                 keys_manager,
47                 network,
48                 amt_msat,
49                 description,
50                 duration
51         )
52 }
53
54 /// See [`create_invoice_from_channelmanager`]
55 /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
56 /// available and the current time is supplied by the caller.
57 pub fn create_invoice_from_channelmanager_and_duration_since_epoch<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
58         channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
59         amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
60 ) -> Result<Invoice, SignOrCreationError<()>>
61 where
62         M::Target: chain::Watch<Signer>,
63         T::Target: BroadcasterInterface,
64         K::Target: KeysInterface<Signer = Signer>,
65         F::Target: FeeEstimator,
66         L::Target: Logger,
67 {
68         // Marshall route hints.
69         let our_channels = channelmanager.list_usable_channels();
70         let mut route_hints = vec![];
71         for channel in our_channels {
72                 let short_channel_id = match channel.short_channel_id {
73                         Some(id) => id,
74                         None => continue,
75                 };
76                 let forwarding_info = match channel.counterparty.forwarding_info {
77                         Some(info) => info,
78                         None => continue,
79                 };
80                 route_hints.push(RouteHint(vec![RouteHintHop {
81                         src_node_id: channel.counterparty.node_id,
82                         short_channel_id,
83                         fees: RoutingFees {
84                                 base_msat: forwarding_info.fee_base_msat,
85                                 proportional_millionths: forwarding_info.fee_proportional_millionths,
86                         },
87                         cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
88                         htlc_minimum_msat: None,
89                         htlc_maximum_msat: None,
90                 }]));
91         }
92
93         // `create_inbound_payment` only returns an error if the amount is greater than the total bitcoin
94         // supply.
95         let (payment_hash, payment_secret) = channelmanager.create_inbound_payment(
96                 amt_msat, DEFAULT_EXPIRY_TIME.try_into().unwrap())
97                 .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
98         let our_node_pubkey = channelmanager.get_our_node_id();
99         let mut invoice = InvoiceBuilder::new(network)
100                 .description(description)
101                 .duration_since_epoch(duration_since_epoch)
102                 .payee_pub_key(our_node_pubkey)
103                 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
104                 .payment_secret(payment_secret)
105                 .basic_mpp()
106                 .min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into());
107         if let Some(amt) = amt_msat {
108                 invoice = invoice.amount_milli_satoshis(amt);
109         }
110         for hint in route_hints {
111                 invoice = invoice.private_route(hint);
112         }
113
114         let raw_invoice = match invoice.build_raw() {
115                 Ok(inv) => inv,
116                 Err(e) => return Err(SignOrCreationError::CreationError(e))
117         };
118         let hrp_str = raw_invoice.hrp.to_string();
119         let hrp_bytes = hrp_str.as_bytes();
120         let data_without_signature = raw_invoice.data.to_base32();
121         let signed_raw_invoice = raw_invoice.sign(|_| keys_manager.sign_invoice(hrp_bytes, &data_without_signature, Recipient::Node));
122         match signed_raw_invoice {
123                 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
124                 Err(e) => Err(SignOrCreationError::SignError(e))
125         }
126 }
127
128 /// A [`Router`] implemented using [`find_route`].
129 pub struct DefaultRouter<G: Deref<Target = NetworkGraph>, L: Deref> where L::Target: Logger {
130         network_graph: G,
131         logger: L,
132 }
133
134 impl<G: Deref<Target = NetworkGraph>, L: Deref> DefaultRouter<G, L> where L::Target: Logger {
135         /// Creates a new router using the given [`NetworkGraph`] and  [`Logger`].
136         pub fn new(network_graph: G, logger: L) -> Self {
137                 Self { network_graph, logger }
138         }
139 }
140
141 impl<G: Deref<Target = NetworkGraph>, L: Deref, S: Score> Router<S> for DefaultRouter<G, L>
142 where L::Target: Logger {
143         fn find_route(
144                 &self, payer: &PublicKey, params: &RouteParameters, _payment_hash: &PaymentHash,
145                 first_hops: Option<&[&ChannelDetails]>, scorer: &S
146         ) -> Result<Route, LightningError> {
147                 find_route(payer, params, &*self.network_graph, first_hops, &*self.logger, scorer)
148         }
149 }
150
151 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Payer for ChannelManager<Signer, M, T, K, F, L>
152 where
153         M::Target: chain::Watch<Signer>,
154         T::Target: BroadcasterInterface,
155         K::Target: KeysInterface<Signer = Signer>,
156         F::Target: FeeEstimator,
157         L::Target: Logger,
158 {
159         fn node_id(&self) -> PublicKey {
160                 self.get_our_node_id()
161         }
162
163         fn first_hops(&self) -> Vec<ChannelDetails> {
164                 self.list_usable_channels()
165         }
166
167         fn send_payment(
168                 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
169         ) -> Result<PaymentId, PaymentSendFailure> {
170                 self.send_payment(route, payment_hash, payment_secret)
171         }
172
173         fn send_spontaneous_payment(
174                 &self, route: &Route, payment_preimage: PaymentPreimage,
175         ) -> Result<PaymentId, PaymentSendFailure> {
176                 self.send_spontaneous_payment(route, Some(payment_preimage))
177                         .map(|(_, payment_id)| payment_id)
178         }
179
180         fn retry_payment(
181                 &self, route: &Route, payment_id: PaymentId
182         ) -> Result<(), PaymentSendFailure> {
183                 self.retry_payment(route, payment_id)
184         }
185
186         fn abandon_payment(&self, payment_id: PaymentId) {
187                 self.abandon_payment(payment_id)
188         }
189 }
190
191 #[cfg(test)]
192 mod test {
193         use core::time::Duration;
194         use {Currency, Description, InvoiceDescription};
195         use lightning::ln::PaymentHash;
196         use lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY;
197         use lightning::ln::functional_test_utils::*;
198         use lightning::ln::features::InitFeatures;
199         use lightning::ln::msgs::ChannelMessageHandler;
200         use lightning::routing::router::{PaymentParameters, RouteParameters, find_route};
201         use lightning::util::events::MessageSendEventsProvider;
202         use lightning::util::test_utils;
203         use utils::create_invoice_from_channelmanager_and_duration_since_epoch;
204
205         #[test]
206         fn test_from_channelmanager() {
207                 let chanmon_cfgs = create_chanmon_cfgs(2);
208                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
209                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
210                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
211                 let _chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
212                 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
213                         &nodes[1].node, nodes[1].keys_manager, Currency::BitcoinTestnet, Some(10_000), "test".to_string(),
214                         Duration::from_secs(1234567)).unwrap();
215                 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
216                 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
217                 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
218
219                 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
220                         .with_features(invoice.features().unwrap().clone())
221                         .with_route_hints(invoice.route_hints());
222                 let route_params = RouteParameters {
223                         payment_params,
224                         final_value_msat: invoice.amount_milli_satoshis().unwrap(),
225                         final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
226                 };
227                 let first_hops = nodes[0].node.list_usable_channels();
228                 let network_graph = node_cfgs[0].network_graph;
229                 let logger = test_utils::TestLogger::new();
230                 let scorer = test_utils::TestScorer::with_penalty(0);
231                 let route = find_route(
232                         &nodes[0].node.get_our_node_id(), &route_params, network_graph,
233                         Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer,
234                 ).unwrap();
235
236                 let payment_event = {
237                         let mut payment_hash = PaymentHash([0; 32]);
238                         payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
239                         nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
240                         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
241                         assert_eq!(added_monitors.len(), 1);
242                         added_monitors.clear();
243
244                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
245                         assert_eq!(events.len(), 1);
246                         SendEvent::from_event(events.remove(0))
247
248                 };
249                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
250                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
251                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
252                 assert_eq!(added_monitors.len(), 1);
253                 added_monitors.clear();
254                 let events = nodes[1].node.get_and_clear_pending_msg_events();
255                 assert_eq!(events.len(), 2);
256         }
257 }