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