@@ -5,22 +5,119 @@ use payment::{Payer, Router};
5
5
6
6
use bech32:: ToBase32 ;
7
7
use bitcoin_hashes:: Hash ;
8
+ use bitcoin_hashes:: sha256:: Hash as Sha256 ;
8
9
use crate :: prelude:: * ;
9
10
use lightning:: chain;
10
11
use lightning:: chain:: chaininterface:: { BroadcasterInterface , FeeEstimator } ;
11
12
use lightning:: chain:: keysinterface:: { Sign , KeysInterface } ;
12
13
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 } ;
14
15
use lightning:: ln:: msgs:: LightningError ;
15
16
use lightning:: routing:: scoring:: Score ;
16
17
use lightning:: routing:: network_graph:: { NetworkGraph , RoutingFees } ;
17
18
use lightning:: routing:: router:: { Route , RouteHint , RouteHintHop , RouteParameters , find_route} ;
18
19
use lightning:: util:: logger:: Logger ;
20
+ use secp256k1:: Secp256k1 ;
19
21
use secp256k1:: key:: PublicKey ;
20
22
use core:: convert:: TryInto ;
21
23
use core:: ops:: Deref ;
22
24
use core:: time:: Duration ;
23
25
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
+
24
121
#[ cfg( feature = "std" ) ]
25
122
/// Utility to construct an invoice. Generally, unless you want to do something like a custom
26
123
/// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
@@ -193,15 +290,20 @@ where
193
290
mod test {
194
291
use core:: time:: Duration ;
195
292
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 } ;
198
298
use lightning:: ln:: functional_test_utils:: * ;
199
299
use lightning:: ln:: features:: InitFeatures ;
200
300
use lightning:: ln:: msgs:: ChannelMessageHandler ;
201
301
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 } ;
203
304
use lightning:: util:: test_utils;
204
305
use utils:: create_invoice_from_channelmanager_and_duration_since_epoch;
306
+ use secp256k1:: PublicKey ;
205
307
206
308
#[ test]
207
309
fn test_from_channelmanager ( ) {
@@ -255,4 +357,121 @@ mod test {
255
357
let events = nodes[ 1 ] . node . get_and_clear_pending_msg_events ( ) ;
256
358
assert_eq ! ( events. len( ) , 2 ) ;
257
359
}
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
+ }
258
477
}
0 commit comments