Re-order imports
[rust-lightning] / lightning / src / ln / max_payment_path_len_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 //! Tests for calculating the maximum length of a path based on the payment metadata, custom TLVs,
11 //! and/or blinded paths present.
12
13 use bitcoin::secp256k1::Secp256k1;
14 use crate::blinded_path::BlindedPath;
15 use crate::blinded_path::payment::{PaymentConstraints, PaymentContext, ReceiveTlvs};
16 use crate::events::MessageSendEventsProvider;
17 use crate::ln::PaymentSecret;
18 use crate::ln::blinded_payment_tests::get_blinded_route_parameters;
19 use crate::ln::channelmanager::PaymentId;
20 use crate::ln::functional_test_utils::*;
21 use crate::ln::msgs;
22 use crate::ln::onion_utils;
23 use crate::ln::onion_utils::MIN_FINAL_VALUE_ESTIMATE_WITH_OVERPAY;
24 use crate::ln::outbound_payment::{RecipientOnionFields, Retry, RetryableSendFailure};
25 use crate::prelude::*;
26 use crate::routing::router::{DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, PaymentParameters, RouteParameters};
27 use crate::util::errors::APIError;
28 use crate::util::ser::Writeable;
29 use crate::util::test_utils;
30
31 // 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) +
32 // 2+4 (outgoing_cltv_value) + 2+8 (short_channel_id)
33 const INTERMED_PAYLOAD_LEN_ESTIMATE: usize = 61;
34
35 // Length of the HMAC of an onion payload when encoded into the packet.
36 const PAYLOAD_HMAC_LEN: usize = 32;
37
38 #[test]
39 fn large_payment_metadata() {
40         // Test that we'll limit our maximum path length based on the size of the provided
41         // payment_metadata, and refuse to send at all prior to pathfinding if it's too large.
42         let chanmon_cfgs = create_chanmon_cfgs(3);
43         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
44         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
45         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
46         create_announced_chan_between_nodes(&nodes, 0, 1);
47         create_announced_chan_between_nodes(&nodes, 1, 2);
48
49         let amt_msat = 100_000;
50
51         // Construct payment_metadata such that we can send the payment to the next hop but no further
52         // without exceeding the max onion packet size.
53         let final_payload_len_without_metadata = msgs::OutboundOnionPayload::Receive {
54                 payment_data: Some(msgs::FinalOnionHopData {
55                         payment_secret: PaymentSecret([0; 32]), total_msat: MIN_FINAL_VALUE_ESTIMATE_WITH_OVERPAY
56                 }),
57                 payment_metadata: None,
58                 keysend_preimage: None,
59                 custom_tlvs: &Vec::new(),
60                 sender_intended_htlc_amt_msat: MIN_FINAL_VALUE_ESTIMATE_WITH_OVERPAY,
61                 cltv_expiry_height: nodes[0].best_block_info().1 + DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
62         }.serialized_length();
63         let max_metadata_len = 1300
64                 - 1 // metadata type
65                 - crate::util::ser::BigSize(1200).serialized_length() // metadata length
66                 - 2 // onion payload varint prefix increased ser size due to metadata
67                 - PAYLOAD_HMAC_LEN
68                 - final_payload_len_without_metadata;
69         let mut payment_metadata = vec![42; max_metadata_len];
70
71         // Check that the maximum-size metadata is sendable.
72         let (mut route_0_1, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], &nodes[1], amt_msat);
73         let mut recipient_onion_max_md_size = RecipientOnionFields {
74                 payment_secret: Some(payment_secret),
75                 payment_metadata: Some(payment_metadata.clone()),
76                 custom_tlvs: Vec::new(),
77         };
78         nodes[0].node.send_payment(payment_hash, recipient_onion_max_md_size.clone(), PaymentId(payment_hash.0), route_0_1.route_params.clone().unwrap(), Retry::Attempts(0)).unwrap();
79         check_added_monitors!(nodes[0], 1);
80         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
81         assert_eq!(events.len(), 1);
82         let path = &[&nodes[1]];
83         let args = PassAlongPathArgs::new(&nodes[0], path, amt_msat, payment_hash, events.pop().unwrap())
84                 .with_payment_secret(payment_secret)
85                 .with_payment_metadata(payment_metadata.clone());
86         do_pass_along_path(args);
87         claim_payment_along_route(
88                 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1]]], payment_preimage)
89         );
90
91         // Check that the payment parameter for max path length will prevent us from routing past our
92         // next-hop peer given the payment_metadata size.
93         let (mut route_0_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(&nodes[0], &nodes[2], amt_msat);
94         let mut route_params_0_2 = route_0_2.route_params.clone().unwrap();
95         route_params_0_2.payment_params.max_path_length = 1;
96         nodes[0].router.expect_find_route_query(route_params_0_2);
97         let err = nodes[0].node.send_payment(payment_hash_2, recipient_onion_max_md_size.clone(), PaymentId(payment_hash_2.0), route_0_2.route_params.clone().unwrap(), Retry::Attempts(0)).unwrap_err();
98         assert_eq!(err, RetryableSendFailure::RouteNotFound);
99
100         // If our payment_metadata contains 1 additional byte, we'll fail prior to pathfinding.
101         let mut recipient_onion_too_large_md = recipient_onion_max_md_size.clone();
102         recipient_onion_too_large_md.payment_metadata.as_mut().map(|mut md| md.push(42));
103         let err = nodes[0].node.send_payment(payment_hash, recipient_onion_too_large_md.clone(), PaymentId(payment_hash.0), route_0_1.route_params.clone().unwrap(), Retry::Attempts(0)).unwrap_err();
104         assert_eq!(err, RetryableSendFailure::OnionPacketSizeExceeded);
105
106         // Confirm that we'll fail to construct an onion packet given this payment_metadata that's too
107         // large for even a 1-hop path.
108         let secp_ctx = Secp256k1::signing_only();
109         route_0_1.paths[0].hops[0].fee_msat = MIN_FINAL_VALUE_ESTIMATE_WITH_OVERPAY;
110         route_0_1.paths[0].hops[0].cltv_expiry_delta = DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA;
111         let err = onion_utils::create_payment_onion(&secp_ctx, &route_0_1.paths[0], &test_utils::privkey(42), MIN_FINAL_VALUE_ESTIMATE_WITH_OVERPAY, &recipient_onion_too_large_md, nodes[0].best_block_info().1 + DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, &payment_hash, &None, [0; 32]).unwrap_err();
112         match err {
113                 APIError::InvalidRoute { err } => {
114                         assert_eq!(err, "Route size too large considering onion data");
115                 },
116                 _ => panic!(),
117         }
118
119         // If we remove enough payment_metadata bytes to allow for 2 hops, we're now able to send to
120         // nodes[2].
121         let mut recipient_onion_allows_2_hops = RecipientOnionFields {
122                 payment_secret: Some(payment_secret_2),
123                 payment_metadata: Some(vec![42; max_metadata_len - INTERMED_PAYLOAD_LEN_ESTIMATE]),
124                 custom_tlvs: Vec::new(),
125         };
126         let mut route_params_0_2 = route_0_2.route_params.clone().unwrap();
127         route_params_0_2.payment_params.max_path_length = 2;
128         nodes[0].router.expect_find_route_query(route_params_0_2);
129         nodes[0].node.send_payment(payment_hash_2, recipient_onion_allows_2_hops.clone(), PaymentId(payment_hash_2.0), route_0_2.route_params.unwrap(), Retry::Attempts(0)).unwrap();
130         check_added_monitors!(nodes[0], 1);
131         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
132         assert_eq!(events.len(), 1);
133         let path = &[&nodes[1], &nodes[2]];
134         let args = PassAlongPathArgs::new(&nodes[0], path, amt_msat, payment_hash_2, events.pop().unwrap())
135                 .with_payment_secret(payment_secret_2)
136                 .with_payment_metadata(recipient_onion_allows_2_hops.payment_metadata.unwrap());
137         do_pass_along_path(args);
138         claim_payment_along_route(
139                 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1], &nodes[2]]], payment_preimage_2)
140         );
141 }
142
143 #[test]
144 fn one_hop_blinded_path_with_custom_tlv() {
145         // Test that we'll limit our maximum path length when paying to a 1-hop blinded path based on the
146         // size of the provided custom TLV, and refuse to send at all prior to pathfinding if it's too
147         // large.
148         let chanmon_cfgs = create_chanmon_cfgs(3);
149         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
150         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
151         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
152         create_announced_chan_between_nodes(&nodes, 0, 1);
153         let chan_upd_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0).0.contents;
154
155         // Construct the route parameters for sending to nodes[2]'s 1-hop blinded path.
156         let amt_msat = 100_000;
157         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[2], Some(amt_msat), None);
158         let payee_tlvs = ReceiveTlvs {
159                 payment_secret,
160                 payment_constraints: PaymentConstraints {
161                         max_cltv_expiry: u32::max_value(),
162                         htlc_minimum_msat: chan_upd_1_2.htlc_minimum_msat,
163                 },
164                 payment_context: PaymentContext::unknown(),
165         };
166         let mut secp_ctx = Secp256k1::new();
167         let blinded_path = BlindedPath::one_hop_for_payment(
168                 nodes[2].node.get_our_node_id(), payee_tlvs, TEST_FINAL_CLTV as u16,
169                 &chanmon_cfgs[2].keys_manager, &secp_ctx
170         ).unwrap();
171         let route_params = RouteParameters::from_payment_params_and_value(
172                 PaymentParameters::blinded(vec![blinded_path.clone()]),
173                 amt_msat,
174         );
175
176         // Calculate the maximum custom TLV value size where a valid onion packet is still possible.
177         const CUSTOM_TLV_TYPE: u64 = 65537;
178         let final_payload_len_without_custom_tlv = msgs::OutboundOnionPayload::BlindedReceive {
179                 sender_intended_htlc_amt_msat: MIN_FINAL_VALUE_ESTIMATE_WITH_OVERPAY,
180                 total_msat: MIN_FINAL_VALUE_ESTIMATE_WITH_OVERPAY,
181                 cltv_expiry_height: nodes[0].best_block_info().1 + DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
182                 encrypted_tlvs: &blinded_path.1.blinded_hops[0].encrypted_payload,
183                 intro_node_blinding_point: Some(blinded_path.1.blinding_point),
184                 keysend_preimage: None,
185                 custom_tlvs: &Vec::new()
186         }.serialized_length();
187         let max_custom_tlv_len = 1300
188                 - crate::util::ser::BigSize(CUSTOM_TLV_TYPE).serialized_length() // custom TLV type
189                 - crate::util::ser::BigSize(1200).serialized_length() // custom TLV length
190                 - 1 // onion payload varint prefix increased ser size due to custom TLV
191                 - PAYLOAD_HMAC_LEN
192                 - final_payload_len_without_custom_tlv;
193
194         // Check that we can send the maximum custom TLV with 1 blinded hop.
195         let recipient_onion_max_custom_tlv_size = RecipientOnionFields::spontaneous_empty()
196                 .with_custom_tlvs(vec![(CUSTOM_TLV_TYPE, vec![42; max_custom_tlv_len])])
197                 .unwrap();
198         nodes[1].node.send_payment(payment_hash, recipient_onion_max_custom_tlv_size.clone(), PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0)).unwrap();
199         check_added_monitors(&nodes[1], 1);
200
201         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
202         assert_eq!(events.len(), 1);
203         let path = &[&nodes[2]];
204         let args = PassAlongPathArgs::new(&nodes[1], path, amt_msat, payment_hash, events.pop().unwrap())
205                 .with_payment_secret(payment_secret)
206                 .with_custom_tlvs(recipient_onion_max_custom_tlv_size.custom_tlvs.clone());
207         do_pass_along_path(args);
208         claim_payment_along_route(
209                 ClaimAlongRouteArgs::new(&nodes[1], &[&[&nodes[2]]], payment_preimage)
210                         .with_custom_tlvs(recipient_onion_max_custom_tlv_size.custom_tlvs.clone())
211         );
212
213         // If 1 byte is added to the custom TLV value, we'll fail to send prior to pathfinding.
214         let mut recipient_onion_too_large_custom_tlv = recipient_onion_max_custom_tlv_size.clone();
215         recipient_onion_too_large_custom_tlv.custom_tlvs[0].1.push(42);
216         let err = nodes[1].node.send_payment(payment_hash, recipient_onion_too_large_custom_tlv, PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0)).unwrap_err();
217         assert_eq!(err, RetryableSendFailure::OnionPacketSizeExceeded);
218
219         // With the maximum-size custom TLV, our max path length is limited to 1, so attempting to route
220         // nodes[0] -> nodes[2] will fail.
221         let err = nodes[0].node.send_payment(payment_hash, recipient_onion_max_custom_tlv_size.clone(), PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0)).unwrap_err();
222         assert_eq!(err, RetryableSendFailure::RouteNotFound);
223
224         // If we remove enough custom TLV bytes to allow for 1 intermediate unblinded hop, we're now able
225         // to send nodes[0] -> nodes[2].
226         let mut recipient_onion_allows_2_hops = recipient_onion_max_custom_tlv_size.clone();
227         recipient_onion_allows_2_hops.custom_tlvs[0].1.resize(max_custom_tlv_len - INTERMED_PAYLOAD_LEN_ESTIMATE, 0);
228         nodes[0].node.send_payment(payment_hash, recipient_onion_allows_2_hops.clone(), PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0)).unwrap();
229         check_added_monitors(&nodes[0], 1);
230
231         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
232         assert_eq!(events.len(), 1);
233         let path = &[&nodes[1], &nodes[2]];
234         let args = PassAlongPathArgs::new(&nodes[0], path, amt_msat, payment_hash, events.pop().unwrap())
235                 .with_payment_secret(payment_secret)
236                 .with_custom_tlvs(recipient_onion_allows_2_hops.custom_tlvs.clone());
237         do_pass_along_path(args);
238         claim_payment_along_route(
239                 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1], &nodes[2]]], payment_preimage)
240                         .with_custom_tlvs(recipient_onion_allows_2_hops.custom_tlvs)
241         );
242 }
243
244 #[test]
245 fn blinded_path_with_custom_tlv() {
246         // Test that we'll limit our maximum path length when paying to a blinded path based on the size
247         // of the provided custom TLV, and refuse to send at all prior to pathfinding if it's too large.
248         let chanmon_cfgs = create_chanmon_cfgs(4);
249         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
250         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
251         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
252         create_announced_chan_between_nodes(&nodes, 0, 1);
253         create_announced_chan_between_nodes(&nodes, 1, 2);
254         let chan_upd_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).0.contents;
255
256         // Construct the route parameters for sending to nodes[3]'s blinded path.
257         let amt_msat = 100_000;
258         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[3], Some(amt_msat), None);
259         let route_params = get_blinded_route_parameters(amt_msat, payment_secret, 1, 1_0000_0000,
260                 nodes.iter().skip(2).map(|n| n.node.get_our_node_id()).collect(), &[&chan_upd_2_3],
261                 &chanmon_cfgs[3].keys_manager);
262
263         // Calculate the maximum custom TLV value size where a valid onion packet is still possible.
264         const CUSTOM_TLV_TYPE: u64 = 65537;
265         let mut route = get_route(&nodes[1], &route_params).unwrap();
266         let reserved_packet_bytes_without_custom_tlv: usize = onion_utils::build_onion_payloads(
267                 &route.paths[0], MIN_FINAL_VALUE_ESTIMATE_WITH_OVERPAY,
268                 &RecipientOnionFields::spontaneous_empty(),
269                 nodes[0].best_block_info().1 + DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, &None
270         )
271                 .unwrap()
272                 .0
273                 .iter()
274                 .map(|payload| payload.serialized_length() + PAYLOAD_HMAC_LEN)
275                 .sum();
276         let max_custom_tlv_len = 1300
277                 - crate::util::ser::BigSize(CUSTOM_TLV_TYPE).serialized_length() // custom TLV type
278                 - crate::util::ser::BigSize(1200).serialized_length() // custom TLV length
279                 - 2 // onion payload varint prefix increased ser size due to custom TLV
280                 - reserved_packet_bytes_without_custom_tlv;
281
282         // Check that we can send the maximum custom TLV size with 0 intermediate unblinded hops.
283         let recipient_onion_max_custom_tlv_size = RecipientOnionFields::spontaneous_empty()
284                 .with_custom_tlvs(vec![(CUSTOM_TLV_TYPE, vec![42; max_custom_tlv_len])])
285                 .unwrap();
286         nodes[1].node.send_payment(payment_hash, recipient_onion_max_custom_tlv_size.clone(), PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0)).unwrap();
287         check_added_monitors(&nodes[1], 1);
288
289         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
290         assert_eq!(events.len(), 1);
291         let path = &[&nodes[2], &nodes[3]];
292         let args = PassAlongPathArgs::new(&nodes[1], path, amt_msat, payment_hash, events.pop().unwrap())
293                 .with_payment_secret(payment_secret)
294                 .with_custom_tlvs(recipient_onion_max_custom_tlv_size.custom_tlvs.clone());
295         do_pass_along_path(args);
296         claim_payment_along_route(
297                 ClaimAlongRouteArgs::new(&nodes[1], &[&[&nodes[2], &nodes[3]]], payment_preimage)
298                         .with_custom_tlvs(recipient_onion_max_custom_tlv_size.custom_tlvs.clone())
299         );
300
301         // If 1 byte is added to the custom TLV value, we'll fail to send prior to pathfinding.
302         let mut recipient_onion_too_large_custom_tlv = recipient_onion_max_custom_tlv_size.clone();
303         recipient_onion_too_large_custom_tlv.custom_tlvs[0].1.push(42);
304         let err = nodes[1].node.send_payment(payment_hash, recipient_onion_too_large_custom_tlv.clone(), PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0)).unwrap_err();
305         assert_eq!(err, RetryableSendFailure::OnionPacketSizeExceeded);
306
307         // Confirm that we can't construct an onion packet given this too-large custom TLV.
308         let secp_ctx = Secp256k1::signing_only();
309         route.paths[0].hops[0].fee_msat = MIN_FINAL_VALUE_ESTIMATE_WITH_OVERPAY;
310         route.paths[0].hops[0].cltv_expiry_delta = DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA;
311         let err = onion_utils::create_payment_onion(&secp_ctx, &route.paths[0], &test_utils::privkey(42), MIN_FINAL_VALUE_ESTIMATE_WITH_OVERPAY, &recipient_onion_too_large_custom_tlv, nodes[0].best_block_info().1 + DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, &payment_hash, &None, [0; 32]).unwrap_err();
312         match err {
313                 APIError::InvalidRoute { err } => {
314                         assert_eq!(err, "Route size too large considering onion data");
315                 },
316                 _ => panic!(),
317         }
318
319         // With the maximum-size custom TLV, we can't have any intermediate unblinded hops, so attempting
320         // to route nodes[0] -> nodes[3] will fail.
321         let err = nodes[0].node.send_payment(payment_hash, recipient_onion_max_custom_tlv_size.clone(), PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0)).unwrap_err();
322         assert_eq!(err, RetryableSendFailure::RouteNotFound);
323
324         // If we remove enough custom TLV bytes to allow for 1 intermediate unblinded hop, we're now able
325         // to send nodes[0] -> nodes[3].
326         let mut recipient_onion_allows_2_hops = recipient_onion_max_custom_tlv_size.clone();
327         recipient_onion_allows_2_hops.custom_tlvs[0].1.resize(max_custom_tlv_len - INTERMED_PAYLOAD_LEN_ESTIMATE, 0);
328         nodes[0].node.send_payment(payment_hash, recipient_onion_allows_2_hops.clone(), PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0)).unwrap();
329         check_added_monitors(&nodes[0], 1);
330
331         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
332         assert_eq!(events.len(), 1);
333         let path = &[&nodes[1], &nodes[2], &nodes[3]];
334         let args = PassAlongPathArgs::new(&nodes[0], path, amt_msat, payment_hash, events.pop().unwrap())
335                 .with_payment_secret(payment_secret)
336                 .with_custom_tlvs(recipient_onion_allows_2_hops.custom_tlvs.clone());
337         do_pass_along_path(args);
338         claim_payment_along_route(
339                 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1], &nodes[2], &nodes[3]]], payment_preimage)
340                         .with_custom_tlvs(recipient_onion_allows_2_hops.custom_tlvs)
341         );
342 }