Merge pull request #2120 from valentinewallace/2023-03-blinded-pathfinding
[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 crate::io;
24 use crate::io_extras::read_to_end;
25 use crate::sync::{Arc, Mutex};
26
27 use crate::prelude::*;
28
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>
38         >,
39         custom_message_handler: Arc<TestCustomMessageHandler>,
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                 Ok(OnionMessagePath {
55                         intermediate_nodes: vec![],
56                         destination,
57                 })
58         }
59 }
60
61 struct TestOffersMessageHandler {}
62
63 impl OffersMessageHandler for TestOffersMessageHandler {
64         fn handle_message(&self, _message: OffersMessage) -> Option<OffersMessage> {
65                 None
66         }
67 }
68
69 #[derive(Clone, Debug, PartialEq)]
70 enum TestCustomMessage {
71         Request,
72         Response,
73 }
74
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];
79
80 impl CustomOnionMessageContents for TestCustomMessage {
81         fn tlv_type(&self) -> u64 {
82                 match self {
83                         TestCustomMessage::Request => CUSTOM_REQUEST_MESSAGE_TYPE,
84                         TestCustomMessage::Response => CUSTOM_RESPONSE_MESSAGE_TYPE,
85                 }
86         }
87 }
88
89 impl Writeable for TestCustomMessage {
90         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
91                 match self {
92                         TestCustomMessage::Request => Ok(CUSTOM_REQUEST_MESSAGE_CONTENTS.write(w)?),
93                         TestCustomMessage::Response => Ok(CUSTOM_RESPONSE_MESSAGE_CONTENTS.write(w)?),
94                 }
95         }
96 }
97
98 struct TestCustomMessageHandler {
99         expected_messages: Mutex<VecDeque<TestCustomMessage>>,
100 }
101
102 impl TestCustomMessageHandler {
103         fn new() -> Self {
104                 Self { expected_messages: Mutex::new(VecDeque::new()) }
105         }
106
107         fn expect_message(&self, message: TestCustomMessage) {
108                 self.expected_messages.lock().unwrap().push_back(message);
109         }
110 }
111
112 impl Drop for TestCustomMessageHandler {
113         fn drop(&mut self) {
114                 #[cfg(feature = "std")] {
115                         if std::thread::panicking() {
116                                 return;
117                         }
118                 }
119                 assert!(self.expected_messages.lock().unwrap().is_empty());
120         }
121 }
122
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),
129                 }
130
131                 match msg {
132                         TestCustomMessage::Request => Some(TestCustomMessage::Response),
133                         TestCustomMessage::Response => None,
134                 }
135         }
136         fn read_custom_message<R: io::Read>(&self, message_type: u64, buffer: &mut R) -> Result<Option<Self::CustomMessage>, DecodeError> where Self: Sized {
137                 match message_type {
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))
142                         },
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))
147                         },
148                         _ => Ok(None),
149                 }
150         }
151 }
152
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()
167                         ),
168                         custom_message_handler,
169                 });
170         }
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();
178         }
179         nodes
180 }
181
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();
186                 let onion_msg =  {
187                         let msgs = events.get(&node.get_node_pk()).unwrap();
188                         assert_eq!(msgs.len(), 1);
189                         msgs[0].clone()
190                 };
191                 node.messenger.handle_onion_message(&prev_node.get_node_pk(), &onion_msg);
192                 prev_node = node;
193         }
194 }
195
196 #[test]
197 fn one_hop() {
198         let nodes = create_nodes(2);
199         let test_msg = OnionMessageContents::Custom(TestCustomMessage::Response);
200
201         let path = OnionMessagePath {
202                 intermediate_nodes: vec![],
203                 destination: Destination::Node(nodes[1].get_node_pk()),
204         };
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);
208 }
209
210 #[test]
211 fn two_unblinded_hops() {
212         let nodes = create_nodes(3);
213         let test_msg = OnionMessageContents::Custom(TestCustomMessage::Response);
214
215         let path = OnionMessagePath {
216                 intermediate_nodes: vec![nodes[1].get_node_pk()],
217                 destination: Destination::Node(nodes[2].get_node_pk()),
218         };
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);
222 }
223
224 #[test]
225 fn two_unblinded_two_blinded() {
226         let nodes = create_nodes(5);
227         let test_msg = OnionMessageContents::Custom(TestCustomMessage::Response);
228
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),
234         };
235
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);
239 }
240
241 #[test]
242 fn three_blinded_hops() {
243         let nodes = create_nodes(4);
244         let test_msg = OnionMessageContents::Custom(TestCustomMessage::Response);
245
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),
251         };
252
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);
256 }
257
258 #[test]
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);
263
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),
269         };
270         let err = nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap_err();
271         assert_eq!(err, SendError::TooBigPacket);
272 }
273
274 #[test]
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;
280
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),
286         };
287
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);
291
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),
297         };
298         nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg), None).unwrap();
299         nodes[1].custom_message_handler.expect_message(TestCustomMessage::Response);
300         nodes.remove(2);
301         pass_along_path(&nodes);
302 }
303
304 #[test]
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;
309
310         // 0 hops
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),
317         };
318         let err = nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg.clone()), None).unwrap_err();
319         assert_eq!(err, SendError::TooFewBlindedHops);
320
321         // 1 hop
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),
328         };
329         let err = nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg), None).unwrap_err();
330         assert_eq!(err, SendError::TooFewBlindedHops);
331 }
332
333 #[test]
334 fn reply_path() {
335         let mut nodes = create_nodes(4);
336         let test_msg = TestCustomMessage::Request;
337         let secp_ctx = Secp256k1::new();
338
339         // Destination::Node
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()),
343         };
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);
350         nodes.reverse();
351         pass_along_path(&nodes);
352
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),
358         };
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();
360
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);
364
365         // Make sure the last node successfully decoded the reply path.
366         nodes[0].custom_message_handler.expect_message(TestCustomMessage::Response);
367         nodes.reverse();
368         pass_along_path(&nodes);
369 }
370
371 #[test]
372 fn invalid_custom_message_type() {
373         let nodes = create_nodes(2);
374
375         struct InvalidCustomMessage{}
376         impl CustomOnionMessageContents for InvalidCustomMessage {
377                 fn tlv_type(&self) -> u64 {
378                         // Onion message contents must have a TLV >= 64.
379                         63
380                 }
381         }
382
383         impl Writeable for InvalidCustomMessage {
384                 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> { unreachable!() }
385         }
386
387         let test_msg = OnionMessageContents::Custom(InvalidCustomMessage {});
388         let path = OnionMessagePath {
389                 intermediate_nodes: vec![],
390                 destination: Destination::Node(nodes[1].get_node_pk()),
391         };
392         let err = nodes[0].messenger.send_onion_message(path, test_msg, None).unwrap_err();
393         assert_eq!(err, SendError::InvalidMessage);
394 }
395
396 #[test]
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()),
403         };
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();
406         }
407         let err = nodes[0].messenger.send_onion_message(path, OnionMessageContents::Custom(test_msg), None).unwrap_err();
408         assert_eq!(err, SendError::BufferFull);
409 }
410
411 #[test]
412 fn many_hops() {
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;
418
419         let mut intermediate_nodes = vec![];
420         for i in 1..(num_nodes-1) {
421                 intermediate_nodes.push(nodes[i].get_node_pk());
422         }
423
424         let path = OnionMessagePath {
425                 intermediate_nodes,
426                 destination: Destination::Node(nodes[num_nodes-1].get_node_pk()),
427         };
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);
431 }