Onion messages: fix edge case where we are the introduction node
[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::chain::keysinterface::{KeysInterface, Recipient};
13 use crate::ln::features::InitFeatures;
14 use crate::ln::msgs::{self, DecodeError, OnionMessageHandler};
15 use super::{BlindedRoute, CustomOnionMessageContents, CustomOnionMessageHandler, Destination, OnionMessageContents, OnionMessenger, SendError};
16 use crate::util::enforcing_trait_impls::EnforcingSigner;
17 use crate::util::ser::{MaybeReadableArgs, 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::sync::Arc;
25
26 struct MessengerNode {
27         keys_manager: Arc<test_utils::TestKeysInterface>,
28         messenger: OnionMessenger<EnforcingSigner, Arc<test_utils::TestKeysInterface>, Arc<test_utils::TestLogger>, Arc<TestCustomMessageHandler>>,
29         logger: Arc<test_utils::TestLogger>,
30 }
31
32 impl MessengerNode {
33         fn get_node_pk(&self) -> PublicKey {
34                 let secp_ctx = Secp256k1::new();
35                 PublicKey::from_secret_key(&secp_ctx, &self.keys_manager.get_node_secret(Recipient::Node).unwrap())
36         }
37 }
38
39 #[derive(Clone)]
40 struct TestCustomMessage {}
41
42 const CUSTOM_MESSAGE_TYPE: u64 = 4242;
43 const CUSTOM_MESSAGE_CONTENTS: [u8; 32] = [42; 32];
44
45 impl CustomOnionMessageContents for TestCustomMessage {
46         fn tlv_type(&self) -> u64 {
47                 CUSTOM_MESSAGE_TYPE
48         }
49 }
50
51 impl Writeable for TestCustomMessage {
52         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
53                 Ok(CUSTOM_MESSAGE_CONTENTS.write(w)?)
54         }
55 }
56
57 impl MaybeReadableArgs<u64> for TestCustomMessage {
58         fn read<R: io::Read>(buffer: &mut R, message_type: u64) -> Result<Option<Self>, DecodeError> where Self: Sized {
59                 if message_type == CUSTOM_MESSAGE_TYPE {
60                         let mut buf = Vec::new();
61                         buffer.read_to_end(&mut buf)?;
62                         assert_eq!(buf, CUSTOM_MESSAGE_CONTENTS);
63                         return Ok(Some(TestCustomMessage {}))
64                 }
65                 Ok(None)
66         }
67 }
68
69 struct TestCustomMessageHandler {}
70
71 impl CustomOnionMessageHandler for TestCustomMessageHandler {
72         type CustomMessage = TestCustomMessage;
73         fn handle_custom_message(&self, _msg: Self::CustomMessage) {}
74 }
75
76 fn create_nodes(num_messengers: u8) -> Vec<MessengerNode> {
77         let mut nodes = Vec::new();
78         for i in 0..num_messengers {
79                 let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
80                 let seed = [i as u8; 32];
81                 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet));
82                 nodes.push(MessengerNode {
83                         keys_manager: keys_manager.clone(),
84                         messenger: OnionMessenger::new(keys_manager, logger.clone(), Arc::new(TestCustomMessageHandler {})),
85                         logger,
86                 });
87         }
88         for idx in 0..num_messengers - 1 {
89                 let i = idx as usize;
90                 let mut features = InitFeatures::empty();
91                 features.set_onion_messages_optional();
92                 let init_msg = msgs::Init { features, remote_network_address: None };
93                 nodes[i].messenger.peer_connected(&nodes[i + 1].get_node_pk(), &init_msg.clone()).unwrap();
94                 nodes[i + 1].messenger.peer_connected(&nodes[i].get_node_pk(), &init_msg.clone()).unwrap();
95         }
96         nodes
97 }
98
99 fn pass_along_path(path: &Vec<MessengerNode>, expected_path_id: Option<[u8; 32]>) {
100         let mut prev_node = &path[0];
101         let num_nodes = path.len();
102         for (idx, node) in path.into_iter().skip(1).enumerate() {
103                 let events = prev_node.messenger.release_pending_msgs();
104                 let onion_msg =  {
105                         let msgs = events.get(&node.get_node_pk()).unwrap();
106                         assert_eq!(msgs.len(), 1);
107                         msgs[0].clone()
108                 };
109                 node.messenger.handle_onion_message(&prev_node.get_node_pk(), &onion_msg);
110                 if idx == num_nodes - 1 {
111                         node.logger.assert_log_contains(
112                                 "lightning::onion_message::messenger".to_string(),
113                                 format!("Received an onion message with path_id: {:02x?}", expected_path_id).to_string(), 1);
114                 }
115                 prev_node = node;
116         }
117 }
118
119 #[test]
120 fn one_hop() {
121         let nodes = create_nodes(2);
122         let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
123
124         nodes[0].messenger.send_onion_message(&[], Destination::Node(nodes[1].get_node_pk()), test_msg, None).unwrap();
125         pass_along_path(&nodes, None);
126 }
127
128 #[test]
129 fn two_unblinded_hops() {
130         let nodes = create_nodes(3);
131         let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
132
133         nodes[0].messenger.send_onion_message(&[nodes[1].get_node_pk()], Destination::Node(nodes[2].get_node_pk()), test_msg, None).unwrap();
134         pass_along_path(&nodes, None);
135 }
136
137 #[test]
138 fn two_unblinded_two_blinded() {
139         let nodes = create_nodes(5);
140         let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
141
142         let secp_ctx = Secp256k1::new();
143         let blinded_route = BlindedRoute::new(&[nodes[3].get_node_pk(), nodes[4].get_node_pk()], &*nodes[4].keys_manager, &secp_ctx).unwrap();
144
145         nodes[0].messenger.send_onion_message(&[nodes[1].get_node_pk(), nodes[2].get_node_pk()], Destination::BlindedRoute(blinded_route), test_msg, None).unwrap();
146         pass_along_path(&nodes, None);
147 }
148
149 #[test]
150 fn three_blinded_hops() {
151         let nodes = create_nodes(4);
152         let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
153
154         let secp_ctx = Secp256k1::new();
155         let blinded_route = BlindedRoute::new(&[nodes[1].get_node_pk(), nodes[2].get_node_pk(), nodes[3].get_node_pk()], &*nodes[3].keys_manager, &secp_ctx).unwrap();
156
157         nodes[0].messenger.send_onion_message(&[], Destination::BlindedRoute(blinded_route), test_msg, None).unwrap();
158         pass_along_path(&nodes, None);
159 }
160
161 #[test]
162 fn too_big_packet_error() {
163         // Make sure we error as expected if a packet is too big to send.
164         let nodes = create_nodes(2);
165         let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
166
167         let hop_node_id = nodes[1].get_node_pk();
168         let hops = [hop_node_id; 400];
169         let err = nodes[0].messenger.send_onion_message(&hops, Destination::Node(hop_node_id), test_msg, None).unwrap_err();
170         assert_eq!(err, SendError::TooBigPacket);
171 }
172
173 #[test]
174 fn we_are_intro_node() {
175         // If we are sending straight to a blinded route and we are the introduction node, we need to
176         // advance the blinded route by 1 hop so the second hop is the new introduction node.
177         let nodes = create_nodes(3);
178         let test_msg = TestCustomMessage {};
179
180         let secp_ctx = Secp256k1::new();
181         let blinded_route = BlindedRoute::new(&[nodes[0].get_node_pk(), nodes[1].get_node_pk(), nodes[2].get_node_pk()], &*nodes[2].keys_manager, &secp_ctx).unwrap();
182
183         nodes[0].messenger.send_onion_message(&[], Destination::BlindedRoute(blinded_route), OnionMessageContents::Custom(test_msg.clone()), None).unwrap();
184         pass_along_path(&nodes, None);
185 }
186
187 #[test]
188 fn invalid_blinded_route_error() {
189         // Make sure we error as expected if a provided blinded route has 0 or 1 hops.
190         let nodes = create_nodes(3);
191         let test_msg = TestCustomMessage {};
192
193         // 0 hops
194         let secp_ctx = Secp256k1::new();
195         let mut blinded_route = BlindedRoute::new(&[nodes[1].get_node_pk(), nodes[2].get_node_pk()], &*nodes[2].keys_manager, &secp_ctx).unwrap();
196         blinded_route.blinded_hops.clear();
197         let err = nodes[0].messenger.send_onion_message(&[], Destination::BlindedRoute(blinded_route), OnionMessageContents::Custom(test_msg.clone()), None).unwrap_err();
198         assert_eq!(err, SendError::TooFewBlindedHops);
199
200         // 1 hop
201         let mut blinded_route = BlindedRoute::new(&[nodes[1].get_node_pk(), nodes[2].get_node_pk()], &*nodes[2].keys_manager, &secp_ctx).unwrap();
202         blinded_route.blinded_hops.remove(0);
203         assert_eq!(blinded_route.blinded_hops.len(), 1);
204         let err = nodes[0].messenger.send_onion_message(&[], Destination::BlindedRoute(blinded_route), OnionMessageContents::Custom(test_msg), None).unwrap_err();
205         assert_eq!(err, SendError::TooFewBlindedHops);
206 }
207
208 #[test]
209 fn reply_path() {
210         let nodes = create_nodes(4);
211         let test_msg = TestCustomMessage {};
212         let secp_ctx = Secp256k1::new();
213
214         // Destination::Node
215         let reply_path = BlindedRoute::new(&[nodes[2].get_node_pk(), nodes[1].get_node_pk(), nodes[0].get_node_pk()], &*nodes[0].keys_manager, &secp_ctx).unwrap();
216         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();
217         pass_along_path(&nodes, None);
218         // Make sure the last node successfully decoded the reply path.
219         nodes[3].logger.assert_log_contains(
220                 "lightning::onion_message::messenger".to_string(),
221                 format!("Received an onion message with path_id None and a reply_path").to_string(), 1);
222
223         // Destination::BlindedRoute
224         let blinded_route = BlindedRoute::new(&[nodes[1].get_node_pk(), nodes[2].get_node_pk(), nodes[3].get_node_pk()], &*nodes[3].keys_manager, &secp_ctx).unwrap();
225         let reply_path = BlindedRoute::new(&[nodes[2].get_node_pk(), nodes[1].get_node_pk(), nodes[0].get_node_pk()], &*nodes[0].keys_manager, &secp_ctx).unwrap();
226
227         nodes[0].messenger.send_onion_message(&[], Destination::BlindedRoute(blinded_route), OnionMessageContents::Custom(test_msg), Some(reply_path)).unwrap();
228         pass_along_path(&nodes, None);
229         nodes[3].logger.assert_log_contains(
230                 "lightning::onion_message::messenger".to_string(),
231                 format!("Received an onion message with path_id None and a reply_path").to_string(), 2);
232 }
233
234 #[test]
235 fn invalid_custom_message_type() {
236         let nodes = create_nodes(2);
237
238         struct InvalidCustomMessage{}
239         impl CustomOnionMessageContents for InvalidCustomMessage {
240                 fn tlv_type(&self) -> u64 {
241                         // Onion message contents must have a TLV >= 64.
242                         63
243                 }
244         }
245
246         impl Writeable for InvalidCustomMessage {
247                 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> { unreachable!() }
248         }
249
250         impl MaybeReadableArgs<u64> for InvalidCustomMessage {
251                 fn read<R: io::Read>(_buffer: &mut R, _message_type: u64) -> Result<Option<Self>, DecodeError> where Self: Sized {
252                         unreachable!()
253                 }
254         }
255
256         let test_msg = OnionMessageContents::Custom(InvalidCustomMessage {});
257         let err = nodes[0].messenger.send_onion_message(&[], Destination::Node(nodes[1].get_node_pk()), test_msg, None).unwrap_err();
258         assert_eq!(err, SendError::InvalidMessage);
259 }
260
261 #[test]
262 fn peer_buffer_full() {
263         let nodes = create_nodes(2);
264         let test_msg = TestCustomMessage {};
265         for _ in 0..188 { // Based on MAX_PER_PEER_BUFFER_SIZE in OnionMessenger
266                 nodes[0].messenger.send_onion_message(&[], Destination::Node(nodes[1].get_node_pk()), OnionMessageContents::Custom(test_msg.clone()), None).unwrap();
267         }
268         let err = nodes[0].messenger.send_onion_message(&[], Destination::Node(nodes[1].get_node_pk()), OnionMessageContents::Custom(test_msg), None).unwrap_err();
269         assert_eq!(err, SendError::BufferFull);
270 }