@@ -5,20 +5,116 @@ use payment::{Payer, Router};
55
66use bech32:: ToBase32 ;
77use bitcoin_hashes:: Hash ;
8+ use bitcoin_hashes:: sha256:: Hash as Sha256 ;
89use lightning:: chain;
910use lightning:: chain:: chaininterface:: { BroadcasterInterface , FeeEstimator } ;
1011use lightning:: chain:: keysinterface:: { Sign , KeysInterface } ;
1112use 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 } ;
1314use lightning:: ln:: msgs:: LightningError ;
1415use lightning:: routing:: scoring:: Score ;
1516use lightning:: routing:: network_graph:: { NetworkGraph , RoutingFees } ;
1617use lightning:: routing:: router:: { Route , RouteHint , RouteHintHop , RouteParameters , find_route} ;
1718use lightning:: util:: logger:: Logger ;
19+ use secp256k1:: Secp256k1 ;
1820use secp256k1:: key:: PublicKey ;
1921use std:: convert:: TryInto ;
2022use 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 ( fake_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: * fake_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 fake_node_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 ( fake_node_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 } ;
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,102 @@ 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+ expect_payment_received ! ( nodes[ 1 ] , payment_hash, payment_secret, payment_amt, payment_preimage_opt) ;
405+ do_claim_payment_along_route ( & nodes[ 0 ] , & vec ! ( & vec!( & nodes[ 1 ] ) [ ..] ) , false , payment_preimage) ;
406+ let events = nodes[ 0 ] . node . get_and_clear_pending_events ( ) ;
407+ assert_eq ! ( events. len( ) , 2 ) ;
408+ match events[ 0 ] {
409+ Event :: PaymentSent { payment_preimage : ref ev_preimage, payment_hash : ref ev_hash, ref fee_paid_msat, .. } => {
410+ assert_eq ! ( payment_preimage, * ev_preimage) ;
411+ assert_eq ! ( payment_hash, * ev_hash) ;
412+ assert_eq ! ( fee_paid_msat, & Some ( 0 ) ) ;
413+ } ,
414+ _ => panic ! ( "Unexpected event" )
415+ }
416+ match events[ 1 ] {
417+ Event :: PaymentPathSuccessful { payment_hash : hash, .. } => {
418+ assert_eq ! ( hash, Some ( payment_hash) ) ;
419+ } ,
420+ _ => panic ! ( "Unexpected event" )
421+ }
422+ }
223423}
0 commit comments