1 //! Convenient utilities to create an invoice.
3 use {Currency, DEFAULT_EXPIRY_TIME, Invoice, InvoiceBuilder, SignOrCreationError, RawInvoice};
4 use payment::{Payer, Router};
7 use bitcoin_hashes::Hash;
9 use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
10 use lightning::chain::keysinterface::{Sign, KeysInterface};
11 use lightning::ln::{PaymentHash, PaymentSecret};
12 use lightning::ln::channelmanager::{ChannelDetails, ChannelManager, PaymentId, PaymentSendFailure, MIN_FINAL_CLTV_EXPIRY};
13 use lightning::ln::msgs::LightningError;
14 use lightning::routing;
15 use lightning::routing::network_graph::{NetworkGraph, RoutingFees};
16 use lightning::routing::router::{Route, RouteHint, RouteHintHop, RouteParameters, find_route};
17 use lightning::util::logger::Logger;
18 use secp256k1::key::PublicKey;
19 use std::convert::TryInto;
22 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
23 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
24 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
25 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
26 /// that the payment secret is valid when the invoice is paid.
27 pub fn create_invoice_from_channelmanager<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
28 channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
29 amt_msat: Option<u64>, description: String
30 ) -> Result<Invoice, SignOrCreationError<()>>
32 M::Target: chain::Watch<Signer>,
33 T::Target: BroadcasterInterface,
34 K::Target: KeysInterface<Signer = Signer>,
35 F::Target: FeeEstimator,
38 // Marshall route hints.
39 let our_channels = channelmanager.list_usable_channels();
40 let mut route_hints = vec![];
41 for channel in our_channels {
42 let short_channel_id = match channel.short_channel_id {
46 let forwarding_info = match channel.counterparty.forwarding_info {
50 route_hints.push(RouteHint(vec![RouteHintHop {
51 src_node_id: channel.counterparty.node_id,
54 base_msat: forwarding_info.fee_base_msat,
55 proportional_millionths: forwarding_info.fee_proportional_millionths,
57 cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
58 htlc_minimum_msat: None,
59 htlc_maximum_msat: None,
63 let (payment_hash, payment_secret) = channelmanager.create_inbound_payment(
65 DEFAULT_EXPIRY_TIME.try_into().unwrap(),
68 let our_node_pubkey = channelmanager.get_our_node_id();
69 let mut invoice = InvoiceBuilder::new(network)
70 .description(description)
72 .payee_pub_key(our_node_pubkey)
73 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
74 .payment_secret(payment_secret)
76 .min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into());
77 if let Some(amt) = amt_msat {
78 invoice = invoice.amount_milli_satoshis(amt);
80 for hint in route_hints {
81 invoice = invoice.private_route(hint);
84 let raw_invoice = match invoice.build_raw() {
86 Err(e) => return Err(SignOrCreationError::CreationError(e))
88 let hrp_str = raw_invoice.hrp.to_string();
89 let hrp_bytes = hrp_str.as_bytes();
90 let data_without_signature = raw_invoice.data.to_base32();
91 let invoice_preimage = RawInvoice::construct_invoice_preimage(hrp_bytes, &data_without_signature);
92 let signed_raw_invoice = raw_invoice.sign(|_| keys_manager.sign_invoice(invoice_preimage));
93 match signed_raw_invoice {
94 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
95 Err(e) => Err(SignOrCreationError::SignError(e))
99 /// A [`Router`] implemented using [`find_route`].
100 pub struct DefaultRouter<G, L: Deref> where G: Deref<Target = NetworkGraph>, L::Target: Logger {
105 impl<G, L: Deref> DefaultRouter<G, L> where G: Deref<Target = NetworkGraph>, L::Target: Logger {
106 /// Creates a new router using the given [`NetworkGraph`] and [`Logger`].
107 pub fn new(network_graph: G, logger: L) -> Self {
108 Self { network_graph, logger }
112 impl<G, L: Deref, S: routing::Score> Router<S> for DefaultRouter<G, L>
113 where G: Deref<Target = NetworkGraph>, L::Target: Logger {
115 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&ChannelDetails]>,
117 ) -> Result<Route, LightningError> {
118 find_route(payer, params, &*self.network_graph, first_hops, &*self.logger, scorer)
122 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Payer for ChannelManager<Signer, M, T, K, F, L>
124 M::Target: chain::Watch<Signer>,
125 T::Target: BroadcasterInterface,
126 K::Target: KeysInterface<Signer = Signer>,
127 F::Target: FeeEstimator,
130 fn node_id(&self) -> PublicKey {
131 self.get_our_node_id()
134 fn first_hops(&self) -> Vec<ChannelDetails> {
135 self.list_usable_channels()
139 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
140 ) -> Result<PaymentId, PaymentSendFailure> {
141 self.send_payment(route, payment_hash, payment_secret)
145 &self, route: &Route, payment_id: PaymentId
146 ) -> Result<(), PaymentSendFailure> {
147 self.retry_payment(route, payment_id)
153 use {Currency, Description, InvoiceDescription};
154 use lightning::ln::PaymentHash;
155 use lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY;
156 use lightning::ln::functional_test_utils::*;
157 use lightning::ln::features::InitFeatures;
158 use lightning::ln::msgs::ChannelMessageHandler;
159 use lightning::routing::router::{Payee, RouteParameters, find_route};
160 use lightning::routing::scorer::Scorer;
161 use lightning::util::events::MessageSendEventsProvider;
162 use lightning::util::test_utils;
164 fn test_from_channelmanager() {
165 let chanmon_cfgs = create_chanmon_cfgs(2);
166 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
167 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
168 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
169 let _chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
170 let invoice = ::utils::create_invoice_from_channelmanager(&nodes[1].node, nodes[1].keys_manager, Currency::BitcoinTestnet, Some(10_000), "test".to_string()).unwrap();
171 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
172 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
173 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
175 let payee = Payee::new(invoice.recover_payee_pub_key())
176 .with_features(invoice.features().unwrap().clone())
177 .with_route_hints(invoice.route_hints());
178 let params = RouteParameters {
180 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
181 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
183 let first_hops = nodes[0].node.list_usable_channels();
184 let network_graph = node_cfgs[0].network_graph;
185 let logger = test_utils::TestLogger::new();
186 let scorer = Scorer::with_fixed_penalty(0);
187 let route = find_route(
188 &nodes[0].node.get_our_node_id(), ¶ms, network_graph,
189 Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer,
192 let payment_event = {
193 let mut payment_hash = PaymentHash([0; 32]);
194 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
195 nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
196 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
197 assert_eq!(added_monitors.len(), 1);
198 added_monitors.clear();
200 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
201 assert_eq!(events.len(), 1);
202 SendEvent::from_event(events.remove(0))
205 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
206 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
207 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
208 assert_eq!(added_monitors.len(), 1);
209 added_monitors.clear();
210 let events = nodes[1].node.get_and_clear_pending_msg_events();
211 assert_eq!(events.len(), 2);