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