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 chain::keysinterface::{KeysInterface, Recipient};
13 use ln::features::InitFeatures;
14 use ln::msgs::{self, DecodeError, OnionMessageHandler};
15 use super::{BlindedRoute, CustomOnionMessageContents, CustomOnionMessageHandler, Destination, OnionMessenger, SendError};
16 use util::enforcing_trait_impls::EnforcingSigner;
17 use util::ser::{MaybeReadableArgs, Writeable, Writer};
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 impl MaybeReadableArgs<u64> for TestCustomMessage {
58 fn read<R: io::Read>(buffer: &mut R, message_type: u64) -> Result<Option<Self>, DecodeError> where Self: Sized {
59 if message_type == CUSTOM_MESSAGE_TYPE {
60 let mut buf = Vec::new();
61 buffer.read_to_end(&mut buf)?;
62 assert_eq!(buf, CUSTOM_MESSAGE_CONTENTS);
63 return Ok(Some(TestCustomMessage {}))
69 struct TestCustomMessageHandler {}
71 impl CustomOnionMessageHandler for TestCustomMessageHandler {
72 type CustomMessage = TestCustomMessage;
73 fn handle_custom_message(&self, _msg: Self::CustomMessage) {}
76 fn create_nodes(num_messengers: u8) -> Vec<MessengerNode> {
77 let mut nodes = Vec::new();
78 for i in 0..num_messengers {
79 let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
80 let seed = [i as u8; 32];
81 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet));
82 nodes.push(MessengerNode {
83 keys_manager: keys_manager.clone(),
84 messenger: OnionMessenger::new(keys_manager, logger.clone(), Arc::new(TestCustomMessageHandler {})),
88 for idx in 0..num_messengers - 1 {
90 let mut features = InitFeatures::empty();
91 features.set_onion_messages_optional();
92 let init_msg = msgs::Init { features, remote_network_address: None };
93 nodes[i].messenger.peer_connected(&nodes[i + 1].get_node_pk(), &init_msg.clone()).unwrap();
94 nodes[i + 1].messenger.peer_connected(&nodes[i].get_node_pk(), &init_msg.clone()).unwrap();
99 fn pass_along_path(path: &Vec<MessengerNode>, expected_path_id: Option<[u8; 32]>) {
100 let mut prev_node = &path[0];
101 let num_nodes = path.len();
102 for (idx, node) in path.into_iter().skip(1).enumerate() {
103 let events = prev_node.messenger.release_pending_msgs();
105 let msgs = events.get(&node.get_node_pk()).unwrap();
106 assert_eq!(msgs.len(), 1);
109 node.messenger.handle_onion_message(&prev_node.get_node_pk(), &onion_msg);
110 if idx == num_nodes - 1 {
111 node.logger.assert_log_contains(
112 "lightning::onion_message::messenger".to_string(),
113 format!("Received an onion message with path_id: {:02x?}", expected_path_id).to_string(), 1);
121 let nodes = create_nodes(2);
123 nodes[0].messenger.send_onion_message(&[], Destination::Node(nodes[1].get_node_pk()), None).unwrap();
124 pass_along_path(&nodes, None);
128 fn two_unblinded_hops() {
129 let nodes = create_nodes(3);
131 nodes[0].messenger.send_onion_message(&[nodes[1].get_node_pk()], Destination::Node(nodes[2].get_node_pk()), None).unwrap();
132 pass_along_path(&nodes, None);
136 fn two_unblinded_two_blinded() {
137 let nodes = create_nodes(5);
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), None).unwrap();
143 pass_along_path(&nodes, None);
147 fn three_blinded_hops() {
148 let nodes = create_nodes(4);
150 let secp_ctx = Secp256k1::new();
151 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 nodes[0].messenger.send_onion_message(&[], Destination::BlindedRoute(blinded_route), None).unwrap();
154 pass_along_path(&nodes, None);
158 fn too_big_packet_error() {
159 // Make sure we error as expected if a packet is too big to send.
160 let nodes = create_nodes(2);
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), None).unwrap_err();
165 assert_eq!(err, SendError::TooBigPacket);
169 fn invalid_blinded_route_error() {
170 // Make sure we error as expected if a provided blinded route has 0 or 1 hops.
171 let nodes = create_nodes(3);
174 let secp_ctx = Secp256k1::new();
175 let mut blinded_route = BlindedRoute::new(&[nodes[1].get_node_pk(), nodes[2].get_node_pk()], &*nodes[2].keys_manager, &secp_ctx).unwrap();
176 blinded_route.blinded_hops.clear();
177 let err = nodes[0].messenger.send_onion_message(&[], Destination::BlindedRoute(blinded_route), None).unwrap_err();
178 assert_eq!(err, SendError::TooFewBlindedHops);
181 let mut blinded_route = BlindedRoute::new(&[nodes[1].get_node_pk(), nodes[2].get_node_pk()], &*nodes[2].keys_manager, &secp_ctx).unwrap();
182 blinded_route.blinded_hops.remove(0);
183 assert_eq!(blinded_route.blinded_hops.len(), 1);
184 let err = nodes[0].messenger.send_onion_message(&[], Destination::BlindedRoute(blinded_route), None).unwrap_err();
185 assert_eq!(err, SendError::TooFewBlindedHops);
190 let nodes = create_nodes(4);
191 let secp_ctx = Secp256k1::new();
194 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();
195 nodes[0].messenger.send_onion_message(&[nodes[1].get_node_pk(), nodes[2].get_node_pk()], Destination::Node(nodes[3].get_node_pk()), Some(reply_path)).unwrap();
196 pass_along_path(&nodes, None);
197 // Make sure the last node successfully decoded the reply path.
198 nodes[3].logger.assert_log_contains(
199 "lightning::onion_message::messenger".to_string(),
200 format!("Received an onion message with path_id: None and reply_path").to_string(), 1);
202 // Destination::BlindedRoute
203 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();
204 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();
206 nodes[0].messenger.send_onion_message(&[], Destination::BlindedRoute(blinded_route), Some(reply_path)).unwrap();
207 pass_along_path(&nodes, None);
208 nodes[3].logger.assert_log_contains(
209 "lightning::onion_message::messenger".to_string(),
210 format!("Received an onion message with path_id: None and reply_path").to_string(), 2);
214 fn peer_buffer_full() {
215 let nodes = create_nodes(2);
216 for _ in 0..188 { // Based on MAX_PER_PEER_BUFFER_SIZE in OnionMessenger
217 nodes[0].messenger.send_onion_message(&[], Destination::Node(nodes[1].get_node_pk()), None).unwrap();
219 let err = nodes[0].messenger.send_onion_message(&[], Destination::Node(nodes[1].get_node_pk()), None).unwrap_err();
220 assert_eq!(err, SendError::BufferFull);