MessageRouter trait for OnionMessenger
[rust-lightning] / lightning / src / onion_message / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
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
8 // licenses.
9
10 //! Onion message testing and test utilities live here.
11
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;
19
20 use bitcoin::network::constants::Network;
21 use bitcoin::secp256k1::{PublicKey, Secp256k1};
22
23 use core::sync::atomic::{AtomicU16, Ordering};
24 use crate::io;
25 use crate::io_extras::read_to_end;
26 use crate::sync::Arc;
27
28 struct MessengerNode {
29         keys_manager: Arc<test_utils::TestKeysInterface>,
30         messenger: OnionMessenger<
31                 Arc<test_utils::TestKeysInterface>,
32                 Arc<test_utils::TestKeysInterface>,
33                 Arc<test_utils::TestLogger>,
34                 Arc<TestMessageRouter>,
35                 Arc<TestOffersMessageHandler>,
36                 Arc<TestCustomMessageHandler>
37         >,
38         custom_message_handler: Arc<TestCustomMessageHandler>,
39         logger: Arc<test_utils::TestLogger>,
40 }
41
42 impl MessengerNode {
43         fn get_node_pk(&self) -> PublicKey {
44                 self.keys_manager.get_node_id(Recipient::Node).unwrap()
45         }
46 }
47
48 struct TestMessageRouter {}
49
50 impl MessageRouter for TestMessageRouter {
51         fn find_path(
52                 &self, _sender: PublicKey, _peers: Vec<PublicKey>, _destination: Destination
53         ) -> Result<OnionMessagePath, ()> {
54                 todo!()
55         }
56 }
57
58 struct TestOffersMessageHandler {}
59
60 impl OffersMessageHandler for TestOffersMessageHandler {
61         fn handle_message(&self, _message: OffersMessage) {
62                 todo!()
63         }
64 }
65
66 #[derive(Clone)]
67 struct TestCustomMessage {}
68
69 const CUSTOM_MESSAGE_TYPE: u64 = 4242;
70 const CUSTOM_MESSAGE_CONTENTS: [u8; 32] = [42; 32];
71
72 impl CustomOnionMessageContents for TestCustomMessage {
73         fn tlv_type(&self) -> u64 {
74                 CUSTOM_MESSAGE_TYPE
75         }
76 }
77
78 impl Writeable for TestCustomMessage {
79         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
80                 Ok(CUSTOM_MESSAGE_CONTENTS.write(w)?)
81         }
82 }
83
84 struct TestCustomMessageHandler {
85         num_messages_expected: AtomicU16,
86 }
87
88 impl TestCustomMessageHandler {
89         fn new() -> Self {
90                 Self { num_messages_expected: AtomicU16::new(0) }
91         }
92 }
93
94 impl Drop for TestCustomMessageHandler {
95         fn drop(&mut self) {
96                 #[cfg(feature = "std")] {
97                         if std::thread::panicking() {
98                                 return;
99                         }
100                 }
101                 assert_eq!(self.num_messages_expected.load(Ordering::SeqCst), 0);
102         }
103 }
104
105 impl CustomOnionMessageHandler for TestCustomMessageHandler {
106         type CustomMessage = TestCustomMessage;
107         fn handle_custom_message(&self, _msg: Self::CustomMessage) {
108                 self.num_messages_expected.fetch_sub(1, Ordering::SeqCst);
109         }
110         fn read_custom_message<R: io::Read>(&self, message_type: u64, buffer: &mut R) -> Result<Option<Self::CustomMessage>, DecodeError> where Self: Sized {
111                 if message_type == CUSTOM_MESSAGE_TYPE {
112                         let buf = read_to_end(buffer)?;
113                         assert_eq!(buf, CUSTOM_MESSAGE_CONTENTS);
114                         return Ok(Some(TestCustomMessage {}))
115                 }
116                 Ok(None)
117         }
118 }
119
120 fn create_nodes(num_messengers: u8) -> Vec<MessengerNode> {
121         let mut nodes = Vec::new();
122         for i in 0..num_messengers {
123                 let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
124                 let seed = [i as u8; 32];
125                 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet));
126                 let message_router = Arc::new(TestMessageRouter {});
127                 let offers_message_handler = Arc::new(TestOffersMessageHandler {});
128                 let custom_message_handler = Arc::new(TestCustomMessageHandler::new());
129                 nodes.push(MessengerNode {
130                         keys_manager: keys_manager.clone(),
131                         messenger: OnionMessenger::new(
132                                 keys_manager.clone(), keys_manager, logger.clone(), message_router,
133                                 offers_message_handler, custom_message_handler.clone()
134                         ),
135                         custom_message_handler,
136                         logger,
137                 });
138         }
139         for idx in 0..num_messengers - 1 {
140                 let i = idx as usize;
141                 let mut features = InitFeatures::empty();
142                 features.set_onion_messages_optional();
143                 let init_msg = msgs::Init { features, networks: None, remote_network_address: None };
144                 nodes[i].messenger.peer_connected(&nodes[i + 1].get_node_pk(), &init_msg.clone(), true).unwrap();
145                 nodes[i + 1].messenger.peer_connected(&nodes[i].get_node_pk(), &init_msg.clone(), false).unwrap();
146         }
147         nodes
148 }
149
150 fn pass_along_path(path: &Vec<MessengerNode>) {
151         path[path.len() - 1].custom_message_handler.num_messages_expected.fetch_add(1, Ordering::SeqCst);
152         let mut prev_node = &path[0];
153         for node in path.into_iter().skip(1) {
154                 let events = prev_node.messenger.release_pending_msgs();
155                 let onion_msg =  {
156                         let msgs = events.get(&node.get_node_pk()).unwrap();
157                         assert_eq!(msgs.len(), 1);
158                         msgs[0].clone()
159                 };
160                 node.messenger.handle_onion_message(&prev_node.get_node_pk(), &onion_msg);
161                 prev_node = node;
162         }
163 }
164
165 #[test]
166 fn one_hop() {
167         let nodes = create_nodes(2);
168         let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
169
170         let path = OnionMessagePath {
171                 intermediate_nodes: vec![],
172                 destination: Destination::Node(nodes[1].get_node_pk()),
173         };
174         nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
175         pass_along_path(&nodes);
176 }
177
178 #[test]
179 fn two_unblinded_hops() {
180         let nodes = create_nodes(3);
181         let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
182
183         let path = OnionMessagePath {
184                 intermediate_nodes: vec![nodes[1].get_node_pk()],
185                 destination: Destination::Node(nodes[2].get_node_pk()),
186         };
187         nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
188         pass_along_path(&nodes);
189 }
190
191 #[test]
192 fn two_unblinded_two_blinded() {
193         let nodes = create_nodes(5);
194         let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
195
196         let secp_ctx = Secp256k1::new();
197         let blinded_path = BlindedPath::new_for_message(&[nodes[3].get_node_pk(), nodes[4].get_node_pk()], &*nodes[4].keys_manager, &secp_ctx).unwrap();
198         let path = OnionMessagePath {
199                 intermediate_nodes: vec![nodes[1].get_node_pk(), nodes[2].get_node_pk()],
200                 destination: Destination::BlindedPath(blinded_path),
201         };
202
203         nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
204         pass_along_path(&nodes);
205 }
206
207 #[test]
208 fn three_blinded_hops() {
209         let nodes = create_nodes(4);
210         let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
211
212         let secp_ctx = Secp256k1::new();
213         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();
214         let path = OnionMessagePath {
215                 intermediate_nodes: vec![],
216                 destination: Destination::BlindedPath(blinded_path),
217         };
218
219         nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
220         pass_along_path(&nodes);
221 }
222
223 #[test]
224 fn too_big_packet_error() {
225         // Make sure we error as expected if a packet is too big to send.
226         let nodes = create_nodes(2);
227         let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
228
229         let hop_node_id = nodes[1].get_node_pk();
230         let hops = vec![hop_node_id; 400];
231         let path = OnionMessagePath {
232                 intermediate_nodes: hops,
233                 destination: Destination::Node(hop_node_id),
234         };
235         let err = nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap_err();
236         assert_eq!(err, SendError::TooBigPacket);
237 }
238
239 #[test]
240 fn we_are_intro_node() {
241         // If we are sending straight to a blinded path and we are the introduction node, we need to
242         // advance the blinded path by 1 hop so the second hop is the new introduction node.
243         let mut nodes = create_nodes(3);
244         let test_msg = TestCustomMessage {};
245
246         let secp_ctx = Secp256k1::new();
247         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();
248         let path = OnionMessagePath {
249                 intermediate_nodes: vec![],
250                 destination: Destination::BlindedPath(blinded_path),
251         };
252
253         nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg.clone()), None).unwrap();
254         pass_along_path(&nodes);
255
256         // Try with a two-hop blinded path where we are the introduction node.
257         let blinded_path = BlindedPath::new_for_message(&[nodes[0].get_node_pk(), nodes[1].get_node_pk()], &*nodes[1].keys_manager, &secp_ctx).unwrap();
258         let path = OnionMessagePath {
259                 intermediate_nodes: vec![],
260                 destination: Destination::BlindedPath(blinded_path),
261         };
262         nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg), None).unwrap();
263         nodes.remove(2);
264         pass_along_path(&nodes);
265 }
266
267 #[test]
268 fn invalid_blinded_path_error() {
269         // Make sure we error as expected if a provided blinded path has 0 or 1 hops.
270         let nodes = create_nodes(3);
271         let test_msg = TestCustomMessage {};
272
273         // 0 hops
274         let secp_ctx = Secp256k1::new();
275         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();
276         blinded_path.blinded_hops.clear();
277         let path = OnionMessagePath {
278                 intermediate_nodes: vec![],
279                 destination: Destination::BlindedPath(blinded_path),
280         };
281         let err = nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg.clone()), None).unwrap_err();
282         assert_eq!(err, SendError::TooFewBlindedHops);
283
284         // 1 hop
285         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();
286         blinded_path.blinded_hops.remove(0);
287         assert_eq!(blinded_path.blinded_hops.len(), 1);
288         let path = OnionMessagePath {
289                 intermediate_nodes: vec![],
290                 destination: Destination::BlindedPath(blinded_path),
291         };
292         let err = nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg), None).unwrap_err();
293         assert_eq!(err, SendError::TooFewBlindedHops);
294 }
295
296 #[test]
297 fn reply_path() {
298         let nodes = create_nodes(4);
299         let test_msg = TestCustomMessage {};
300         let secp_ctx = Secp256k1::new();
301
302         // Destination::Node
303         let path = OnionMessagePath {
304                 intermediate_nodes: vec![nodes[1].get_node_pk(), nodes[2].get_node_pk()],
305                 destination: Destination::Node(nodes[3].get_node_pk()),
306         };
307         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();
308         nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg.clone()), Some(reply_path)).unwrap();
309         pass_along_path(&nodes);
310         // Make sure the last node successfully decoded the reply path.
311         nodes[3].logger.assert_log_contains(
312                 "lightning::onion_message::messenger",
313                 &format!("Received an onion message with path_id None and a reply_path"), 1);
314
315         // Destination::BlindedPath
316         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();
317         let path = OnionMessagePath {
318                 intermediate_nodes: vec![],
319                 destination: Destination::BlindedPath(blinded_path),
320         };
321         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();
322
323         nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg), Some(reply_path)).unwrap();
324         pass_along_path(&nodes);
325         nodes[3].logger.assert_log_contains(
326                 "lightning::onion_message::messenger",
327                 &format!("Received an onion message with path_id None and a reply_path"), 2);
328 }
329
330 #[test]
331 fn invalid_custom_message_type() {
332         let nodes = create_nodes(2);
333
334         struct InvalidCustomMessage{}
335         impl CustomOnionMessageContents for InvalidCustomMessage {
336                 fn tlv_type(&self) -> u64 {
337                         // Onion message contents must have a TLV >= 64.
338                         63
339                 }
340         }
341
342         impl Writeable for InvalidCustomMessage {
343                 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> { unreachable!() }
344         }
345
346         let test_msg = OnionMessageContents::Custom(InvalidCustomMessage {});
347         let path = OnionMessagePath {
348                 intermediate_nodes: vec![],
349                 destination: Destination::Node(nodes[1].get_node_pk()),
350         };
351         let err = nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap_err();
352         assert_eq!(err, SendError::InvalidMessage);
353 }
354
355 #[test]
356 fn peer_buffer_full() {
357         let nodes = create_nodes(2);
358         let test_msg = TestCustomMessage {};
359         let path = OnionMessagePath {
360                 intermediate_nodes: vec![],
361                 destination: Destination::Node(nodes[1].get_node_pk()),
362         };
363         for _ in 0..188 { // Based on MAX_PER_PEER_BUFFER_SIZE in OnionMessenger
364                 nodes[0].messenger.send_onion_message(path.clone(), OnionMessageContents::Custom(test_msg.clone()), None).unwrap();
365         }
366         let err = nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg), None).unwrap_err();
367         assert_eq!(err, SendError::BufferFull);
368 }
369
370 #[test]
371 fn many_hops() {
372         // Check we can send over a route with many hops. This will exercise our logic for onion messages
373         // of size [`crate::onion_message::packet::BIG_PACKET_HOP_DATA_LEN`].
374         let num_nodes: usize = 25;
375         let nodes = create_nodes(num_nodes as u8);
376         let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
377
378         let mut intermediate_nodes = vec![];
379         for i in 1..(num_nodes-1) {
380                 intermediate_nodes.push(nodes[i].get_node_pk());
381         }
382
383         let path = OnionMessagePath {
384                 intermediate_nodes,
385                 destination: Destination::Node(nodes[num_nodes-1].get_node_pk()),
386         };
387         nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
388         pass_along_path(&nodes);
389 }