1 // This file is Copyright its original authors, visible in version control
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
10 //! Onion message testing and test utilities live here.
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;
20 use bitcoin::network::constants::Network;
21 use bitcoin::secp256k1::{PublicKey, Secp256k1};
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>,
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())
40 struct TestCustomMessage {}
42 const CUSTOM_MESSAGE_TYPE: u64 = 4242;
43 const CUSTOM_MESSAGE_CONTENTS: [u8; 32] = [42; 32];
45 impl CustomOnionMessageContents for TestCustomMessage {
46 fn tlv_type(&self) -> u64 {
51 impl Writeable for TestCustomMessage {
52 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
53 Ok(CUSTOM_MESSAGE_CONTENTS.write(w)?)
57 struct TestCustomMessageHandler {}
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 {}))
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 {})),
85 for idx in 0..num_messengers - 1 {
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();
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();
102 let msgs = events.get(&node.get_node_pk()).unwrap();
103 assert_eq!(msgs.len(), 1);
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);
118 let nodes = create_nodes(2);
119 let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
121 nodes[0].messenger.send_onion_message(&[], Destination::Node(nodes[1].get_node_pk()), test_msg, None).unwrap();
122 pass_along_path(&nodes, None);
126 fn two_unblinded_hops() {
127 let nodes = create_nodes(3);
128 let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
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);
135 fn two_unblinded_two_blinded() {
136 let nodes = create_nodes(5);
137 let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
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();
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);
147 fn three_blinded_hops() {
148 let nodes = create_nodes(4);
149 let test_msg = OnionMessageContents::Custom(TestCustomMessage {});
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();
154 nodes[0].messenger.send_onion_message(&[], Destination::BlindedRoute(blinded_route), test_msg, None).unwrap();
155 pass_along_path(&nodes, None);
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 {});
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);
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 {};
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();
180 nodes[0].messenger.send_onion_message(&[], Destination::BlindedRoute(blinded_route), OnionMessageContents::Custom(test_msg.clone()), None).unwrap();
181 pass_along_path(&nodes, None);
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();
187 pass_along_path(&nodes, None);
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 {};
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);
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);
213 let nodes = create_nodes(4);
214 let test_msg = TestCustomMessage {};
215 let secp_ctx = Secp256k1::new();
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);
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();
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);
238 fn invalid_custom_message_type() {
239 let nodes = create_nodes(2);
241 struct InvalidCustomMessage{}
242 impl CustomOnionMessageContents for InvalidCustomMessage {
243 fn tlv_type(&self) -> u64 {
244 // Onion message contents must have a TLV >= 64.
249 impl Writeable for InvalidCustomMessage {
250 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> { unreachable!() }
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);
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();
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);