Skip to content

Commit 2c4a6df

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 f7f5061 commit 2c4a6df

File tree

5 files changed

+341
-23
lines changed

5 files changed

+341
-23
lines changed

lightning-invoice/src/lib.rs

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

14951495
/// The supplied millisatoshi amount was greater than the total bitcoin supply.
14961496
InvalidAmount,
1497+
1498+
/// Route hints were required for this invoice and were missing. Applies to
1499+
/// [phantom invoices].
1500+
///
1501+
/// [phantom invoices]: crate::utils::create_phantom_invoice
1502+
MissingRouteHints,
1503+
1504+
/// For [phantom invoices], short channel ids for phantom route hints are supplied and used to
1505+
/// retrieve the phantom's private key. This can fail if an scid was not previously retrieved from
1506+
/// [`ChannelManager::get_phantom_scid`].
1507+
///
1508+
/// [phantom invoices]: crate::utils::create_phantom_invoice
1509+
/// [`ChannelManager::get_phantom_scid`]: lightning::ln::channelmanager::ChannelManager::get_phantom_scid
1510+
InvalidPhantomScid,
14971511
}
14981512

14991513
impl Display for CreationError {
@@ -1504,6 +1518,8 @@ impl Display for CreationError {
15041518
CreationError::TimestampOutOfBounds => f.write_str("The unix timestamp of the supplied date is <0 or can't be represented as `SystemTime`"),
15051519
CreationError::ExpiryTimeOutOfBounds => f.write_str("The supplied expiry time could cause an overflow if added to a `PositiveTimestamp`"),
15061520
CreationError::InvalidAmount => f.write_str("The supplied millisatoshi amount was greater than the total bitcoin supply"),
1521+
CreationError::MissingRouteHints => f.write_str("The invoice required route hints and they weren't provided"),
1522+
CreationError::InvalidPhantomScid => f.write_str("Failed to retrieve the phantom secret with the supplied phantom scid"),
15071523
}
15081524
}
15091525
}

lightning-invoice/src/utils.rs

Lines changed: 223 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,119 @@ use payment::{Payer, Router};
55

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

26+
#[cfg(feature = "std")]
27+
/// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice."
28+
/// This works because the invoice officially pays to a fake node (the "phantom"). Useful for
29+
/// load-balancing payments between multiple nodes.
30+
///
31+
/// `channels` contains a list of tuples of `(phantom_node_scid, real_node_pubkey,
32+
/// real_channel_details)`, where `phantom_node_scid` is unique to each `channels` entry and should
33+
/// be retrieved freshly for each new invoice from [`ChannelManager::get_phantom_scid`].
34+
/// `real_channel_details` comes from [`ChannelManager::list_channels`].
35+
///
36+
/// `payment_hash` and `payment_secret` come from [`ChannelManager::create_inbound_payment`] or
37+
/// [`ChannelManager::create_inbound_payment_for_hash`].
38+
///
39+
/// See [`KeysInterface::get_phantom_secret`] for more requirements on supporting phantom node
40+
/// payments.
41+
///
42+
/// [`KeysInterface::get_phantom_secret`]: lightning::chain::keysinterface::KeysInterface::get_phantom_secret
43+
pub fn create_phantom_invoice<Signer: Sign, K: Deref>(
44+
amt_msat: Option<u64>, description: String, payment_hash: PaymentHash, payment_secret:
45+
PaymentSecret, channels: &[(u64, PublicKey, &ChannelDetails)], keys_manager: K, network: Currency
46+
) -> Result<Invoice, SignOrCreationError<()>> where K::Target: KeysInterface {
47+
if channels.len() == 0 {
48+
return Err(SignOrCreationError::CreationError(CreationError::MissingRouteHints))
49+
}
50+
let phantom_secret = match keys_manager.get_phantom_secret(channels[0].0) {
51+
Ok(s) => s,
52+
Err(()) => return Err(SignOrCreationError::CreationError(CreationError::InvalidPhantomScid))
53+
};
54+
let mut route_hints = vec![];
55+
for (phantom_scid, real_node_pubkey, channel) in channels {
56+
let short_channel_id = match channel.short_channel_id {
57+
Some(id) => id,
58+
None => continue,
59+
};
60+
let forwarding_info = match &channel.counterparty.forwarding_info {
61+
Some(info) => info.clone(),
62+
None => continue,
63+
};
64+
route_hints.push(RouteHint(vec![
65+
RouteHintHop {
66+
src_node_id: channel.counterparty.node_id,
67+
short_channel_id,
68+
fees: RoutingFees {
69+
base_msat: forwarding_info.fee_base_msat,
70+
proportional_millionths: forwarding_info.fee_proportional_millionths,
71+
},
72+
cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
73+
htlc_minimum_msat: None,
74+
htlc_maximum_msat: None,
75+
},
76+
RouteHintHop {
77+
src_node_id: *real_node_pubkey,
78+
short_channel_id: *phantom_scid,
79+
fees: RoutingFees {
80+
base_msat: 0,
81+
proportional_millionths: 0,
82+
},
83+
cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
84+
htlc_minimum_msat: None,
85+
htlc_maximum_msat: None,
86+
}])
87+
);
88+
}
89+
let phantom_pubkey = PublicKey::from_secret_key(&Secp256k1::new(), &phantom_secret);
90+
let mut invoice = InvoiceBuilder::new(network)
91+
.description(description)
92+
.current_timestamp()
93+
.payee_pub_key(phantom_pubkey)
94+
.payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
95+
.payment_secret(payment_secret)
96+
.min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into());
97+
if let Some(amt) = amt_msat {
98+
invoice = invoice.amount_milli_satoshis(amt);
99+
}
100+
for hint in route_hints {
101+
invoice = invoice.private_route(hint);
102+
}
103+
104+
let raw_invoice = match invoice.build_raw() {
105+
Ok(inv) => inv,
106+
Err(e) => return Err(SignOrCreationError::CreationError(e))
107+
};
108+
let hrp_str = raw_invoice.hrp.to_string();
109+
let hrp_bytes = hrp_str.as_bytes();
110+
let data_without_signature = raw_invoice.data.to_base32();
111+
let invoice_preimage = RawInvoice::construct_invoice_preimage(hrp_bytes, &data_without_signature);
112+
let secp_ctx = Secp256k1::new();
113+
let invoice_preimage_msg = secp256k1::Message::from_slice(&Sha256::hash(&invoice_preimage)).unwrap();
114+
let signed_raw_invoice = raw_invoice.sign(|_| Ok(secp_ctx.sign_recoverable(&invoice_preimage_msg, &phantom_secret)));
115+
match signed_raw_invoice {
116+
Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
117+
Err(e) => Err(SignOrCreationError::SignError(e))
118+
}
119+
}
120+
24121
#[cfg(feature = "std")]
25122
/// Utility to construct an invoice. Generally, unless you want to do something like a custom
26123
/// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
@@ -193,15 +290,20 @@ where
193290
mod test {
194291
use core::time::Duration;
195292
use {Currency, Description, InvoiceDescription};
196-
use lightning::ln::PaymentHash;
197-
use lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY;
293+
use bitcoin_hashes::Hash;
294+
use bitcoin_hashes::sha256::Hash as Sha256;
295+
use lightning::chain::keysinterface::{KeysInterface, KeysManager};
296+
use lightning::ln::{PaymentPreimage, PaymentHash};
297+
use lightning::ln::channelmanager::{ChannelDetails, MIN_FINAL_CLTV_EXPIRY};
198298
use lightning::ln::functional_test_utils::*;
199299
use lightning::ln::features::InitFeatures;
200300
use lightning::ln::msgs::ChannelMessageHandler;
201301
use lightning::routing::router::{Payee, RouteParameters, find_route};
202-
use lightning::util::events::MessageSendEventsProvider;
302+
use lightning::util::enforcing_trait_impls::EnforcingSigner;
303+
use lightning::util::events::{MessageSendEvent, MessageSendEventsProvider, Event, PaymentPurpose};
203304
use lightning::util::test_utils;
204305
use utils::create_invoice_from_channelmanager_and_duration_since_epoch;
306+
use secp256k1::PublicKey;
205307

206308
#[test]
207309
fn test_from_channelmanager() {
@@ -255,4 +357,121 @@ mod test {
255357
let events = nodes[1].node.get_and_clear_pending_msg_events();
256358
assert_eq!(events.len(), 2);
257359
}
360+
361+
#[test]
362+
fn test_multi_node_receive() {
363+
do_test_multi_node_receive(true);
364+
do_test_multi_node_receive(false);
365+
}
366+
367+
fn do_test_multi_node_receive(user_generated_pmt_hash: bool) {
368+
let mut chanmon_cfgs = create_chanmon_cfgs(3);
369+
let seed = [42 as u8; 32];
370+
chanmon_cfgs[2].keys_manager.backing = KeysManager::new_multi_receive(&seed, 43, 44, chanmon_cfgs[1].keys_manager.get_inbound_payment_key_material());
371+
let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
372+
let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
373+
let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
374+
let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
375+
nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_0_1.1);
376+
nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_1.0);
377+
let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
378+
nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
379+
nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
380+
381+
let payment_amt = 10_000;
382+
let (payment_preimage, payment_hash, payment_secret) = {
383+
if user_generated_pmt_hash {
384+
let payment_preimage = PaymentPreimage([1; 32]);
385+
let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
386+
let payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(payment_amt), 3600).unwrap();
387+
(payment_preimage, payment_hash, payment_secret)
388+
} else {
389+
let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(payment_amt), 3600).unwrap();
390+
let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
391+
(payment_preimage, payment_hash, payment_secret)
392+
}
393+
};
394+
let channels_1 = nodes[1].node.list_channels();
395+
let channels_2 = nodes[2].node.list_channels();
396+
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)>>();
397+
for channel in channels_2.iter() {
398+
route_hints.push((nodes[2].node.get_phantom_scid(), nodes[2].node.get_our_node_id(), &channel));
399+
}
400+
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();
401+
402+
assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
403+
assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
404+
assert_eq!(invoice.route_hints().len(), 2);
405+
assert!(!invoice.features().unwrap().supports_basic_mpp());
406+
407+
let payee = Payee::from_node_id(invoice.recover_payee_pub_key())
408+
.with_features(invoice.features().unwrap().clone())
409+
.with_route_hints(invoice.route_hints());
410+
let params = RouteParameters {
411+
payee,
412+
final_value_msat: invoice.amount_milli_satoshis().unwrap(),
413+
final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
414+
};
415+
let first_hops = nodes[0].node.list_usable_channels();
416+
let network_graph = node_cfgs[0].network_graph;
417+
let logger = test_utils::TestLogger::new();
418+
let scorer = test_utils::TestScorer::with_fixed_penalty(0);
419+
let route = find_route(
420+
&nodes[0].node.get_our_node_id(), &params, network_graph,
421+
Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer,
422+
).unwrap();
423+
let payment_event = {
424+
let mut payment_hash = PaymentHash([0; 32]);
425+
payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
426+
nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
427+
let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
428+
assert_eq!(added_monitors.len(), 1);
429+
added_monitors.clear();
430+
431+
let mut events = nodes[0].node.get_and_clear_pending_msg_events();
432+
assert_eq!(events.len(), 1);
433+
SendEvent::from_event(events.remove(0))
434+
};
435+
nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
436+
commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
437+
expect_pending_htlcs_forwardable!(nodes[1]);
438+
let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) };
439+
let events = nodes[1].node.get_and_clear_pending_events();
440+
assert_eq!(events.len(), 2);
441+
match events[0] {
442+
Event::PendingHTLCsForwardable { .. } => { },
443+
_ => panic!("Unexpected event"),
444+
}
445+
match events[1] {
446+
Event::PaymentReceived { payment_hash: ref hash, ref purpose, amt } => {
447+
assert_eq!(*hash, payment_hash);
448+
assert_eq!(amt, payment_amt);
449+
match purpose {
450+
PaymentPurpose::InvoicePayment { payment_preimage, payment_secret: secret, .. } => {
451+
assert_eq!(*payment_preimage, payment_preimage_opt);
452+
assert_eq!(*secret, payment_secret);
453+
},
454+
_ => panic!("Unexpected payment purpose"),
455+
}
456+
},
457+
_ => panic!("Unexpected event"),
458+
}
459+
do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1])[..]), false, payment_preimage);
460+
let events = nodes[0].node.get_and_clear_pending_events();
461+
assert_eq!(events.len(), 2);
462+
match events[0] {
463+
Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
464+
assert_eq!(payment_preimage, *ev_preimage);
465+
assert_eq!(payment_hash, *ev_hash);
466+
assert_eq!(fee_paid_msat, &Some(0));
467+
},
468+
_ => panic!("Unexpected event")
469+
}
470+
match events[1] {
471+
Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
472+
assert_eq!(hash, Some(payment_hash));
473+
},
474+
_ => panic!("Unexpected event")
475+
}
476+
}
258477
}

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)