Add boilerplate for sending and receiving onion messages in PeerManager
[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 chain::keysinterface::{KeysInterface, Recipient};
13 use ln::msgs::OnionMessageHandler;
14 use super::{BlindedRoute, Destination, OnionMessenger, SendError};
15 use util::enforcing_trait_impls::EnforcingSigner;
16 use util::test_utils;
17
18 use bitcoin::network::constants::Network;
19 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
20
21 use sync::Arc;
22
23 struct MessengerNode {
24         keys_manager: Arc<test_utils::TestKeysInterface>,
25         messenger: OnionMessenger<EnforcingSigner, Arc<test_utils::TestKeysInterface>, Arc<test_utils::TestLogger>>,
26         logger: Arc<test_utils::TestLogger>,
27 }
28
29 impl MessengerNode {
30         fn get_node_pk(&self) -> PublicKey {
31                 let secp_ctx = Secp256k1::new();
32                 PublicKey::from_secret_key(&secp_ctx, &self.keys_manager.get_node_secret(Recipient::Node).unwrap())
33         }
34 }
35
36 fn create_nodes(num_messengers: u8) -> Vec<MessengerNode> {
37         let mut res = Vec::new();
38         for i in 0..num_messengers {
39                 let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
40                 let seed = [i as u8; 32];
41                 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet));
42                 res.push(MessengerNode {
43                         keys_manager: keys_manager.clone(),
44                         messenger: OnionMessenger::new(keys_manager, logger.clone()),
45                         logger,
46                 });
47         }
48         res
49 }
50
51 fn pass_along_path(path: &Vec<MessengerNode>, expected_path_id: Option<[u8; 32]>) {
52         let mut prev_node = &path[0];
53         let num_nodes = path.len();
54         for (idx, node) in path.into_iter().skip(1).enumerate() {
55                 let events = prev_node.messenger.release_pending_msgs();
56                 assert_eq!(events.len(), 1);
57                 let onion_msg =  {
58                         let msgs = events.get(&node.get_node_pk()).unwrap();
59                         assert_eq!(msgs.len(), 1);
60                         msgs[0].clone()
61                 };
62                 node.messenger.handle_onion_message(&prev_node.get_node_pk(), &onion_msg);
63                 if idx == num_nodes - 1 {
64                         node.logger.assert_log_contains(
65                                 "lightning::onion_message::messenger".to_string(),
66                                 format!("Received an onion message with path_id: {:02x?}", expected_path_id).to_string(), 1);
67                 }
68                 prev_node = node;
69         }
70 }
71
72 #[test]
73 fn one_hop() {
74         let nodes = create_nodes(2);
75
76         nodes[0].messenger.send_onion_message(&[], Destination::Node(nodes[1].get_node_pk()), None).unwrap();
77         pass_along_path(&nodes, None);
78 }
79
80 #[test]
81 fn two_unblinded_hops() {
82         let nodes = create_nodes(3);
83
84         nodes[0].messenger.send_onion_message(&[nodes[1].get_node_pk()], Destination::Node(nodes[2].get_node_pk()), None).unwrap();
85         pass_along_path(&nodes, None);
86 }
87
88 #[test]
89 fn two_unblinded_two_blinded() {
90         let nodes = create_nodes(5);
91
92         let secp_ctx = Secp256k1::new();
93         let blinded_route = BlindedRoute::new::<EnforcingSigner, _, _>(&[nodes[3].get_node_pk(), nodes[4].get_node_pk()], &*nodes[4].keys_manager, &secp_ctx).unwrap();
94
95         nodes[0].messenger.send_onion_message(&[nodes[1].get_node_pk(), nodes[2].get_node_pk()], Destination::BlindedRoute(blinded_route), None).unwrap();
96         pass_along_path(&nodes, None);
97 }
98
99 #[test]
100 fn three_blinded_hops() {
101         let nodes = create_nodes(4);
102
103         let secp_ctx = Secp256k1::new();
104         let blinded_route = BlindedRoute::new::<EnforcingSigner, _, _>(&[nodes[1].get_node_pk(), nodes[2].get_node_pk(), nodes[3].get_node_pk()], &*nodes[3].keys_manager, &secp_ctx).unwrap();
105
106         nodes[0].messenger.send_onion_message(&[], Destination::BlindedRoute(blinded_route), None).unwrap();
107         pass_along_path(&nodes, None);
108 }
109
110 #[test]
111 fn too_big_packet_error() {
112         // Make sure we error as expected if a packet is too big to send.
113         let nodes = create_nodes(1);
114
115         let hop_secret = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
116         let secp_ctx = Secp256k1::new();
117         let hop_node_id = PublicKey::from_secret_key(&secp_ctx, &hop_secret);
118
119         let hops = [hop_node_id; 400];
120         let err = nodes[0].messenger.send_onion_message(&hops, Destination::Node(hop_node_id), None).unwrap_err();
121         assert_eq!(err, SendError::TooBigPacket);
122 }
123
124 #[test]
125 fn invalid_blinded_route_error() {
126         // Make sure we error as expected if a provided blinded route has 0 or 1 hops.
127         let mut nodes = create_nodes(3);
128
129         // 0 hops
130         let secp_ctx = Secp256k1::new();
131         let mut blinded_route = BlindedRoute::new::<EnforcingSigner, _, _>(&[nodes[1].get_node_pk(), nodes[2].get_node_pk()], &*nodes[2].keys_manager, &secp_ctx).unwrap();
132         blinded_route.blinded_hops.clear();
133         let err = nodes[0].messenger.send_onion_message(&[], Destination::BlindedRoute(blinded_route), None).unwrap_err();
134         assert_eq!(err, SendError::TooFewBlindedHops);
135
136         // 1 hop
137         let mut blinded_route = BlindedRoute::new::<EnforcingSigner, _, _>(&[nodes[1].get_node_pk(), nodes[2].get_node_pk()], &*nodes[2].keys_manager, &secp_ctx).unwrap();
138         blinded_route.blinded_hops.remove(0);
139         assert_eq!(blinded_route.blinded_hops.len(), 1);
140         let err = nodes[0].messenger.send_onion_message(&[], Destination::BlindedRoute(blinded_route), None).unwrap_err();
141         assert_eq!(err, SendError::TooFewBlindedHops);
142 }
143
144 #[test]
145 fn reply_path() {
146         let mut nodes = create_nodes(4);
147         let secp_ctx = Secp256k1::new();
148
149         // Destination::Node
150         let reply_path = BlindedRoute::new::<EnforcingSigner, _, _>(&[nodes[2].get_node_pk(), nodes[1].get_node_pk(), nodes[0].get_node_pk()], &*nodes[0].keys_manager, &secp_ctx).unwrap();
151         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();
152         pass_along_path(&nodes, None);
153         // Make sure the last node successfully decoded the reply path.
154         nodes[3].logger.assert_log_contains(
155                 "lightning::onion_message::messenger".to_string(),
156                 format!("Received an onion message with path_id: None and reply_path").to_string(), 1);
157
158         // Destination::BlindedRoute
159         let blinded_route = BlindedRoute::new::<EnforcingSigner, _, _>(&[nodes[1].get_node_pk(), nodes[2].get_node_pk(), nodes[3].get_node_pk()], &*nodes[3].keys_manager, &secp_ctx).unwrap();
160         let reply_path = BlindedRoute::new::<EnforcingSigner, _, _>(&[nodes[2].get_node_pk(), nodes[1].get_node_pk(), nodes[0].get_node_pk()], &*nodes[0].keys_manager, &secp_ctx).unwrap();
161
162         nodes[0].messenger.send_onion_message(&[], Destination::BlindedRoute(blinded_route), Some(reply_path)).unwrap();
163         pass_along_path(&nodes, None);
164         nodes[3].logger.assert_log_contains(
165                 "lightning::onion_message::messenger".to_string(),
166                 format!("Received an onion message with path_id: None and reply_path").to_string(), 2);
167 }