1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Onion message testing and test utilities live here.
12 use crate::blinded_path::BlindedPath;
13 use crate::sign::{NodeSigner, Recipient};
14 use crate::ln::features::InitFeatures;
15 use crate::ln::msgs::{self, DecodeError, OnionMessageHandler};
16 use super::{CustomOnionMessageContents, CustomOnionMessageHandler, Destination, MessageRouter, OffersMessage, OffersMessageHandler, OnionMessageContents, OnionMessagePath, OnionMessenger, SendError};
17 use crate::util::ser::{Writeable, Writer};
18 use crate::util::test_utils;
20 use bitcoin::network::constants::Network;
21 use bitcoin::secp256k1::{PublicKey, Secp256k1};
24 use crate::io_extras::read_to_end;
25 use crate::sync::{Arc, Mutex};
27 use crate::prelude::*;
29 struct MessengerNode {
30 keys_manager: Arc<test_utils::TestKeysInterface>,
31 messenger: OnionMessenger<
32 Arc<test_utils::TestKeysInterface>,
33 Arc<test_utils::TestKeysInterface>,
34 Arc<test_utils::TestLogger>,
35 Arc<TestMessageRouter>,
36 Arc<TestOffersMessageHandler>,
37 Arc<TestCustomMessageHandler>
39 custom_message_handler: Arc<TestCustomMessageHandler>,
43 fn get_node_pk(&self) -> PublicKey {
44 self.keys_manager.get_node_id(Recipient::Node).unwrap()
48 struct TestMessageRouter {}
50 impl MessageRouter for TestMessageRouter {
52 &self, _sender: PublicKey, _peers: Vec<PublicKey>, destination: Destination
53 ) -> Result<OnionMessagePath, ()> {
55 intermediate_nodes: vec![],
61 struct TestOffersMessageHandler {}
63 impl OffersMessageHandler for TestOffersMessageHandler {
64 fn handle_message(&self, _message: OffersMessage) -> Option<OffersMessage> {
69 #[derive(Clone, Debug, PartialEq)]
70 enum TestCustomMessage {
75 const CUSTOM_REQUEST_MESSAGE_TYPE: u64 = 4242;
76 const CUSTOM_RESPONSE_MESSAGE_TYPE: u64 = 4343;
77 const CUSTOM_REQUEST_MESSAGE_CONTENTS: [u8; 32] = [42; 32];
78 const CUSTOM_RESPONSE_MESSAGE_CONTENTS: [u8; 32] = [43; 32];
80 impl CustomOnionMessageContents for TestCustomMessage {
81 fn tlv_type(&self) -> u64 {
83 TestCustomMessage::Request => CUSTOM_REQUEST_MESSAGE_TYPE,
84 TestCustomMessage::Response => CUSTOM_RESPONSE_MESSAGE_TYPE,
89 impl Writeable for TestCustomMessage {
90 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
92 TestCustomMessage::Request => Ok(CUSTOM_REQUEST_MESSAGE_CONTENTS.write(w)?),
93 TestCustomMessage::Response => Ok(CUSTOM_RESPONSE_MESSAGE_CONTENTS.write(w)?),
98 struct TestCustomMessageHandler {
99 expected_messages: Mutex<VecDeque<TestCustomMessage>>,
102 impl TestCustomMessageHandler {
104 Self { expected_messages: Mutex::new(VecDeque::new()) }
107 fn expect_message(&self, message: TestCustomMessage) {
108 self.expected_messages.lock().unwrap().push_back(message);
112 impl Drop for TestCustomMessageHandler {
114 #[cfg(feature = "std")] {
115 if std::thread::panicking() {
119 assert!(self.expected_messages.lock().unwrap().is_empty());
123 impl CustomOnionMessageHandler for TestCustomMessageHandler {
124 type CustomMessage = TestCustomMessage;
125 fn handle_custom_message(&self, msg: Self::CustomMessage) -> Option<Self::CustomMessage> {
126 match self.expected_messages.lock().unwrap().pop_front() {
127 Some(expected_msg) => assert_eq!(expected_msg, msg),
128 None => panic!("Unexpected message: {:?}", msg),
132 TestCustomMessage::Request => Some(TestCustomMessage::Response),
133 TestCustomMessage::Response => None,
136 fn read_custom_message<R: io::Read>(&self, message_type: u64, buffer: &mut R) -> Result<Option<Self::CustomMessage>, DecodeError> where Self: Sized {
138 CUSTOM_REQUEST_MESSAGE_TYPE => {
139 let buf = read_to_end(buffer)?;
140 assert_eq!(buf, CUSTOM_REQUEST_MESSAGE_CONTENTS);
141 Ok(Some(TestCustomMessage::Request))
143 CUSTOM_RESPONSE_MESSAGE_TYPE => {
144 let buf = read_to_end(buffer)?;
145 assert_eq!(buf, CUSTOM_RESPONSE_MESSAGE_CONTENTS);
146 Ok(Some(TestCustomMessage::Response))
153 fn create_nodes(num_messengers: u8) -> Vec<MessengerNode> {
154 let mut nodes = Vec::new();
155 for i in 0..num_messengers {
156 let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
157 let seed = [i as u8; 32];
158 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet));
159 let message_router = Arc::new(TestMessageRouter {});
160 let offers_message_handler = Arc::new(TestOffersMessageHandler {});
161 let custom_message_handler = Arc::new(TestCustomMessageHandler::new());
162 nodes.push(MessengerNode {
163 keys_manager: keys_manager.clone(),
164 messenger: OnionMessenger::new(
165 keys_manager.clone(), keys_manager, logger.clone(), message_router,
166 offers_message_handler, custom_message_handler.clone()
168 custom_message_handler,
171 for idx in 0..num_messengers - 1 {
172 let i = idx as usize;
173 let mut features = InitFeatures::empty();
174 features.set_onion_messages_optional();
175 let init_msg = msgs::Init { features, networks: None, remote_network_address: None };
176 nodes[i].messenger.peer_connected(&nodes[i + 1].get_node_pk(), &init_msg.clone(), true).unwrap();
177 nodes[i + 1].messenger.peer_connected(&nodes[i].get_node_pk(), &init_msg.clone(), false).unwrap();
182 fn pass_along_path(path: &Vec<MessengerNode>) {
183 let mut prev_node = &path[0];
184 for node in path.into_iter().skip(1) {
185 let events = prev_node.messenger.release_pending_msgs();
187 let msgs = events.get(&node.get_node_pk()).unwrap();
188 assert_eq!(msgs.len(), 1);
191 node.messenger.handle_onion_message(&prev_node.get_node_pk(), &onion_msg);
198 let nodes = create_nodes(2);
199 let test_msg = OnionMessageContents::Custom(TestCustomMessage::Response);
201 let path = OnionMessagePath {
202 intermediate_nodes: vec![],
203 destination: Destination::Node(nodes[1].get_node_pk()),
205 nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
206 nodes[1].custom_message_handler.expect_message(TestCustomMessage::Response);
207 pass_along_path(&nodes);
211 fn two_unblinded_hops() {
212 let nodes = create_nodes(3);
213 let test_msg = OnionMessageContents::Custom(TestCustomMessage::Response);
215 let path = OnionMessagePath {
216 intermediate_nodes: vec![nodes[1].get_node_pk()],
217 destination: Destination::Node(nodes[2].get_node_pk()),
219 nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
220 nodes[2].custom_message_handler.expect_message(TestCustomMessage::Response);
221 pass_along_path(&nodes);
225 fn two_unblinded_two_blinded() {
226 let nodes = create_nodes(5);
227 let test_msg = OnionMessageContents::Custom(TestCustomMessage::Response);
229 let secp_ctx = Secp256k1::new();
230 let blinded_path = BlindedPath::new_for_message(&[nodes[3].get_node_pk(), nodes[4].get_node_pk()], &*nodes[4].keys_manager, &secp_ctx).unwrap();
231 let path = OnionMessagePath {
232 intermediate_nodes: vec![nodes[1].get_node_pk(), nodes[2].get_node_pk()],
233 destination: Destination::BlindedPath(blinded_path),
236 nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
237 nodes[4].custom_message_handler.expect_message(TestCustomMessage::Response);
238 pass_along_path(&nodes);
242 fn three_blinded_hops() {
243 let nodes = create_nodes(4);
244 let test_msg = OnionMessageContents::Custom(TestCustomMessage::Response);
246 let secp_ctx = Secp256k1::new();
247 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();
248 let path = OnionMessagePath {
249 intermediate_nodes: vec![],
250 destination: Destination::BlindedPath(blinded_path),
253 nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
254 nodes[3].custom_message_handler.expect_message(TestCustomMessage::Response);
255 pass_along_path(&nodes);
259 fn too_big_packet_error() {
260 // Make sure we error as expected if a packet is too big to send.
261 let nodes = create_nodes(2);
262 let test_msg = OnionMessageContents::Custom(TestCustomMessage::Response);
264 let hop_node_id = nodes[1].get_node_pk();
265 let hops = vec![hop_node_id; 400];
266 let path = OnionMessagePath {
267 intermediate_nodes: hops,
268 destination: Destination::Node(hop_node_id),
270 let err = nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap_err();
271 assert_eq!(err, SendError::TooBigPacket);
275 fn we_are_intro_node() {
276 // If we are sending straight to a blinded path and we are the introduction node, we need to
277 // advance the blinded path by 1 hop so the second hop is the new introduction node.
278 let mut nodes = create_nodes(3);
279 let test_msg = TestCustomMessage::Response;
281 let secp_ctx = Secp256k1::new();
282 let blinded_path = BlindedPath::new_for_message(&[nodes[0].get_node_pk(), nodes[1].get_node_pk(), nodes[2].get_node_pk()], &*nodes[2].keys_manager, &secp_ctx).unwrap();
283 let path = OnionMessagePath {
284 intermediate_nodes: vec![],
285 destination: Destination::BlindedPath(blinded_path),
288 nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg.clone()), None).unwrap();
289 nodes[2].custom_message_handler.expect_message(TestCustomMessage::Response);
290 pass_along_path(&nodes);
292 // Try with a two-hop blinded path where we are the introduction node.
293 let blinded_path = BlindedPath::new_for_message(&[nodes[0].get_node_pk(), nodes[1].get_node_pk()], &*nodes[1].keys_manager, &secp_ctx).unwrap();
294 let path = OnionMessagePath {
295 intermediate_nodes: vec![],
296 destination: Destination::BlindedPath(blinded_path),
298 nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg), None).unwrap();
299 nodes[1].custom_message_handler.expect_message(TestCustomMessage::Response);
301 pass_along_path(&nodes);
305 fn invalid_blinded_path_error() {
306 // Make sure we error as expected if a provided blinded path has 0 or 1 hops.
307 let nodes = create_nodes(3);
308 let test_msg = TestCustomMessage::Response;
311 let secp_ctx = Secp256k1::new();
312 let mut blinded_path = BlindedPath::new_for_message(&[nodes[1].get_node_pk(), nodes[2].get_node_pk()], &*nodes[2].keys_manager, &secp_ctx).unwrap();
313 blinded_path.blinded_hops.clear();
314 let path = OnionMessagePath {
315 intermediate_nodes: vec![],
316 destination: Destination::BlindedPath(blinded_path),
318 let err = nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg.clone()), None).unwrap_err();
319 assert_eq!(err, SendError::TooFewBlindedHops);
322 let mut blinded_path = BlindedPath::new_for_message(&[nodes[1].get_node_pk(), nodes[2].get_node_pk()], &*nodes[2].keys_manager, &secp_ctx).unwrap();
323 blinded_path.blinded_hops.remove(0);
324 assert_eq!(blinded_path.blinded_hops.len(), 1);
325 let path = OnionMessagePath {
326 intermediate_nodes: vec![],
327 destination: Destination::BlindedPath(blinded_path),
329 let err = nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg), None).unwrap_err();
330 assert_eq!(err, SendError::TooFewBlindedHops);
335 let mut nodes = create_nodes(4);
336 let test_msg = TestCustomMessage::Request;
337 let secp_ctx = Secp256k1::new();
340 let path = OnionMessagePath {
341 intermediate_nodes: vec![nodes[1].get_node_pk(), nodes[2].get_node_pk()],
342 destination: Destination::Node(nodes[3].get_node_pk()),
344 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, OnionMessageContents::Custom(test_msg.clone()), Some(reply_path)).unwrap();
346 nodes[3].custom_message_handler.expect_message(TestCustomMessage::Request);
347 pass_along_path(&nodes);
348 // Make sure the last node successfully decoded the reply path.
349 nodes[0].custom_message_handler.expect_message(TestCustomMessage::Response);
351 pass_along_path(&nodes);
353 // Destination::BlindedPath
354 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();
355 let path = OnionMessagePath {
356 intermediate_nodes: vec![],
357 destination: Destination::BlindedPath(blinded_path),
359 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();
361 nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg), Some(reply_path)).unwrap();
362 nodes[3].custom_message_handler.expect_message(TestCustomMessage::Request);
363 pass_along_path(&nodes);
365 // Make sure the last node successfully decoded the reply path.
366 nodes[0].custom_message_handler.expect_message(TestCustomMessage::Response);
368 pass_along_path(&nodes);
372 fn invalid_custom_message_type() {
373 let nodes = create_nodes(2);
375 struct InvalidCustomMessage{}
376 impl CustomOnionMessageContents for InvalidCustomMessage {
377 fn tlv_type(&self) -> u64 {
378 // Onion message contents must have a TLV >= 64.
383 impl Writeable for InvalidCustomMessage {
384 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> { unreachable!() }
387 let test_msg = OnionMessageContents::Custom(InvalidCustomMessage {});
388 let path = OnionMessagePath {
389 intermediate_nodes: vec![],
390 destination: Destination::Node(nodes[1].get_node_pk()),
392 let err = nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap_err();
393 assert_eq!(err, SendError::InvalidMessage);
397 fn peer_buffer_full() {
398 let nodes = create_nodes(2);
399 let test_msg = TestCustomMessage::Request;
400 let path = OnionMessagePath {
401 intermediate_nodes: vec![],
402 destination: Destination::Node(nodes[1].get_node_pk()),
404 for _ in 0..188 { // Based on MAX_PER_PEER_BUFFER_SIZE in OnionMessenger
405 nodes[0].messenger.send_onion_message(path.clone(), OnionMessageContents::Custom(test_msg.clone()), None).unwrap();
407 let err = nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg), None).unwrap_err();
408 assert_eq!(err, SendError::BufferFull);
413 // Check we can send over a route with many hops. This will exercise our logic for onion messages
414 // of size [`crate::onion_message::packet::BIG_PACKET_HOP_DATA_LEN`].
415 let num_nodes: usize = 25;
416 let nodes = create_nodes(num_nodes as u8);
417 let test_msg = TestCustomMessage::Response;
419 let mut intermediate_nodes = vec![];
420 for i in 1..(num_nodes-1) {
421 intermediate_nodes.push(nodes[i].get_node_pk());
424 let path = OnionMessagePath {
426 destination: Destination::Node(nodes[num_nodes-1].get_node_pk()),
428 nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg), None).unwrap();
429 nodes[num_nodes-1].custom_message_handler.expect_message(TestCustomMessage::Response);
430 pass_along_path(&nodes);