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