e6058c459eb972710a84605d30bbc69360fd976c
[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) -> Option<OffersMessage> {
62                 None
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) -> Option<Self::CustomMessage> {
108                 self.num_messages_expected.fetch_sub(1, Ordering::SeqCst);
109                 None
110         }
111         fn read_custom_message<R: io::Read>(&self, message_type: u64, buffer: &mut R) -> Result<Option<Self::CustomMessage>, DecodeError> where Self: Sized {
112                 if message_type == CUSTOM_MESSAGE_TYPE {
113                         let buf = read_to_end(buffer)?;
114                         assert_eq!(buf, CUSTOM_MESSAGE_CONTENTS);
115                         return Ok(Some(TestCustomMessage {}))
116                 }
117                 Ok(None)
118         }
119 }
120
121 fn create_nodes(num_messengers: u8) -> Vec<MessengerNode> {
122         let mut nodes = Vec::new();
123         for i in 0..num_messengers {
124                 let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
125                 let seed = [i as u8; 32];
126                 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet));
127                 let message_router = Arc::new(TestMessageRouter {});
128                 let offers_message_handler = Arc::new(TestOffersMessageHandler {});
129                 let custom_message_handler = Arc::new(TestCustomMessageHandler::new());
130                 nodes.push(MessengerNode {
131                         keys_manager: keys_manager.clone(),
132                         messenger: OnionMessenger::new(
133                                 keys_manager.clone(), keys_manager, logger.clone(), message_router,
134                                 offers_message_handler, custom_message_handler.clone()
135                         ),
136                         custom_message_handler,
137                         logger,
138                 });
139         }
140         for idx in 0..num_messengers - 1 {
141                 let i = idx as usize;
142                 let mut features = InitFeatures::empty();
143                 features.set_onion_messages_optional();
144                 let init_msg = msgs::Init { features, networks: None, remote_network_address: None };
145                 nodes[i].messenger.peer_connected(&nodes[i + 1].get_node_pk(), &init_msg.clone(), true).unwrap();
146                 nodes[i + 1].messenger.peer_connected(&nodes[i].get_node_pk(), &init_msg.clone(), false).unwrap();
147         }
148         nodes
149 }
150
151 fn pass_along_path(path: &Vec<MessengerNode>) {
152         path[path.len() - 1].custom_message_handler.num_messages_expected.fetch_add(1, Ordering::SeqCst);
153         let mut prev_node = &path[0];
154         for node in path.into_iter().skip(1) {
155                 let events = prev_node.messenger.release_pending_msgs();
156                 let onion_msg =  {
157                         let msgs = events.get(&node.get_node_pk()).unwrap();
158                         assert_eq!(msgs.len(), 1);
159                         msgs[0].clone()
160                 };
161                 node.messenger.handle_onion_message(&prev_node.get_node_pk(), &onion_msg);
162                 prev_node = node;
163         }
164 }
165
166 #[test]
167 fn one_hop() {
168         let nodes = create_nodes(2);
169         let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
170
171         let path = OnionMessagePath {
172                 intermediate_nodes: vec![],
173                 destination: Destination::Node(nodes[1].get_node_pk()),
174         };
175         nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
176         pass_along_path(&nodes);
177 }
178
179 #[test]
180 fn two_unblinded_hops() {
181         let nodes = create_nodes(3);
182         let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
183
184         let path = OnionMessagePath {
185                 intermediate_nodes: vec![nodes[1].get_node_pk()],
186                 destination: Destination::Node(nodes[2].get_node_pk()),
187         };
188         nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
189         pass_along_path(&nodes);
190 }
191
192 #[test]
193 fn two_unblinded_two_blinded() {
194         let nodes = create_nodes(5);
195         let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
196
197         let secp_ctx = Secp256k1::new();
198         let blinded_path = BlindedPath::new_for_message(&[nodes[3].get_node_pk(), nodes[4].get_node_pk()], &*nodes[4].keys_manager, &secp_ctx).unwrap();
199         let path = OnionMessagePath {
200                 intermediate_nodes: vec![nodes[1].get_node_pk(), nodes[2].get_node_pk()],
201                 destination: Destination::BlindedPath(blinded_path),
202         };
203
204         nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
205         pass_along_path(&nodes);
206 }
207
208 #[test]
209 fn three_blinded_hops() {
210         let nodes = create_nodes(4);
211         let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
212
213         let secp_ctx = Secp256k1::new();
214         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();
215         let path = OnionMessagePath {
216                 intermediate_nodes: vec![],
217                 destination: Destination::BlindedPath(blinded_path),
218         };
219
220         nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
221         pass_along_path(&nodes);
222 }
223
224 #[test]
225 fn too_big_packet_error() {
226         // Make sure we error as expected if a packet is too big to send.
227         let nodes = create_nodes(2);
228         let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
229
230         let hop_node_id = nodes[1].get_node_pk();
231         let hops = vec![hop_node_id; 400];
232         let path = OnionMessagePath {
233                 intermediate_nodes: hops,
234                 destination: Destination::Node(hop_node_id),
235         };
236         let err = nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap_err();
237         assert_eq!(err, SendError::TooBigPacket);
238 }
239
240 #[test]
241 fn we_are_intro_node() {
242         // If we are sending straight to a blinded path and we are the introduction node, we need to
243         // advance the blinded path by 1 hop so the second hop is the new introduction node.
244         let mut nodes = create_nodes(3);
245         let test_msg = TestCustomMessage {};
246
247         let secp_ctx = Secp256k1::new();
248         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();
249         let path = OnionMessagePath {
250                 intermediate_nodes: vec![],
251                 destination: Destination::BlindedPath(blinded_path),
252         };
253
254         nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg.clone()), None).unwrap();
255         pass_along_path(&nodes);
256
257         // Try with a two-hop blinded path where we are the introduction node.
258         let blinded_path = BlindedPath::new_for_message(&[nodes[0].get_node_pk(), nodes[1].get_node_pk()], &*nodes[1].keys_manager, &secp_ctx).unwrap();
259         let path = OnionMessagePath {
260                 intermediate_nodes: vec![],
261                 destination: Destination::BlindedPath(blinded_path),
262         };
263         nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg), None).unwrap();
264         nodes.remove(2);
265         pass_along_path(&nodes);
266 }
267
268 #[test]
269 fn invalid_blinded_path_error() {
270         // Make sure we error as expected if a provided blinded path has 0 or 1 hops.
271         let nodes = create_nodes(3);
272         let test_msg = TestCustomMessage {};
273
274         // 0 hops
275         let secp_ctx = Secp256k1::new();
276         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();
277         blinded_path.blinded_hops.clear();
278         let path = OnionMessagePath {
279                 intermediate_nodes: vec![],
280                 destination: Destination::BlindedPath(blinded_path),
281         };
282         let err = nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg.clone()), None).unwrap_err();
283         assert_eq!(err, SendError::TooFewBlindedHops);
284
285         // 1 hop
286         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();
287         blinded_path.blinded_hops.remove(0);
288         assert_eq!(blinded_path.blinded_hops.len(), 1);
289         let path = OnionMessagePath {
290                 intermediate_nodes: vec![],
291                 destination: Destination::BlindedPath(blinded_path),
292         };
293         let err = nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg), None).unwrap_err();
294         assert_eq!(err, SendError::TooFewBlindedHops);
295 }
296
297 #[test]
298 fn reply_path() {
299         let nodes = create_nodes(4);
300         let test_msg = TestCustomMessage {};
301         let secp_ctx = Secp256k1::new();
302
303         // Destination::Node
304         let path = OnionMessagePath {
305                 intermediate_nodes: vec![nodes[1].get_node_pk(), nodes[2].get_node_pk()],
306                 destination: Destination::Node(nodes[3].get_node_pk()),
307         };
308         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();
309         nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg.clone()), Some(reply_path)).unwrap();
310         pass_along_path(&nodes);
311         // Make sure the last node successfully decoded the reply path.
312         nodes[3].logger.assert_log_contains(
313                 "lightning::onion_message::messenger",
314                 &format!("Received an onion message with path_id None and a reply_path"), 1);
315
316         // Destination::BlindedPath
317         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();
318         let path = OnionMessagePath {
319                 intermediate_nodes: vec![],
320                 destination: Destination::BlindedPath(blinded_path),
321         };
322         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();
323
324         nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg), Some(reply_path)).unwrap();
325         pass_along_path(&nodes);
326         nodes[3].logger.assert_log_contains(
327                 "lightning::onion_message::messenger",
328                 &format!("Received an onion message with path_id None and a reply_path"), 2);
329 }
330
331 #[test]
332 fn invalid_custom_message_type() {
333         let nodes = create_nodes(2);
334
335         struct InvalidCustomMessage{}
336         impl CustomOnionMessageContents for InvalidCustomMessage {
337                 fn tlv_type(&self) -> u64 {
338                         // Onion message contents must have a TLV >= 64.
339                         63
340                 }
341         }
342
343         impl Writeable for InvalidCustomMessage {
344                 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> { unreachable!() }
345         }
346
347         let test_msg = OnionMessageContents::Custom(InvalidCustomMessage {});
348         let path = OnionMessagePath {
349                 intermediate_nodes: vec![],
350                 destination: Destination::Node(nodes[1].get_node_pk()),
351         };
352         let err = nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap_err();
353         assert_eq!(err, SendError::InvalidMessage);
354 }
355
356 #[test]
357 fn peer_buffer_full() {
358         let nodes = create_nodes(2);
359         let test_msg = TestCustomMessage {};
360         let path = OnionMessagePath {
361                 intermediate_nodes: vec![],
362                 destination: Destination::Node(nodes[1].get_node_pk()),
363         };
364         for _ in 0..188 { // Based on MAX_PER_PEER_BUFFER_SIZE in OnionMessenger
365                 nodes[0].messenger.send_onion_message(path.clone(), OnionMessageContents::Custom(test_msg.clone()), None).unwrap();
366         }
367         let err = nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg), None).unwrap_err();
368         assert_eq!(err, SendError::BufferFull);
369 }
370
371 #[test]
372 fn many_hops() {
373         // Check we can send over a route with many hops. This will exercise our logic for onion messages
374         // of size [`crate::onion_message::packet::BIG_PACKET_HOP_DATA_LEN`].
375         let num_nodes: usize = 25;
376         let nodes = create_nodes(num_nodes as u8);
377         let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
378
379         let mut intermediate_nodes = vec![];
380         for i in 1..(num_nodes-1) {
381                 intermediate_nodes.push(nodes[i].get_node_pk());
382         }
383
384         let path = OnionMessagePath {
385                 intermediate_nodes,
386                 destination: Destination::Node(nodes[num_nodes-1].get_node_pk()),
387         };
388         nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap();
389         pass_along_path(&nodes);
390 }