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