Skip to content

Commit 9b379f3

Browse files
committed
Generalize CustomOnionMessageContents trait
Rename CustomOnionMessageContents to OnionMessageContents and use it as a trait bound on messages passed to OnionMessenger methods. This allows using the trait in an upcoming commit as a bound on the contents of PendingOnionMessage. Also, make ParsedOnionMessageContent have pub(super) visibility as it no longer needs to be exposed. It now implements OnionMessageContents so that Payload can be bounded by OnionMessageContents directly, but used when either reading a ParsedOnionMessageContent or writing a specific type of OnionMessageContents (e.g., OffersMessage).
1 parent e7c6cca commit 9b379f3

File tree

7 files changed

+93
-86
lines changed

7 files changed

+93
-86
lines changed

fuzz/src/onion_message.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use lightning::offers::invoice_request::UnsignedInvoiceRequest;
1414
use lightning::util::test_channel_signer::TestChannelSigner;
1515
use lightning::util::logger::Logger;
1616
use lightning::util::ser::{Readable, Writeable, Writer};
17-
use lightning::onion_message::{CustomOnionMessageContents, CustomOnionMessageHandler, Destination, MessageRouter, OffersMessage, OffersMessageHandler, OnionMessagePath, OnionMessenger};
17+
use lightning::onion_message::{CustomOnionMessageHandler, Destination, MessageRouter, OffersMessage, OffersMessageHandler, OnionMessageContents, OnionMessagePath, OnionMessenger};
1818

1919
use crate::utils::test_logger;
2020

@@ -84,7 +84,7 @@ struct TestCustomMessage {}
8484
const CUSTOM_MESSAGE_TYPE: u64 = 4242;
8585
const CUSTOM_MESSAGE_CONTENTS: [u8; 32] = [42; 32];
8686

87-
impl CustomOnionMessageContents for TestCustomMessage {
87+
impl OnionMessageContents for TestCustomMessage {
8888
fn tlv_type(&self) -> u64 {
8989
CUSTOM_MESSAGE_TYPE
9090
}

lightning/src/ln/peer_handler.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ use crate::util::ser::{VecWriter, Writeable, Writer};
2929
use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
3030
use crate::ln::wire;
3131
use crate::ln::wire::{Encode, Type};
32-
use crate::onion_message::{CustomOnionMessageContents, CustomOnionMessageHandler, OffersMessage, OffersMessageHandler, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
32+
use crate::onion_message::{CustomOnionMessageHandler, OffersMessage, OffersMessageHandler, OnionMessageContents, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
3333
use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, NodeAlias};
3434
use crate::util::atomic_counter::AtomicCounter;
3535
use crate::util::logger::Logger;
@@ -131,7 +131,7 @@ impl CustomOnionMessageHandler for IgnoringMessageHandler {
131131
}
132132
}
133133

134-
impl CustomOnionMessageContents for Infallible {
134+
impl OnionMessageContents for Infallible {
135135
fn tlv_type(&self) -> u64 { unreachable!(); }
136136
}
137137

lightning/src/onion_message/functional_tests.rs

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use crate::ln::msgs::{self, DecodeError, OnionMessageHandler};
1515
use crate::sign::{NodeSigner, Recipient};
1616
use crate::util::ser::{FixedLengthReader, LengthReadable, Writeable, Writer};
1717
use crate::util::test_utils;
18-
use super::{CustomOnionMessageContents, CustomOnionMessageHandler, Destination, MessageRouter, OffersMessage, OffersMessageHandler, ParsedOnionMessageContents, OnionMessagePath, OnionMessenger, SendError};
18+
use super::{CustomOnionMessageHandler, Destination, MessageRouter, OffersMessage, OffersMessageHandler, OnionMessageContents, OnionMessagePath, OnionMessenger, SendError};
1919

2020
use bitcoin::network::constants::Network;
2121
use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
@@ -77,7 +77,7 @@ const CUSTOM_RESPONSE_MESSAGE_TYPE: u64 = 4343;
7777
const CUSTOM_REQUEST_MESSAGE_CONTENTS: [u8; 32] = [42; 32];
7878
const CUSTOM_RESPONSE_MESSAGE_CONTENTS: [u8; 32] = [43; 32];
7979

80-
impl CustomOnionMessageContents for TestCustomMessage {
80+
impl OnionMessageContents for TestCustomMessage {
8181
fn tlv_type(&self) -> u64 {
8282
match self {
8383
TestCustomMessage::Request => CUSTOM_REQUEST_MESSAGE_TYPE,
@@ -196,7 +196,7 @@ fn pass_along_path(path: &Vec<MessengerNode>) {
196196
#[test]
197197
fn one_hop() {
198198
let nodes = create_nodes(2);
199-
let test_msg = ParsedOnionMessageContents::Custom(TestCustomMessage::Response);
199+
let test_msg = TestCustomMessage::Response;
200200

201201
let path = OnionMessagePath {
202202
intermediate_nodes: vec![],
@@ -210,7 +210,7 @@ fn one_hop() {
210210
#[test]
211211
fn two_unblinded_hops() {
212212
let nodes = create_nodes(3);
213-
let test_msg = ParsedOnionMessageContents::Custom(TestCustomMessage::Response);
213+
let test_msg = TestCustomMessage::Response;
214214

215215
let path = OnionMessagePath {
216216
intermediate_nodes: vec![nodes[1].get_node_pk()],
@@ -224,7 +224,7 @@ fn two_unblinded_hops() {
224224
#[test]
225225
fn two_unblinded_two_blinded() {
226226
let nodes = create_nodes(5);
227-
let test_msg = ParsedOnionMessageContents::Custom(TestCustomMessage::Response);
227+
let test_msg = TestCustomMessage::Response;
228228

229229
let secp_ctx = Secp256k1::new();
230230
let blinded_path = BlindedPath::new_for_message(&[nodes[3].get_node_pk(), nodes[4].get_node_pk()], &*nodes[4].keys_manager, &secp_ctx).unwrap();
@@ -241,7 +241,7 @@ fn two_unblinded_two_blinded() {
241241
#[test]
242242
fn three_blinded_hops() {
243243
let nodes = create_nodes(4);
244-
let test_msg = ParsedOnionMessageContents::Custom(TestCustomMessage::Response);
244+
let test_msg = TestCustomMessage::Response;
245245

246246
let secp_ctx = Secp256k1::new();
247247
let blinded_path = BlindedPath::new_for_message(&[nodes[1].get_node_pk(), nodes[2].get_node_pk(), nodes[3].get_node_pk()], &*nodes[3].keys_manager, &secp_ctx).unwrap();
@@ -259,7 +259,7 @@ fn three_blinded_hops() {
259259
fn too_big_packet_error() {
260260
// Make sure we error as expected if a packet is too big to send.
261261
let nodes = create_nodes(2);
262-
let test_msg = ParsedOnionMessageContents::Custom(TestCustomMessage::Response);
262+
let test_msg = TestCustomMessage::Response;
263263

264264
let hop_node_id = nodes[1].get_node_pk();
265265
let hops = vec![hop_node_id; 400];
@@ -285,7 +285,7 @@ fn we_are_intro_node() {
285285
destination: Destination::BlindedPath(blinded_path),
286286
};
287287

288-
nodes[0].messenger.send_onion_message(path, ParsedOnionMessageContents::Custom(test_msg.clone()), None).unwrap();
288+
nodes[0].messenger.send_onion_message(path, test_msg.clone(), None).unwrap();
289289
nodes[2].custom_message_handler.expect_message(TestCustomMessage::Response);
290290
pass_along_path(&nodes);
291291

@@ -295,7 +295,7 @@ fn we_are_intro_node() {
295295
intermediate_nodes: vec![],
296296
destination: Destination::BlindedPath(blinded_path),
297297
};
298-
nodes[0].messenger.send_onion_message(path, ParsedOnionMessageContents::Custom(test_msg), None).unwrap();
298+
nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
299299
nodes[1].custom_message_handler.expect_message(TestCustomMessage::Response);
300300
nodes.remove(2);
301301
pass_along_path(&nodes);
@@ -315,7 +315,7 @@ fn invalid_blinded_path_error() {
315315
intermediate_nodes: vec![],
316316
destination: Destination::BlindedPath(blinded_path),
317317
};
318-
let err = nodes[0].messenger.send_onion_message(path, ParsedOnionMessageContents::Custom(test_msg.clone()), None).unwrap_err();
318+
let err = nodes[0].messenger.send_onion_message(path, test_msg.clone(), None).unwrap_err();
319319
assert_eq!(err, SendError::TooFewBlindedHops);
320320

321321
// 1 hop
@@ -326,7 +326,7 @@ fn invalid_blinded_path_error() {
326326
intermediate_nodes: vec![],
327327
destination: Destination::BlindedPath(blinded_path),
328328
};
329-
let err = nodes[0].messenger.send_onion_message(path, ParsedOnionMessageContents::Custom(test_msg), None).unwrap_err();
329+
let err = nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap_err();
330330
assert_eq!(err, SendError::TooFewBlindedHops);
331331
}
332332

@@ -342,7 +342,7 @@ fn reply_path() {
342342
destination: Destination::Node(nodes[3].get_node_pk()),
343343
};
344344
let reply_path = BlindedPath::new_for_message(&[nodes[2].get_node_pk(), nodes[1].get_node_pk(), nodes[0].get_node_pk()], &*nodes[0].keys_manager, &secp_ctx).unwrap();
345-
nodes[0].messenger.send_onion_message(path, ParsedOnionMessageContents::Custom(test_msg.clone()), Some(reply_path)).unwrap();
345+
nodes[0].messenger.send_onion_message(path, test_msg.clone(), Some(reply_path)).unwrap();
346346
nodes[3].custom_message_handler.expect_message(TestCustomMessage::Request);
347347
pass_along_path(&nodes);
348348
// Make sure the last node successfully decoded the reply path.
@@ -358,7 +358,7 @@ fn reply_path() {
358358
};
359359
let reply_path = BlindedPath::new_for_message(&[nodes[2].get_node_pk(), nodes[1].get_node_pk(), nodes[0].get_node_pk()], &*nodes[0].keys_manager, &secp_ctx).unwrap();
360360

361-
nodes[0].messenger.send_onion_message(path, ParsedOnionMessageContents::Custom(test_msg), Some(reply_path)).unwrap();
361+
nodes[0].messenger.send_onion_message(path, test_msg, Some(reply_path)).unwrap();
362362
nodes[3].custom_message_handler.expect_message(TestCustomMessage::Request);
363363
pass_along_path(&nodes);
364364

@@ -373,7 +373,7 @@ fn invalid_custom_message_type() {
373373
let nodes = create_nodes(2);
374374

375375
struct InvalidCustomMessage{}
376-
impl CustomOnionMessageContents for InvalidCustomMessage {
376+
impl OnionMessageContents for InvalidCustomMessage {
377377
fn tlv_type(&self) -> u64 {
378378
// Onion message contents must have a TLV >= 64.
379379
63
@@ -384,7 +384,7 @@ fn invalid_custom_message_type() {
384384
fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> { unreachable!() }
385385
}
386386

387-
let test_msg = ParsedOnionMessageContents::Custom(InvalidCustomMessage {});
387+
let test_msg = InvalidCustomMessage {};
388388
let path = OnionMessagePath {
389389
intermediate_nodes: vec![],
390390
destination: Destination::Node(nodes[1].get_node_pk()),
@@ -402,9 +402,9 @@ fn peer_buffer_full() {
402402
destination: Destination::Node(nodes[1].get_node_pk()),
403403
};
404404
for _ in 0..188 { // Based on MAX_PER_PEER_BUFFER_SIZE in OnionMessenger
405-
nodes[0].messenger.send_onion_message(path.clone(), ParsedOnionMessageContents::Custom(test_msg.clone()), None).unwrap();
405+
nodes[0].messenger.send_onion_message(path.clone(), test_msg.clone(), None).unwrap();
406406
}
407-
let err = nodes[0].messenger.send_onion_message(path, ParsedOnionMessageContents::Custom(test_msg), None).unwrap_err();
407+
let err = nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap_err();
408408
assert_eq!(err, SendError::BufferFull);
409409
}
410410

@@ -425,7 +425,7 @@ fn many_hops() {
425425
intermediate_nodes,
426426
destination: Destination::Node(nodes[num_nodes-1].get_node_pk()),
427427
};
428-
nodes[0].messenger.send_onion_message(path, ParsedOnionMessageContents::Custom(test_msg), None).unwrap();
428+
nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
429429
nodes[num_nodes-1].custom_message_handler.expect_message(TestCustomMessage::Response);
430430
pass_along_path(&nodes);
431431
}

lightning/src/onion_message/messenger.rs

Lines changed: 48 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ use crate::ln::features::{InitFeatures, NodeFeatures};
2323
use crate::ln::msgs::{self, OnionMessageHandler};
2424
use crate::ln::onion_utils;
2525
use crate::ln::peer_handler::IgnoringMessageHandler;
26-
pub use super::packet::{CustomOnionMessageContents, ParsedOnionMessageContents};
26+
pub use super::packet::OnionMessageContents;
27+
use super::packet::ParsedOnionMessageContents;
2728
use super::offers::OffersMessageHandler;
2829
use super::packet::{BIG_PACKET_HOP_DATA_LEN, ForwardControlTlvs, Packet, Payload, ReceiveControlTlvs, SMALL_PACKET_HOP_DATA_LEN};
2930
use crate::util::logger::Logger;
@@ -60,7 +61,7 @@ use crate::prelude::*;
6061
/// # use lightning::blinded_path::BlindedPath;
6162
/// # use lightning::sign::KeysManager;
6263
/// # use lightning::ln::peer_handler::IgnoringMessageHandler;
63-
/// # use lightning::onion_message::{CustomOnionMessageContents, Destination, MessageRouter, ParsedOnionMessageContents, OnionMessagePath, OnionMessenger};
64+
/// # use lightning::onion_message::{OnionMessageContents, Destination, MessageRouter, OnionMessagePath, OnionMessenger};
6465
/// # use lightning::util::logger::{Logger, Record};
6566
/// # use lightning::util::ser::{Writeable, Writer};
6667
/// # use lightning::io;
@@ -101,7 +102,7 @@ use crate::prelude::*;
101102
/// // Write your custom onion message to `w`
102103
/// }
103104
/// }
104-
/// impl CustomOnionMessageContents for YourCustomMessage {
105+
/// impl OnionMessageContents for YourCustomMessage {
105106
/// fn tlv_type(&self) -> u64 {
106107
/// # let your_custom_message_type = 42;
107108
/// your_custom_message_type
@@ -113,8 +114,7 @@ use crate::prelude::*;
113114
/// destination: Destination::Node(destination_node_id),
114115
/// };
115116
/// let reply_path = None;
116-
/// # let your_custom_message = YourCustomMessage {};
117-
/// let message = ParsedOnionMessageContents::Custom(your_custom_message);
117+
/// # let message = YourCustomMessage {};
118118
/// onion_messenger.send_onion_message(path, message, reply_path);
119119
///
120120
/// // Create a blinded path to yourself, for someone to send an onion message to.
@@ -128,8 +128,7 @@ use crate::prelude::*;
128128
/// destination: Destination::BlindedPath(blinded_path),
129129
/// };
130130
/// let reply_path = None;
131-
/// # let your_custom_message = YourCustomMessage {};
132-
/// let message = ParsedOnionMessageContents::Custom(your_custom_message);
131+
/// # let message = YourCustomMessage {};
133132
/// onion_messenger.send_onion_message(path, message, reply_path);
134133
/// ```
135134
///
@@ -249,7 +248,7 @@ pub enum SendError {
249248
pub trait CustomOnionMessageHandler {
250249
/// The message known to the handler. To support multiple message types, you may want to make this
251250
/// an enum with a variant for each supported message.
252-
type CustomMessage: CustomOnionMessageContents;
251+
type CustomMessage: OnionMessageContents;
253252

254253
/// Called with the custom message that was received, returning a response to send, if any.
255254
fn handle_custom_message(&self, msg: Self::CustomMessage) -> Option<Self::CustomMessage>;
@@ -292,9 +291,8 @@ where
292291
/// Send an onion message with contents `message` to the destination of `path`.
293292
///
294293
/// See [`OnionMessenger`] for example usage.
295-
pub fn send_onion_message<T: CustomOnionMessageContents>(
296-
&self, path: OnionMessagePath, message: ParsedOnionMessageContents<T>,
297-
reply_path: Option<BlindedPath>
294+
pub fn send_onion_message<T: OnionMessageContents>(
295+
&self, path: OnionMessagePath, message: T, reply_path: Option<BlindedPath>
298296
) -> Result<(), SendError> {
299297
let OnionMessagePath { intermediate_nodes, mut destination } = path;
300298
if let Destination::BlindedPath(BlindedPath { ref blinded_hops, .. }) = destination {
@@ -348,9 +346,25 @@ where
348346
}
349347
}
350348

351-
fn find_path_and_enqueue_onion_message<T: CustomOnionMessageContents>(
352-
&self, contents: ParsedOnionMessageContents<T>, destination: Destination,
353-
log_suffix: fmt::Arguments
349+
fn handle_onion_message_response<T: OnionMessageContents>(
350+
&self, response: Option<T>, reply_path: Option<BlindedPath>, log_suffix: fmt::Arguments
351+
) {
352+
if let Some(response) = response {
353+
match reply_path {
354+
Some(reply_path) => {
355+
self.find_path_and_enqueue_onion_message(
356+
response, Destination::BlindedPath(reply_path), log_suffix
357+
);
358+
},
359+
None => {
360+
log_trace!(self.logger, "Missing reply path {}", log_suffix);
361+
},
362+
}
363+
}
364+
}
365+
366+
fn find_path_and_enqueue_onion_message<T: OnionMessageContents>(
367+
&self, contents: T, destination: Destination, log_suffix: fmt::Arguments
354368
) {
355369
let sender = match self.node_signer.get_node_id(Recipient::Node) {
356370
Ok(node_id) => node_id,
@@ -454,41 +468,32 @@ where
454468
onion_decode_ss, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac,
455469
(control_tlvs_ss, &*self.custom_handler, &*self.logger)
456470
) {
457-
Ok((Payload::Receive::<<<CMH as Deref>::Target as CustomOnionMessageHandler>::CustomMessage> {
471+
Ok((Payload::Receive::<ParsedOnionMessageContents<<<CMH as Deref>::Target as CustomOnionMessageHandler>::CustomMessage>> {
458472
message, control_tlvs: ReceiveControlTlvs::Unblinded(ReceiveTlvs { path_id }), reply_path,
459473
}, None)) => {
460474
log_trace!(self.logger,
461475
"Received an onion message with path_id {:02x?} and {} reply_path",
462476
path_id, if reply_path.is_some() { "a" } else { "no" });
463477

464-
let response = match message {
478+
match message {
465479
ParsedOnionMessageContents::Offers(msg) => {
466-
self.offers_handler.handle_message(msg)
467-
.map(|msg| ParsedOnionMessageContents::Offers(msg))
480+
let response = self.offers_handler.handle_message(msg);
481+
self.handle_onion_message_response(
482+
response, reply_path, format_args!(
483+
"when responding to Offers onion message with path_id {:02x?}",
484+
path_id
485+
)
486+
);
468487
},
469488
ParsedOnionMessageContents::Custom(msg) => {
470-
self.custom_handler.handle_custom_message(msg)
471-
.map(|msg| ParsedOnionMessageContents::Custom(msg))
472-
},
473-
};
474-
475-
if let Some(response) = response {
476-
match reply_path {
477-
Some(reply_path) => {
478-
self.find_path_and_enqueue_onion_message(
479-
response, Destination::BlindedPath(reply_path), format_args!(
480-
"when responding to onion message with path_id {:02x?}", path_id
481-
)
482-
);
483-
},
484-
None => {
485-
log_trace!(
486-
self.logger,
487-
"Missing reply path when responding to onion message with path_id {:02x?}",
489+
let response = self.custom_handler.handle_custom_message(msg);
490+
self.handle_onion_message_response(
491+
response, reply_path, format_args!(
492+
"when responding to Custom onion message with path_id {:02x?}",
488493
path_id
489-
);
490-
},
491-
}
494+
)
495+
);
496+
},
492497
}
493498
},
494499
Ok((Payload::Forward(ForwardControlTlvs::Unblinded(ForwardTlvs {
@@ -629,9 +634,9 @@ pub type SimpleRefOnionMessenger<'a, 'b, 'c, L> = OnionMessenger<
629634

630635
/// Construct onion packet payloads and keys for sending an onion message along the given
631636
/// `unblinded_path` to the given `destination`.
632-
fn packet_payloads_and_keys<T: CustomOnionMessageContents, S: secp256k1::Signing + secp256k1::Verification>(
633-
secp_ctx: &Secp256k1<S>, unblinded_path: &[PublicKey], destination: Destination,
634-
message: ParsedOnionMessageContents<T>, mut reply_path: Option<BlindedPath>, session_priv: &SecretKey
637+
fn packet_payloads_and_keys<T: OnionMessageContents, S: secp256k1::Signing + secp256k1::Verification>(
638+
secp_ctx: &Secp256k1<S>, unblinded_path: &[PublicKey], destination: Destination, message: T,
639+
mut reply_path: Option<BlindedPath>, session_priv: &SecretKey
635640
) -> Result<(Vec<(Payload<T>, [u8; 32])>, Vec<onion_utils::OnionKeys>), secp256k1::Error> {
636641
let num_hops = unblinded_path.len() + destination.num_hops();
637642
let mut payloads = Vec::with_capacity(num_hops);
@@ -707,7 +712,7 @@ fn packet_payloads_and_keys<T: CustomOnionMessageContents, S: secp256k1::Signing
707712
}
708713

709714
/// Errors if the serialized payload size exceeds onion_message::BIG_PACKET_HOP_DATA_LEN
710-
fn construct_onion_message_packet<T: CustomOnionMessageContents>(payloads: Vec<(Payload<T>, [u8; 32])>, onion_keys: Vec<onion_utils::OnionKeys>, prng_seed: [u8; 32]) -> Result<Packet, ()> {
715+
fn construct_onion_message_packet<T: OnionMessageContents>(payloads: Vec<(Payload<T>, [u8; 32])>, onion_keys: Vec<onion_utils::OnionKeys>, prng_seed: [u8; 32]) -> Result<Packet, ()> {
711716
// Spec rationale:
712717
// "`len` allows larger messages to be sent than the standard 1300 bytes allowed for an HTLC
713718
// onion, but this should be used sparingly as it is reduces anonymity set, hence the

lightning/src/onion_message/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,6 @@ mod packet;
2727
mod functional_tests;
2828

2929
// Re-export structs so they can be imported with just the `onion_message::` module prefix.
30-
pub use self::messenger::{CustomOnionMessageContents, CustomOnionMessageHandler, DefaultMessageRouter, Destination, MessageRouter, ParsedOnionMessageContents, OnionMessagePath, OnionMessenger, SendError, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
30+
pub use self::messenger::{CustomOnionMessageHandler, DefaultMessageRouter, Destination, MessageRouter, OnionMessageContents, OnionMessagePath, OnionMessenger, SendError, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
3131
pub use self::offers::{OffersMessage, OffersMessageHandler};
3232
pub(crate) use self::packet::{ControlTlvs, Packet};

0 commit comments

Comments
 (0)