Skip to content

Commit aab3970

Browse files
committed
Destination in OnionMessenger::send_onion_message
OnionMessenger::send_onion_message takes an OnionMessagePath. This isn't very useful as it requires finding a path manually. Instead, have the method take a Destination and use OnionMessenger's MessageRouter to construct the path. Later, this will allow for buffering messages where the first node in the path isn't a direct connection.
1 parent 7609abe commit aab3970

File tree

2 files changed

+73
-49
lines changed

2 files changed

+73
-49
lines changed

lightning/src/onion_message/functional_tests.rs

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ fn one_unblinded_hop() {
205205
intermediate_nodes: vec![],
206206
destination: Destination::Node(nodes[1].get_node_pk()),
207207
};
208-
nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
208+
nodes[0].messenger.send_onion_message_using_path(path, test_msg, None).unwrap();
209209
nodes[1].custom_message_handler.expect_message(TestCustomMessage::Response);
210210
pass_along_path(&nodes);
211211
}
@@ -219,7 +219,7 @@ fn two_unblinded_hops() {
219219
intermediate_nodes: vec![nodes[1].get_node_pk()],
220220
destination: Destination::Node(nodes[2].get_node_pk()),
221221
};
222-
nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
222+
nodes[0].messenger.send_onion_message_using_path(path, test_msg, None).unwrap();
223223
nodes[2].custom_message_handler.expect_message(TestCustomMessage::Response);
224224
pass_along_path(&nodes);
225225
}
@@ -235,7 +235,7 @@ fn one_blinded_hop() {
235235
intermediate_nodes: vec![],
236236
destination: Destination::BlindedPath(blinded_path),
237237
};
238-
nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
238+
nodes[0].messenger.send_onion_message_using_path(path, test_msg, None).unwrap();
239239
nodes[1].custom_message_handler.expect_message(TestCustomMessage::Response);
240240
pass_along_path(&nodes);
241241
}
@@ -252,7 +252,7 @@ fn two_unblinded_two_blinded() {
252252
destination: Destination::BlindedPath(blinded_path),
253253
};
254254

255-
nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
255+
nodes[0].messenger.send_onion_message_using_path(path, test_msg, None).unwrap();
256256
nodes[4].custom_message_handler.expect_message(TestCustomMessage::Response);
257257
pass_along_path(&nodes);
258258
}
@@ -269,7 +269,7 @@ fn three_blinded_hops() {
269269
destination: Destination::BlindedPath(blinded_path),
270270
};
271271

272-
nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
272+
nodes[0].messenger.send_onion_message_using_path(path, test_msg, None).unwrap();
273273
nodes[3].custom_message_handler.expect_message(TestCustomMessage::Response);
274274
pass_along_path(&nodes);
275275
}
@@ -286,7 +286,7 @@ fn too_big_packet_error() {
286286
intermediate_nodes: hops,
287287
destination: Destination::Node(hop_node_id),
288288
};
289-
let err = nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap_err();
289+
let err = nodes[0].messenger.send_onion_message_using_path(path, test_msg, None).unwrap_err();
290290
assert_eq!(err, SendError::TooBigPacket);
291291
}
292292

@@ -304,7 +304,7 @@ fn we_are_intro_node() {
304304
destination: Destination::BlindedPath(blinded_path),
305305
};
306306

307-
nodes[0].messenger.send_onion_message(path, test_msg.clone(), None).unwrap();
307+
nodes[0].messenger.send_onion_message_using_path(path, test_msg.clone(), None).unwrap();
308308
nodes[2].custom_message_handler.expect_message(TestCustomMessage::Response);
309309
pass_along_path(&nodes);
310310

@@ -314,7 +314,7 @@ fn we_are_intro_node() {
314314
intermediate_nodes: vec![],
315315
destination: Destination::BlindedPath(blinded_path),
316316
};
317-
nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
317+
nodes[0].messenger.send_onion_message_using_path(path, test_msg, None).unwrap();
318318
nodes[1].custom_message_handler.expect_message(TestCustomMessage::Response);
319319
nodes.remove(2);
320320
pass_along_path(&nodes);
@@ -334,7 +334,7 @@ fn invalid_blinded_path_error() {
334334
intermediate_nodes: vec![],
335335
destination: Destination::BlindedPath(blinded_path),
336336
};
337-
let err = nodes[0].messenger.send_onion_message(path, test_msg.clone(), None).unwrap_err();
337+
let err = nodes[0].messenger.send_onion_message_using_path(path, test_msg.clone(), None).unwrap_err();
338338
assert_eq!(err, SendError::TooFewBlindedHops);
339339
}
340340

@@ -350,7 +350,7 @@ fn reply_path() {
350350
destination: Destination::Node(nodes[3].get_node_pk()),
351351
};
352352
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();
353-
nodes[0].messenger.send_onion_message(path, test_msg.clone(), Some(reply_path)).unwrap();
353+
nodes[0].messenger.send_onion_message_using_path(path, test_msg.clone(), Some(reply_path)).unwrap();
354354
nodes[3].custom_message_handler.expect_message(TestCustomMessage::Request);
355355
pass_along_path(&nodes);
356356
// Make sure the last node successfully decoded the reply path.
@@ -366,7 +366,7 @@ fn reply_path() {
366366
};
367367
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();
368368

369-
nodes[0].messenger.send_onion_message(path, test_msg, Some(reply_path)).unwrap();
369+
nodes[0].messenger.send_onion_message_using_path(path, test_msg, Some(reply_path)).unwrap();
370370
nodes[3].custom_message_handler.expect_message(TestCustomMessage::Request);
371371
pass_along_path(&nodes);
372372

@@ -397,7 +397,7 @@ fn invalid_custom_message_type() {
397397
intermediate_nodes: vec![],
398398
destination: Destination::Node(nodes[1].get_node_pk()),
399399
};
400-
let err = nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap_err();
400+
let err = nodes[0].messenger.send_onion_message_using_path(path, test_msg, None).unwrap_err();
401401
assert_eq!(err, SendError::InvalidMessage);
402402
}
403403

@@ -410,9 +410,9 @@ fn peer_buffer_full() {
410410
destination: Destination::Node(nodes[1].get_node_pk()),
411411
};
412412
for _ in 0..188 { // Based on MAX_PER_PEER_BUFFER_SIZE in OnionMessenger
413-
nodes[0].messenger.send_onion_message(path.clone(), test_msg.clone(), None).unwrap();
413+
nodes[0].messenger.send_onion_message_using_path(path.clone(), test_msg.clone(), None).unwrap();
414414
}
415-
let err = nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap_err();
415+
let err = nodes[0].messenger.send_onion_message_using_path(path, test_msg, None).unwrap_err();
416416
assert_eq!(err, SendError::BufferFull);
417417
}
418418

@@ -433,7 +433,7 @@ fn many_hops() {
433433
intermediate_nodes,
434434
destination: Destination::Node(nodes[num_nodes-1].get_node_pk()),
435435
};
436-
nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
436+
nodes[0].messenger.send_onion_message_using_path(path, test_msg, None).unwrap();
437437
nodes[num_nodes-1].custom_message_handler.expect_message(TestCustomMessage::Response);
438438
pass_along_path(&nodes);
439439
}

lightning/src/onion_message/messenger.rs

Lines changed: 58 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,14 @@ use crate::prelude::*;
7575
/// # struct FakeMessageRouter {}
7676
/// # impl MessageRouter for FakeMessageRouter {
7777
/// # fn find_path(&self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination) -> Result<OnionMessagePath, ()> {
78-
/// # unimplemented!()
78+
/// # let secp_ctx = Secp256k1::new();
79+
/// # let node_secret = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
80+
/// # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
81+
/// # let hop_node_id2 = hop_node_id1;
82+
/// # Ok(OnionMessagePath {
83+
/// # intermediate_nodes: vec![hop_node_id1, hop_node_id2],
84+
/// # destination,
85+
/// # })
7986
/// # }
8087
/// # }
8188
/// # let seed = [42u8; 32];
@@ -85,7 +92,7 @@ use crate::prelude::*;
8592
/// # let node_secret = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
8693
/// # let secp_ctx = Secp256k1::new();
8794
/// # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
88-
/// # let (hop_node_id2, hop_node_id3, hop_node_id4) = (hop_node_id1, hop_node_id1, hop_node_id1);
95+
/// # let (hop_node_id3, hop_node_id4) = (hop_node_id1, hop_node_id1);
8996
/// # let destination_node_id = hop_node_id1;
9097
/// # let message_router = Arc::new(FakeMessageRouter {});
9198
/// # let custom_message_handler = IgnoringMessageHandler {};
@@ -111,27 +118,21 @@ use crate::prelude::*;
111118
/// }
112119
/// }
113120
/// // Send a custom onion message to a node id.
114-
/// let path = OnionMessagePath {
115-
/// intermediate_nodes: vec![hop_node_id1, hop_node_id2],
116-
/// destination: Destination::Node(destination_node_id),
117-
/// };
121+
/// let destination = Destination::Node(destination_node_id);
118122
/// let reply_path = None;
119123
/// # let message = YourCustomMessage {};
120-
/// onion_messenger.send_onion_message(path, message, reply_path);
124+
/// onion_messenger.send_onion_message(message, destination, reply_path);
121125
///
122126
/// // Create a blinded path to yourself, for someone to send an onion message to.
123127
/// # let your_node_id = hop_node_id1;
124128
/// let hops = [hop_node_id3, hop_node_id4, your_node_id];
125129
/// let blinded_path = BlindedPath::new_for_message(&hops, &keys_manager, &secp_ctx).unwrap();
126130
///
127131
/// // Send a custom onion message to a blinded path.
128-
/// let path = OnionMessagePath {
129-
/// intermediate_nodes: vec![hop_node_id1, hop_node_id2],
130-
/// destination: Destination::BlindedPath(blinded_path),
131-
/// };
132+
/// let destination = Destination::BlindedPath(blinded_path);
132133
/// let reply_path = None;
133134
/// # let message = YourCustomMessage {};
134-
/// onion_messenger.send_onion_message(path, message, reply_path);
135+
/// onion_messenger.send_onion_message(message, destination, reply_path);
135136
/// ```
136137
///
137138
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
@@ -302,6 +303,16 @@ impl Destination {
302303
}
303304
}
304305

306+
/// Result of successfully [sending an onion message].
307+
///
308+
/// [sending an onion message]: OnionMessenger::send_onion_message
309+
#[derive(Debug, PartialEq, Eq)]
310+
pub enum SendSuccess {
311+
/// The message was buffered and will be sent once it is processed by
312+
/// [`OnionMessageHandler::next_onion_message_for_peer`].
313+
Buffered,
314+
}
315+
305316
/// Errors that may occur when [sending an onion message].
306317
///
307318
/// [sending an onion message]: OnionMessenger::send_onion_message
@@ -317,6 +328,8 @@ pub enum SendError {
317328
TooFewBlindedHops,
318329
/// Our next-hop peer was offline or does not support onion message forwarding.
319330
InvalidFirstHop,
331+
/// A path from the sender to the destination could not be found by the [`MessageRouter`].
332+
PathNotFound,
320333
/// Onion message contents must have a TLV type >= 64.
321334
InvalidMessage,
322335
/// Our next-hop peer's buffer was full or our total outbound buffer was full.
@@ -566,13 +579,32 @@ where
566579
}
567580
}
568581

569-
/// Sends an [`OnionMessage`] with the given `contents` for sending to the destination of
570-
/// `path`.
582+
/// Sends an [`OnionMessage`] with the given `contents` to `destination`.
571583
///
572584
/// See [`OnionMessenger`] for example usage.
573585
pub fn send_onion_message<T: OnionMessageContents>(
586+
&self, contents: T, destination: Destination, reply_path: Option<BlindedPath>
587+
) -> Result<SendSuccess, SendError> {
588+
let sender = self.node_signer
589+
.get_node_id(Recipient::Node)
590+
.map_err(|_| SendError::GetNodeIdFailed)?;
591+
592+
let peers = self.message_buffers.lock().unwrap()
593+
.iter()
594+
.filter(|(_, buffer)| matches!(buffer, OnionMessageBuffer::ConnectedPeer(_)))
595+
.map(|(node_id, _)| *node_id)
596+
.collect();
597+
598+
let path = self.message_router
599+
.find_path(sender, peers, destination)
600+
.map_err(|_| SendError::PathNotFound)?;
601+
602+
self.send_onion_message_using_path(path, contents, reply_path)
603+
}
604+
605+
pub(super) fn send_onion_message_using_path<T: OnionMessageContents>(
574606
&self, path: OnionMessagePath, contents: T, reply_path: Option<BlindedPath>
575-
) -> Result<(), SendError> {
607+
) -> Result<SendSuccess, SendError> {
576608
let (first_node_id, onion_message) = create_onion_message(
577609
&self.entropy_source, &self.node_signer, &self.secp_ctx, path, contents, reply_path
578610
)?;
@@ -586,7 +618,7 @@ where
586618
hash_map::Entry::Vacant(_) => Err(SendError::InvalidFirstHop),
587619
hash_map::Entry::Occupied(mut e) => {
588620
e.get_mut().enqueue_message(onion_message);
589-
Ok(())
621+
Ok(SendSuccess::Buffered)
590622
},
591623
}
592624
}
@@ -612,27 +644,19 @@ where
612644
&self, contents: T, destination: Destination, reply_path: Option<BlindedPath>,
613645
log_suffix: fmt::Arguments
614646
) {
615-
let sender = match self.node_signer.get_node_id(Recipient::Node) {
616-
Ok(node_id) => node_id,
617-
Err(_) => {
647+
match self.send_onion_message(contents, destination, reply_path) {
648+
Err(SendError::GetNodeIdFailed) => {
618649
log_warn!(self.logger, "Unable to retrieve node id {}", log_suffix);
619-
return;
620-
}
621-
};
622-
623-
let peers = self.message_buffers.lock().unwrap().keys().copied().collect();
624-
let path = match self.message_router.find_path(sender, peers, destination) {
625-
Ok(path) => path,
626-
Err(()) => {
650+
},
651+
Err(SendError::PathNotFound) => {
627652
log_trace!(self.logger, "Failed to find path {}", log_suffix);
628-
return;
629653
},
630-
};
631-
632-
log_trace!(self.logger, "Sending onion message {}", log_suffix);
633-
634-
if let Err(e) = self.send_onion_message(path, contents, reply_path) {
635-
log_trace!(self.logger, "Failed sending onion message {}: {:?}", log_suffix, e);
654+
Err(e) => {
655+
log_trace!(self.logger, "Failed sending onion message {}: {:?}", log_suffix, e);
656+
},
657+
Ok(SendSuccess::Buffered) => {
658+
log_trace!(self.logger, "Buffered onion message {}", log_suffix);
659+
},
636660
}
637661
}
638662

0 commit comments

Comments
 (0)