Prune channels if *either* not updated
[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<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 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 invalid_blinded_route_error() {
172         // Make sure we error as expected if a provided blinded route has 0 or 1 hops.
173         let nodes = create_nodes(3);
174         let test_msg = TestCustomMessage {};
175
176         // 0 hops
177         let secp_ctx = Secp256k1::new();
178         let mut blinded_route = BlindedRoute::new(&[nodes[1].get_node_pk(), nodes[2].get_node_pk()], &*nodes[2].keys_manager, &secp_ctx).unwrap();
179         blinded_route.blinded_hops.clear();
180         let err = nodes[0].messenger.send_onion_message(&[], Destination::BlindedRoute(blinded_route), OnionMessageContents::Custom(test_msg.clone()), None).unwrap_err();
181         assert_eq!(err, SendError::TooFewBlindedHops);
182
183         // 1 hop
184         let mut blinded_route = BlindedRoute::new(&[nodes[1].get_node_pk(), nodes[2].get_node_pk()], &*nodes[2].keys_manager, &secp_ctx).unwrap();
185         blinded_route.blinded_hops.remove(0);
186         assert_eq!(blinded_route.blinded_hops.len(), 1);
187         let err = nodes[0].messenger.send_onion_message(&[], Destination::BlindedRoute(blinded_route), OnionMessageContents::Custom(test_msg), None).unwrap_err();
188         assert_eq!(err, SendError::TooFewBlindedHops);
189 }
190
191 #[test]
192 fn reply_path() {
193         let nodes = create_nodes(4);
194         let test_msg = TestCustomMessage {};
195         let secp_ctx = Secp256k1::new();
196
197         // Destination::Node
198         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();
199         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();
200         pass_along_path(&nodes, None);
201         // Make sure the last node successfully decoded the reply path.
202         nodes[3].logger.assert_log_contains(
203                 "lightning::onion_message::messenger".to_string(),
204                 format!("Received an onion message with path_id None and a reply_path").to_string(), 1);
205
206         // Destination::BlindedRoute
207         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();
208         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();
209
210         nodes[0].messenger.send_onion_message(&[], Destination::BlindedRoute(blinded_route), OnionMessageContents::Custom(test_msg), Some(reply_path)).unwrap();
211         pass_along_path(&nodes, None);
212         nodes[3].logger.assert_log_contains(
213                 "lightning::onion_message::messenger".to_string(),
214                 format!("Received an onion message with path_id None and a reply_path").to_string(), 2);
215 }
216
217 #[test]
218 fn invalid_custom_message_type() {
219         let nodes = create_nodes(2);
220
221         struct InvalidCustomMessage{}
222         impl CustomOnionMessageContents for InvalidCustomMessage {
223                 fn tlv_type(&self) -> u64 {
224                         // Onion message contents must have a TLV >= 64.
225                         63
226                 }
227         }
228
229         impl Writeable for InvalidCustomMessage {
230                 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> { unreachable!() }
231         }
232
233         let test_msg = OnionMessageContents::Custom(InvalidCustomMessage {});
234         let err = nodes[0].messenger.send_onion_message(&[], Destination::Node(nodes[1].get_node_pk()), test_msg, None).unwrap_err();
235         assert_eq!(err, SendError::InvalidMessage);
236 }
237
238 #[test]
239 fn peer_buffer_full() {
240         let nodes = create_nodes(2);
241         let test_msg = TestCustomMessage {};
242         for _ in 0..188 { // Based on MAX_PER_PEER_BUFFER_SIZE in OnionMessenger
243                 nodes[0].messenger.send_onion_message(&[], Destination::Node(nodes[1].get_node_pk()), OnionMessageContents::Custom(test_msg.clone()), None).unwrap();
244         }
245         let err = nodes[0].messenger.send_onion_message(&[], Destination::Node(nodes[1].get_node_pk()), OnionMessageContents::Custom(test_msg), None).unwrap_err();
246         assert_eq!(err, SendError::BufferFull);
247 }