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