Skip to content

Commit 980b1c9

Browse files
Support multi-node receive in ChannelManager, with invoice util
See get_phantom_scid and invoice util's create_phantom_invoice for more info
1 parent 8d27abc commit 980b1c9

File tree

5 files changed

+342
-24
lines changed

5 files changed

+342
-24
lines changed

lightning-invoice/src/lib.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1416,6 +1416,20 @@ pub enum CreationError {
14161416

14171417
/// The supplied millisatoshi amount was greater than the total bitcoin supply.
14181418
InvalidAmount,
1419+
1420+
/// Route hints were required for this invoice and were missing. Applies to
1421+
/// [phantom invoices].
1422+
///
1423+
/// [phantom invoices]: crate::utils::create_phantom_invoice
1424+
MissingRouteHints,
1425+
1426+
/// For [phantom invoices], short channel ids for phantom route hints are supplied and used to
1427+
/// retrieve the phantom's private key. This can fail if an scid was not previously retrieved from
1428+
/// [`ChannelManager::get_phantom_scid`].
1429+
///
1430+
/// [phantom invoices]: crate::utils::create_phantom_invoice
1431+
/// [`ChannelManager::get_phantom_scid`]: lightning::ln::channelmanager::ChannelManager::get_phantom_scid
1432+
InvalidPhantomScid,
14191433
}
14201434

14211435
impl Display for CreationError {
@@ -1426,6 +1440,8 @@ impl Display for CreationError {
14261440
CreationError::TimestampOutOfBounds => f.write_str("The unix timestamp of the supplied date is <0 or can't be represented as `SystemTime`"),
14271441
CreationError::ExpiryTimeOutOfBounds => f.write_str("The supplied expiry time could cause an overflow if added to a `PositiveTimestamp`"),
14281442
CreationError::InvalidAmount => f.write_str("The supplied millisatoshi amount was greater than the total bitcoin supply"),
1443+
CreationError::MissingRouteHints => f.write_str("The invoice required route hints and they weren't provided"),
1444+
CreationError::InvalidPhantomScid => f.write_str("Failed to retrieve the phantom secret with the supplied phantom scid"),
14291445
}
14301446
}
14311447
}

lightning-invoice/src/utils.rs

Lines changed: 224 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,116 @@ use payment::{Payer, Router};
55

66
use bech32::ToBase32;
77
use bitcoin_hashes::Hash;
8+
use bitcoin_hashes::sha256::Hash as Sha256;
89
use lightning::chain;
910
use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
1011
use lightning::chain::keysinterface::{Sign, KeysInterface};
1112
use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
12-
use lightning::ln::channelmanager::{ChannelDetails, ChannelManager, PaymentId, PaymentSendFailure, MIN_FINAL_CLTV_EXPIRY};
13+
use lightning::ln::channelmanager::{ChannelDetails, ChannelManager, PaymentId, PaymentSendFailure, MIN_FINAL_CLTV_EXPIRY, MIN_CLTV_EXPIRY_DELTA};
1314
use lightning::ln::msgs::LightningError;
1415
use lightning::routing::scoring::Score;
1516
use lightning::routing::network_graph::{NetworkGraph, RoutingFees};
1617
use lightning::routing::router::{Route, RouteHint, RouteHintHop, RouteParameters, find_route};
1718
use lightning::util::logger::Logger;
19+
use secp256k1::Secp256k1;
1820
use secp256k1::key::PublicKey;
1921
use std::convert::TryInto;
2022
use std::ops::Deref;
2123

24+
/// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice."
25+
/// This works because the invoice officially pays to a fake node (the "phantom"). Useful for
26+
/// load-balancing payments between multiple nodes.
27+
///
28+
/// `channels` contains a list of tuples of `(phantom_node_scid, real_node_pubkey,
29+
/// real_channel_details)`, where `phantom_node_scid` is unique to each `channels` entry and should
30+
/// be retrieved freshly for each new invoice from [`ChannelManager::get_phantom_scid`].
31+
/// `real_channel_details` comes from [`ChannelManager::list_channels`].
32+
///
33+
/// `payment_hash` and `payment_secret` come from [`ChannelManager::create_inbound_payment`] or
34+
/// [`ChannelManager::create_inbound_payment_for_hash`].
35+
///
36+
/// See [`KeysInterface::get_phantom_secret`] for more requirements on supporting phantom node
37+
/// payments.
38+
///
39+
/// [`KeysInterface::get_phantom_secret`]: lightning::chain::keysinterface::KeysInterface::get_phantom_secret
40+
pub fn create_phantom_invoice<Signer: Sign, K: Deref>(
41+
amt_msat: Option<u64>, description: String, payment_hash: PaymentHash, payment_secret:
42+
PaymentSecret, channels: &[(u64, PublicKey, &ChannelDetails)], keys_manager: K, network: Currency
43+
) -> Result<Invoice, SignOrCreationError<()>> where K::Target: KeysInterface {
44+
if channels.len() == 0 {
45+
return Err(SignOrCreationError::CreationError(CreationError::MissingRouteHints))
46+
}
47+
let phantom_secret = match keys_manager.get_phantom_secret(channels[0].0) {
48+
Ok(s) => s,
49+
Err(()) => return Err(SignOrCreationError::CreationError(CreationError::InvalidPhantomScid))
50+
};
51+
let mut route_hints = vec![];
52+
for (phantom_scid, real_node_pubkey, channel) in channels {
53+
let short_channel_id = match channel.short_channel_id {
54+
Some(id) => id,
55+
None => continue,
56+
};
57+
let forwarding_info = match &channel.counterparty.forwarding_info {
58+
Some(info) => info.clone(),
59+
None => continue,
60+
};
61+
route_hints.push(RouteHint(vec![
62+
RouteHintHop {
63+
src_node_id: channel.counterparty.node_id,
64+
short_channel_id,
65+
fees: RoutingFees {
66+
base_msat: forwarding_info.fee_base_msat,
67+
proportional_millionths: forwarding_info.fee_proportional_millionths,
68+
},
69+
cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
70+
htlc_minimum_msat: None,
71+
htlc_maximum_msat: None,
72+
},
73+
RouteHintHop {
74+
src_node_id: *real_node_pubkey,
75+
short_channel_id: *phantom_scid,
76+
fees: RoutingFees {
77+
base_msat: 0,
78+
proportional_millionths: 0,
79+
},
80+
cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
81+
htlc_minimum_msat: None,
82+
htlc_maximum_msat: None,
83+
}])
84+
);
85+
}
86+
let phantom_pubkey = PublicKey::from_secret_key(&Secp256k1::new(), &phantom_secret);
87+
let mut invoice = InvoiceBuilder::new(network)
88+
.description(description)
89+
.current_timestamp()
90+
.payee_pub_key(phantom_pubkey)
91+
.payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
92+
.payment_secret(payment_secret)
93+
.min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into());
94+
if let Some(amt) = amt_msat {
95+
invoice = invoice.amount_milli_satoshis(amt);
96+
}
97+
for hint in route_hints {
98+
invoice = invoice.private_route(hint);
99+
}
100+
101+
let raw_invoice = match invoice.build_raw() {
102+
Ok(inv) => inv,
103+
Err(e) => return Err(SignOrCreationError::CreationError(e))
104+
};
105+
let hrp_str = raw_invoice.hrp.to_string();
106+
let hrp_bytes = hrp_str.as_bytes();
107+
let data_without_signature = raw_invoice.data.to_base32();
108+
let invoice_preimage = RawInvoice::construct_invoice_preimage(hrp_bytes, &data_without_signature);
109+
let secp_ctx = Secp256k1::new();
110+
let invoice_preimage_msg = secp256k1::Message::from_slice(&Sha256::hash(&invoice_preimage)).unwrap();
111+
let signed_raw_invoice = raw_invoice.sign(|_| Ok(secp_ctx.sign_recoverable(&invoice_preimage_msg, &phantom_secret)));
112+
match signed_raw_invoice {
113+
Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
114+
Err(e) => Err(SignOrCreationError::SignError(e))
115+
}
116+
}
117+
22118
/// Utility to construct an invoice. Generally, unless you want to do something like a custom
23119
/// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
24120
/// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
@@ -160,16 +256,22 @@ where
160256
}
161257

162258
#[cfg(test)]
163-
mod test {
259+
mod tests {
164260
use {Currency, Description, InvoiceDescription};
165-
use lightning::ln::PaymentHash;
166-
use lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY;
261+
use bitcoin_hashes::Hash;
262+
use bitcoin_hashes::sha256::Hash as Sha256;
263+
use lightning::chain::keysinterface::{KeysInterface, KeysManager};
264+
use lightning::ln::{PaymentPreimage, PaymentHash};
265+
use lightning::ln::channelmanager::{ChannelDetails, MIN_FINAL_CLTV_EXPIRY};
167266
use lightning::ln::functional_test_utils::*;
168267
use lightning::ln::features::InitFeatures;
169268
use lightning::ln::msgs::ChannelMessageHandler;
170269
use lightning::routing::router::{Payee, RouteParameters, find_route};
171-
use lightning::util::events::MessageSendEventsProvider;
270+
use lightning::util::enforcing_trait_impls::EnforcingSigner;
271+
use lightning::util::events::{MessageSendEvent, MessageSendEventsProvider, Event, PaymentPurpose};
172272
use lightning::util::test_utils;
273+
use secp256k1::PublicKey;
274+
173275
#[test]
174276
fn test_from_channelmanager() {
175277
let chanmon_cfgs = create_chanmon_cfgs(2);
@@ -220,4 +322,121 @@ mod test {
220322
let events = nodes[1].node.get_and_clear_pending_msg_events();
221323
assert_eq!(events.len(), 2);
222324
}
325+
326+
#[test]
327+
fn test_multi_node_receive() {
328+
do_test_multi_node_receive(true);
329+
do_test_multi_node_receive(false);
330+
}
331+
332+
fn do_test_multi_node_receive(user_generated_pmt_hash: bool) {
333+
let mut chanmon_cfgs = create_chanmon_cfgs(3);
334+
let seed = [42 as u8; 32];
335+
chanmon_cfgs[2].keys_manager.backing = KeysManager::new_multi_receive(&seed, 43, 44, chanmon_cfgs[1].keys_manager.get_inbound_payment_key_material());
336+
let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
337+
let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
338+
let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
339+
let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
340+
nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_0_1.1);
341+
nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_1.0);
342+
let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
343+
nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
344+
nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
345+
346+
let payment_amt = 10_000;
347+
let (payment_preimage, payment_hash, payment_secret) = {
348+
if user_generated_pmt_hash {
349+
let payment_preimage = PaymentPreimage([1; 32]);
350+
let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
351+
let payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(payment_amt), 3600).unwrap();
352+
(payment_preimage, payment_hash, payment_secret)
353+
} else {
354+
let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(payment_amt), 3600).unwrap();
355+
let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
356+
(payment_preimage, payment_hash, payment_secret)
357+
}
358+
};
359+
let channels_1 = nodes[1].node.list_channels();
360+
let channels_2 = nodes[2].node.list_channels();
361+
let mut route_hints = channels_1.iter().map(|e| (nodes[1].node.get_phantom_scid(), nodes[1].node.get_our_node_id(), e)).collect::<Vec<(u64, PublicKey, &ChannelDetails)>>();
362+
for channel in channels_2.iter() {
363+
route_hints.push((nodes[2].node.get_phantom_scid(), nodes[2].node.get_our_node_id(), &channel));
364+
}
365+
let invoice = ::utils::create_phantom_invoice::<EnforcingSigner, &test_utils::TestKeysInterface>(Some(payment_amt), "test".to_string(), payment_hash, payment_secret, &route_hints, &nodes[1].keys_manager, Currency::BitcoinTestnet).unwrap();
366+
367+
assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
368+
assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
369+
assert_eq!(invoice.route_hints().len(), 2);
370+
assert!(!invoice.features().unwrap().supports_basic_mpp());
371+
372+
let payee = Payee::from_node_id(invoice.recover_payee_pub_key())
373+
.with_features(invoice.features().unwrap().clone())
374+
.with_route_hints(invoice.route_hints());
375+
let params = RouteParameters {
376+
payee,
377+
final_value_msat: invoice.amount_milli_satoshis().unwrap(),
378+
final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
379+
};
380+
let first_hops = nodes[0].node.list_usable_channels();
381+
let network_graph = node_cfgs[0].network_graph;
382+
let logger = test_utils::TestLogger::new();
383+
let scorer = test_utils::TestScorer::with_fixed_penalty(0);
384+
let route = find_route(
385+
&nodes[0].node.get_our_node_id(), &params, network_graph,
386+
Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer,
387+
).unwrap();
388+
let payment_event = {
389+
let mut payment_hash = PaymentHash([0; 32]);
390+
payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
391+
nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
392+
let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
393+
assert_eq!(added_monitors.len(), 1);
394+
added_monitors.clear();
395+
396+
let mut events = nodes[0].node.get_and_clear_pending_msg_events();
397+
assert_eq!(events.len(), 1);
398+
SendEvent::from_event(events.remove(0))
399+
};
400+
nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
401+
commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
402+
expect_pending_htlcs_forwardable!(nodes[1]);
403+
let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) };
404+
let events = nodes[1].node.get_and_clear_pending_events();
405+
assert_eq!(events.len(), 2);
406+
match events[0] {
407+
Event::PendingHTLCsForwardable { .. } => { },
408+
_ => panic!("Unexpected event"),
409+
}
410+
match events[1] {
411+
Event::PaymentReceived { payment_hash: ref hash, ref purpose, amt } => {
412+
assert_eq!(*hash, payment_hash);
413+
assert_eq!(amt, payment_amt);
414+
match purpose {
415+
PaymentPurpose::InvoicePayment { payment_preimage, payment_secret: secret, .. } => {
416+
assert_eq!(*payment_preimage, payment_preimage_opt);
417+
assert_eq!(*secret, payment_secret);
418+
},
419+
_ => panic!("Unexpected payment purpose"),
420+
}
421+
},
422+
_ => panic!("Unexpected event"),
423+
}
424+
do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1])[..]), false, payment_preimage);
425+
let events = nodes[0].node.get_and_clear_pending_events();
426+
assert_eq!(events.len(), 2);
427+
match events[0] {
428+
Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
429+
assert_eq!(payment_preimage, *ev_preimage);
430+
assert_eq!(payment_hash, *ev_hash);
431+
assert_eq!(fee_paid_msat, &Some(0));
432+
},
433+
_ => panic!("Unexpected event")
434+
}
435+
match events[1] {
436+
Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
437+
assert_eq!(hash, Some(payment_hash));
438+
},
439+
_ => panic!("Unexpected event")
440+
}
441+
}
223442
}

lightning/src/chain/keysinterface.rs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -407,10 +407,27 @@ pub trait KeysInterface {
407407

408408
/// Get secret key material as bytes for use in encrypting and decrypting inbound payment data.
409409
///
410+
/// If the implementor of this trait supports [phantom node payments], then every node that is
411+
/// intended to be included in the phantom invoice(s) route hints must return the same value from
412+
/// this method.
413+
///
410414
/// This method must return the same value each time it is called.
415+
///
416+
///[phantom node payments]: crate::ln::channelmanager::ChannelManager::get_phantom_scid
411417
fn get_inbound_payment_key_material(&self) -> KeyMaterial;
412418

413-
/// Get a secret key for use in receiving phantom node payments.
419+
/// Get the phantom node secret key for use in receiving a [phantom node payment].
420+
///
421+
/// Must return the same value for all `scid`s in a given phantom invoice's route hints.
422+
///
423+
/// Note that if you are using [`KeysManager`], every additional LDK node after the first one must
424+
/// use [`KeysManager::new_multi_receive`] to initialize its `KeysManager` or payments will fail to
425+
/// be received.
426+
///
427+
/// See [`KeysInterface::get_inbound_payment_key_material`] for further requirements on nodes
428+
/// supporting phantom node payments.
429+
///
430+
///[phantom node payment]: crate::ln::channelmanager::ChannelManager::get_phantom_scid
414431
fn get_phantom_secret(&self, scid: u64) -> Result<SecretKey, ()>;
415432
}
416433

0 commit comments

Comments
 (0)