@@ -28,6 +28,11 @@ use io::{self, Read};
28
28
use prelude:: * ;
29
29
use sync:: { Arc , Mutex } ;
30
30
31
+ // Per the spec, an onion message packet's `hop_data` field length should be
32
+ // SMALL_PACKET_HOP_DATA_LEN if it fits, else BIG_PACKET_HOP_DATA_LEN if it fits.
33
+ pub ( crate ) const SMALL_PACKET_HOP_DATA_LEN : usize = 1300 ;
34
+ pub ( crate ) const BIG_PACKET_HOP_DATA_LEN : usize = 32768 ;
35
+
31
36
#[ derive( Clone , Debug , PartialEq ) ]
32
37
pub ( crate ) struct Packet {
33
38
pub ( crate ) version : u8 ,
@@ -37,6 +42,13 @@ pub(crate) struct Packet {
37
42
pub ( crate ) hmac : [ u8 ; 32 ] ,
38
43
}
39
44
45
+ impl Packet {
46
+ fn len ( & self ) -> u16 {
47
+ // 32 (hmac) + 33 (public_key) + 1 (version) = 66
48
+ self . hop_data . len ( ) as u16 + 66
49
+ }
50
+ }
51
+
40
52
impl Writeable for Packet {
41
53
fn write < W : Writer > ( & self , w : & mut W ) -> Result < ( ) , io:: Error > {
42
54
self . version . write ( w) ?;
@@ -74,6 +86,59 @@ impl LengthReadable for Packet {
74
86
}
75
87
}
76
88
89
+ /// The payload of an onion message.
90
+ pub ( crate ) struct Payload {
91
+ /// Onion message payloads contain an encrypted TLV stream, containing both "control" TLVs and
92
+ /// sometimes user-provided custom "data" TLVs. See [`EncryptedTlvs`] for more information.
93
+ encrypted_tlvs : EncryptedTlvs ,
94
+ // Coming soon:
95
+ // * `message: Message` field
96
+ // * `reply_path: Option<BlindedRoute>` field
97
+ }
98
+
99
+ // Coming soon:
100
+ // enum Message {
101
+ // InvoiceRequest(InvoiceRequest),
102
+ // Invoice(Invoice),
103
+ // InvoiceError(InvoiceError),
104
+ // CustomMessage<T>,
105
+ // }
106
+
107
+ /// We want to avoid encoding and encrypting separately in order to avoid an intermediate Vec, thus
108
+ /// we encode and encrypt at the same time using the secret provided as the second parameter here.
109
+ impl Writeable for ( Payload , [ u8 ; 32 ] ) {
110
+ fn write < W : Writer > ( & self , w : & mut W ) -> Result < ( ) , io:: Error > {
111
+ match & self . 0 . encrypted_tlvs {
112
+ EncryptedTlvs :: Blinded ( encrypted_bytes) => {
113
+ encode_varint_length_prefixed_tlv ! ( w, {
114
+ ( 4 , encrypted_bytes, vec_type)
115
+ } )
116
+ } ,
117
+ EncryptedTlvs :: Unblinded ( control_tlvs) => {
118
+ let write_adapter = ChaChaPolyWriteAdapter :: new ( self . 1 , & control_tlvs) ;
119
+ encode_varint_length_prefixed_tlv ! ( w, {
120
+ ( 4 , write_adapter, required)
121
+ } )
122
+ }
123
+ }
124
+ Ok ( ( ) )
125
+ }
126
+ }
127
+
128
+ /// Onion messages contain an encrypted TLV stream. This can be supplied by someone else, in the
129
+ /// case that we're sending to a blinded route, or created by us if we're constructing payloads for
130
+ /// unblinded hops in the onion message's path.
131
+ pub ( crate ) enum EncryptedTlvs {
132
+ /// If we're sending to a blinded route, the node that constructed the blinded route has provided
133
+ /// our onion message's `EncryptedTlvs`, already encrypted and encoded into bytes.
134
+ Blinded ( Vec < u8 > ) ,
135
+ /// If we're receiving an onion message or constructing an onion message to send through any
136
+ /// unblinded nodes, we'll need to construct the onion message's `EncryptedTlvs` in their
137
+ /// unblinded state to avoid encoding them into an intermediate `Vec`.
138
+ // Below will later have an additional Vec<CustomTlv>
139
+ Unblinded ( ControlTlvs ) ,
140
+ }
141
+
77
142
/// Onion messages have "control" TLVs and "data" TLVs. Control TLVs are used to control the
78
143
/// direction and routing of an onion message from hop to hop, whereas data TLVs contain the onion
79
144
/// message content itself.
@@ -229,6 +294,23 @@ impl BlindedRoute {
229
294
}
230
295
}
231
296
297
+ /// The destination of an onion message.
298
+ pub enum Destination {
299
+ /// We're sending this onion message to a node.
300
+ Node ( PublicKey ) ,
301
+ /// We're sending this onion message to a blinded route.
302
+ BlindedRoute ( BlindedRoute ) ,
303
+ }
304
+
305
+ impl Destination {
306
+ fn num_hops ( & self ) -> usize {
307
+ match self {
308
+ Destination :: Node ( _) => 1 ,
309
+ Destination :: BlindedRoute ( BlindedRoute { blinded_hops, .. } ) => blinded_hops. len ( ) ,
310
+ }
311
+ }
312
+ }
313
+
232
314
/// A sender, receiver and forwarder of onion messages. In upcoming releases, this object will be
233
315
/// used to retrieve invoices and fulfill invoice requests from [offers].
234
316
///
@@ -262,6 +344,38 @@ impl<Signer: Sign, K: Deref, L: Deref> OnionMessenger<Signer, K, L>
262
344
logger,
263
345
}
264
346
}
347
+
348
+ /// Send an empty onion message to `destination`, routing it through `intermediate_nodes`.
349
+ pub fn send_onion_message ( & self , intermediate_nodes : Vec < PublicKey > , destination : Destination ) -> Result < ( ) , secp256k1:: Error > {
350
+ let blinding_secret_bytes = self . keys_manager . get_secure_random_bytes ( ) ;
351
+ let blinding_secret = SecretKey :: from_slice ( & blinding_secret_bytes[ ..] ) . expect ( "RNG is busted" ) ;
352
+ let ( introduction_node_id, blinding_point) = if intermediate_nodes. len ( ) != 0 {
353
+ ( intermediate_nodes[ 0 ] . clone ( ) , PublicKey :: from_secret_key ( & self . secp_ctx , & blinding_secret) )
354
+ } else {
355
+ match destination {
356
+ Destination :: Node ( pk) => ( pk. clone ( ) , PublicKey :: from_secret_key ( & self . secp_ctx , & blinding_secret) ) ,
357
+ Destination :: BlindedRoute ( BlindedRoute { introduction_node_id, blinding_point, .. } ) =>
358
+ ( introduction_node_id. clone ( ) , blinding_point. clone ( ) ) ,
359
+ }
360
+ } ;
361
+ let ( encrypted_data_keys, onion_packet_keys) = construct_sending_keys (
362
+ & self . secp_ctx , & intermediate_nodes, & destination, & blinding_secret) ?;
363
+ let payloads = build_payloads ( intermediate_nodes, destination, encrypted_data_keys) ;
364
+
365
+ let prng_seed = self . keys_manager . get_secure_random_bytes ( ) ;
366
+ let onion_packet = onion_utils:: construct_onion_message_packet ( payloads, onion_packet_keys, prng_seed) ;
367
+
368
+ let mut pending_msg_events = self . pending_msg_events . lock ( ) . unwrap ( ) ;
369
+ pending_msg_events. push ( MessageSendEvent :: SendOnionMessage {
370
+ node_id : introduction_node_id,
371
+ msg : msgs:: OnionMessage {
372
+ blinding_point,
373
+ len : onion_packet. len ( ) ,
374
+ onion_routing_packet : onion_packet,
375
+ }
376
+ } ) ;
377
+ Ok ( ( ) )
378
+ }
265
379
}
266
380
267
381
impl < Signer : Sign , K : Deref , L : Deref > OnionMessageHandler for OnionMessenger < Signer , K , L >
@@ -283,19 +397,69 @@ impl<Signer: Sign, K: Deref, L: Deref> MessageSendEventsProvider for OnionMessen
283
397
}
284
398
}
285
399
400
+ /// Build an onion message's payloads for encoding in the onion packet.
401
+ fn build_payloads ( intermediate_nodes : Vec < PublicKey > , destination : Destination , mut encrypted_tlvs_keys : Vec < [ u8 ; 32 ] > ) -> Vec < ( Payload , [ u8 ; 32 ] ) > {
402
+ let num_intermediate_nodes = intermediate_nodes. len ( ) ;
403
+ let num_payloads = num_intermediate_nodes + destination. num_hops ( ) ;
404
+ assert_eq ! ( encrypted_tlvs_keys. len( ) , num_payloads) ;
405
+ let mut payloads = Vec :: with_capacity ( num_payloads) ;
406
+ let mut enc_tlv_keys = encrypted_tlvs_keys. drain ( ..) ;
407
+ for pk in intermediate_nodes. into_iter ( ) . skip ( 1 ) {
408
+ payloads. push ( ( Payload {
409
+ encrypted_tlvs : EncryptedTlvs :: Unblinded ( ControlTlvs :: Forward {
410
+ next_node_id : pk,
411
+ next_blinding_override : None ,
412
+ } )
413
+ } , enc_tlv_keys. next ( ) . unwrap ( ) ) ) ;
414
+ }
415
+ match destination {
416
+ Destination :: Node ( pk) => {
417
+ if num_intermediate_nodes != 0 {
418
+ payloads. push ( ( Payload {
419
+ encrypted_tlvs : EncryptedTlvs :: Unblinded ( ControlTlvs :: Forward {
420
+ next_node_id : pk,
421
+ next_blinding_override : None ,
422
+ } )
423
+ } , enc_tlv_keys. next ( ) . unwrap ( ) ) ) ;
424
+ }
425
+ payloads. push ( ( Payload {
426
+ encrypted_tlvs : EncryptedTlvs :: Unblinded ( ControlTlvs :: Receive {
427
+ path_id : None ,
428
+ } )
429
+ } , enc_tlv_keys. next ( ) . unwrap ( ) ) ) ;
430
+ } ,
431
+ Destination :: BlindedRoute ( BlindedRoute { introduction_node_id, blinding_point, blinded_hops } ) => {
432
+ if num_intermediate_nodes != 0 {
433
+ payloads. push ( ( Payload {
434
+ encrypted_tlvs : EncryptedTlvs :: Unblinded ( ControlTlvs :: Forward {
435
+ next_node_id : introduction_node_id,
436
+ next_blinding_override : Some ( blinding_point) ,
437
+ } )
438
+ } , enc_tlv_keys. next ( ) . unwrap ( ) ) ) ;
439
+ }
440
+ for hop in blinded_hops {
441
+ payloads. push ( ( Payload {
442
+ encrypted_tlvs : EncryptedTlvs :: Blinded ( hop. encrypted_payload ) ,
443
+ } , enc_tlv_keys. next ( ) . unwrap ( ) ) ) ;
444
+ }
445
+ }
446
+ }
447
+ payloads
448
+ }
449
+
286
450
#[ inline]
287
451
fn construct_keys_callback <
288
452
T : secp256k1:: Signing + secp256k1:: Verification ,
289
453
FType : FnMut ( PublicKey , SharedSecret , [ u8 ; 32 ] , PublicKey , [ u8 ; 32 ] ) >
290
- ( secp_ctx : & Secp256k1 < T > , unblinded_path : & Vec < PublicKey > , session_priv : & SecretKey , mut callback : FType )
454
+ ( secp_ctx : & Secp256k1 < T > , unblinded_path : & Vec < PublicKey > , destination : Option < & Destination > , session_priv : & SecretKey , mut callback : FType )
291
455
-> Result < ( ) , secp256k1:: Error > {
292
456
let mut msg_blinding_point_priv = session_priv. clone ( ) ;
293
457
let mut msg_blinding_point = PublicKey :: from_secret_key ( secp_ctx, & msg_blinding_point_priv) ;
294
458
let mut onion_packet_pubkey_priv = msg_blinding_point_priv. clone ( ) ;
295
459
let mut onion_packet_pubkey = msg_blinding_point. clone ( ) ;
296
460
297
461
macro_rules! build_keys {
298
- ( $pk: expr, $blinded: expr) => {
462
+ ( $pk: expr, $blinded: expr) => { {
299
463
let encrypted_data_ss = SharedSecret :: new( & $pk, & msg_blinding_point_priv) ;
300
464
301
465
let hop_pk_blinding_factor = {
@@ -312,6 +476,13 @@ fn construct_keys_callback<
312
476
313
477
let ( rho, _) = onion_utils:: gen_rho_mu_from_shared_secret( encrypted_data_ss. as_ref( ) ) ;
314
478
callback( blinded_hop_pk, onion_packet_ss, hop_pk_blinding_factor, onion_packet_pubkey, rho) ;
479
+ ( encrypted_data_ss, onion_packet_ss)
480
+ } }
481
+ }
482
+
483
+ macro_rules! build_keys_in_loop {
484
+ ( $pk: expr, $blinded: expr) => {
485
+ let ( encrypted_data_ss, onion_packet_ss) = build_keys!( $pk, $blinded) ;
315
486
316
487
let msg_blinding_point_blinding_factor = {
317
488
let mut sha = Sha256 :: engine( ) ;
@@ -335,7 +506,19 @@ fn construct_keys_callback<
335
506
}
336
507
337
508
for pk in unblinded_path {
338
- build_keys ! ( pk, false ) ;
509
+ build_keys_in_loop ! ( pk, false ) ;
510
+ }
511
+ if let Some ( dest) = destination {
512
+ match dest {
513
+ Destination :: Node ( pk) => {
514
+ build_keys ! ( pk, false ) ;
515
+ } ,
516
+ Destination :: BlindedRoute ( BlindedRoute { blinded_hops, .. } ) => {
517
+ for hop in blinded_hops {
518
+ build_keys_in_loop ! ( hop. blinded_node_id, true ) ;
519
+ }
520
+ } ,
521
+ }
339
522
}
340
523
Ok ( ( ) )
341
524
}
@@ -351,14 +534,44 @@ fn construct_blinded_route_keys<T: secp256k1::Signing + secp256k1::Verification>
351
534
let mut encrypted_data_keys = Vec :: with_capacity ( unblinded_path. len ( ) ) ;
352
535
let mut blinded_node_pks = Vec :: with_capacity ( unblinded_path. len ( ) ) ;
353
536
354
- construct_keys_callback ( secp_ctx, unblinded_path, session_priv, |blinded_hop_pubkey, _, _, _, encrypted_data_ss| {
537
+ construct_keys_callback ( secp_ctx, unblinded_path, None , session_priv, |blinded_hop_pubkey, _, _, _, encrypted_data_ss| {
355
538
blinded_node_pks. push ( blinded_hop_pubkey) ;
356
539
encrypted_data_keys. push ( encrypted_data_ss) ;
357
540
} ) ?;
358
541
359
542
Ok ( ( encrypted_data_keys, blinded_node_pks) )
360
543
}
361
544
545
+ /// Construct keys for sending an onion message along the given `path`.
546
+ ///
547
+ /// Returns: `(encrypted_tlvs_keys, onion_packet_keys)`
548
+ /// where the encrypted tlvs keys are used to encrypt the [`EncryptedTlvs`] of the onion message and the
549
+ /// onion packet keys are used to encrypt the onion packet.
550
+ fn construct_sending_keys < T : secp256k1:: Signing + secp256k1:: Verification > (
551
+ secp_ctx : & Secp256k1 < T > , unblinded_path : & Vec < PublicKey > , destination : & Destination , session_priv : & SecretKey
552
+ ) -> Result < ( Vec < [ u8 ; 32 ] > , Vec < onion_utils:: OnionKeys > ) , secp256k1:: Error > {
553
+ let num_hops = unblinded_path. len ( ) + destination. num_hops ( ) ;
554
+ let mut encrypted_data_keys = Vec :: with_capacity ( num_hops) ;
555
+ let mut onion_packet_keys = Vec :: with_capacity ( num_hops) ;
556
+
557
+ construct_keys_callback ( secp_ctx, unblinded_path, Some ( destination) , session_priv, |_, onion_packet_ss, _blinding_factor, ephemeral_pubkey, encrypted_data_ss| {
558
+ encrypted_data_keys. push ( encrypted_data_ss) ;
559
+
560
+ let ( rho, mu) = onion_utils:: gen_rho_mu_from_shared_secret ( onion_packet_ss. as_ref ( ) ) ;
561
+ onion_packet_keys. push ( onion_utils:: OnionKeys {
562
+ #[ cfg( test) ]
563
+ shared_secret : onion_packet_ss,
564
+ #[ cfg( test) ]
565
+ blinding_factor : _blinding_factor,
566
+ ephemeral_pubkey,
567
+ rho,
568
+ mu,
569
+ } ) ;
570
+ } ) ?;
571
+
572
+ Ok ( ( encrypted_data_keys, onion_packet_keys) )
573
+ }
574
+
362
575
/// Useful for simplifying the parameters of [`SimpleArcChannelManager`] and
363
576
/// [`SimpleArcPeerManager`]. See their docs for more details.
364
577
///
0 commit comments