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