]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/blinded_payment_tests.rs
Test sending + receiving custom TLVs to blinded paths.
[rust-lightning] / lightning / src / ln / blinded_payment_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 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
11 use crate::blinded_path::BlindedPath;
12 use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, PaymentConstraints, PaymentRelay, ReceiveTlvs};
13 use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PaymentFailureReason};
14 use crate::ln::PaymentSecret;
15 use crate::ln::channelmanager;
16 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
17 use crate::ln::features::BlindedHopFeatures;
18 use crate::ln::functional_test_utils::*;
19 use crate::ln::msgs;
20 use crate::ln::msgs::ChannelMessageHandler;
21 use crate::ln::onion_utils;
22 use crate::ln::onion_utils::INVALID_ONION_BLINDING;
23 use crate::ln::outbound_payment::{Retry, IDEMPOTENCY_TIMEOUT_TICKS};
24 use crate::offers::invoice::BlindedPayInfo;
25 use crate::prelude::*;
26 use crate::routing::router::{Payee, PaymentParameters, RouteParameters};
27 use crate::util::config::UserConfig;
28 use crate::util::test_utils;
29
30 fn blinded_payment_path(
31         payment_secret: PaymentSecret, intro_node_min_htlc: u64, intro_node_max_htlc: u64,
32         node_ids: Vec<PublicKey>, channel_upds: &[&msgs::UnsignedChannelUpdate],
33         keys_manager: &test_utils::TestKeysInterface
34 ) -> (BlindedPayInfo, BlindedPath) {
35         let mut intermediate_nodes = Vec::new();
36         let mut intro_node_min_htlc_opt = Some(intro_node_min_htlc);
37         let mut intro_node_max_htlc_opt = Some(intro_node_max_htlc);
38         for (idx, (node_id, chan_upd)) in node_ids.iter().zip(channel_upds).enumerate() {
39                 intermediate_nodes.push(ForwardNode {
40                         node_id: *node_id,
41                         tlvs: ForwardTlvs {
42                                 short_channel_id: chan_upd.short_channel_id,
43                                 payment_relay: PaymentRelay {
44                                         cltv_expiry_delta: chan_upd.cltv_expiry_delta,
45                                         fee_proportional_millionths: chan_upd.fee_proportional_millionths,
46                                         fee_base_msat: chan_upd.fee_base_msat,
47                                 },
48                                 payment_constraints: PaymentConstraints {
49                                         max_cltv_expiry: u32::max_value(),
50                                         htlc_minimum_msat: intro_node_min_htlc_opt.take()
51                                                 .unwrap_or_else(|| channel_upds[idx - 1].htlc_minimum_msat),
52                                 },
53                                 features: BlindedHopFeatures::empty(),
54                         },
55                         htlc_maximum_msat: intro_node_max_htlc_opt.take()
56                                 .unwrap_or_else(|| channel_upds[idx - 1].htlc_maximum_msat),
57                 });
58         }
59         let payee_tlvs = ReceiveTlvs {
60                 payment_secret,
61                 payment_constraints: PaymentConstraints {
62                         max_cltv_expiry: u32::max_value(),
63                         htlc_minimum_msat:
64                                 intro_node_min_htlc_opt.unwrap_or_else(|| channel_upds.last().unwrap().htlc_minimum_msat),
65                 },
66         };
67         let mut secp_ctx = Secp256k1::new();
68         BlindedPath::new_for_payment(
69                 &intermediate_nodes[..], *node_ids.last().unwrap(), payee_tlvs,
70                 intro_node_max_htlc_opt.unwrap_or_else(|| channel_upds.last().unwrap().htlc_maximum_msat),
71                 TEST_FINAL_CLTV as u16, keys_manager, &secp_ctx
72         ).unwrap()
73 }
74
75 pub fn get_blinded_route_parameters(
76         amt_msat: u64, payment_secret: PaymentSecret, intro_node_min_htlc: u64, intro_node_max_htlc: u64,
77         node_ids: Vec<PublicKey>, channel_upds: &[&msgs::UnsignedChannelUpdate],
78         keys_manager: &test_utils::TestKeysInterface
79 ) -> RouteParameters {
80         RouteParameters::from_payment_params_and_value(
81                 PaymentParameters::blinded(vec![
82                         blinded_payment_path(
83                                 payment_secret, intro_node_min_htlc, intro_node_max_htlc, node_ids, channel_upds,
84                                 keys_manager
85                         )
86                 ]), amt_msat
87         )
88 }
89
90 #[test]
91 fn one_hop_blinded_path() {
92         do_one_hop_blinded_path(true);
93         do_one_hop_blinded_path(false);
94 }
95
96 fn do_one_hop_blinded_path(success: bool) {
97         let chanmon_cfgs = create_chanmon_cfgs(2);
98         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
99         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
100         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
101         let chan_upd = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0).0.contents;
102
103         let amt_msat = 5000;
104         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(amt_msat), None);
105         let payee_tlvs = ReceiveTlvs {
106                 payment_secret,
107                 payment_constraints: PaymentConstraints {
108                         max_cltv_expiry: u32::max_value(),
109                         htlc_minimum_msat: chan_upd.htlc_minimum_msat,
110                 },
111         };
112         let mut secp_ctx = Secp256k1::new();
113         let blinded_path = BlindedPath::one_hop_for_payment(
114                 nodes[1].node.get_our_node_id(), payee_tlvs, TEST_FINAL_CLTV as u16,
115                 &chanmon_cfgs[1].keys_manager, &secp_ctx
116         ).unwrap();
117
118         let route_params = RouteParameters::from_payment_params_and_value(
119                 PaymentParameters::blinded(vec![blinded_path]),
120                 amt_msat,
121         );
122         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(),
123         PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
124         check_added_monitors(&nodes[0], 1);
125         pass_along_route(&nodes[0], &[&[&nodes[1]]], amt_msat, payment_hash, payment_secret);
126         if success {
127                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
128         } else {
129                 fail_payment(&nodes[0], &[&nodes[1]], payment_hash);
130         }
131 }
132
133 #[test]
134 fn mpp_to_one_hop_blinded_path() {
135         let chanmon_cfgs = create_chanmon_cfgs(4);
136         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
137         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
138         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
139         let mut secp_ctx = Secp256k1::new();
140
141         create_announced_chan_between_nodes(&nodes, 0, 1);
142         create_announced_chan_between_nodes(&nodes, 0, 2);
143         let chan_upd_1_3 = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents;
144         create_announced_chan_between_nodes(&nodes, 2, 3).0.contents;
145
146         let amt_msat = 15_000_000;
147         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[3], Some(amt_msat), None);
148         let payee_tlvs = ReceiveTlvs {
149                 payment_secret,
150                 payment_constraints: PaymentConstraints {
151                         max_cltv_expiry: u32::max_value(),
152                         htlc_minimum_msat: chan_upd_1_3.htlc_minimum_msat,
153                 },
154         };
155         let blinded_path = BlindedPath::one_hop_for_payment(
156                 nodes[3].node.get_our_node_id(), payee_tlvs, TEST_FINAL_CLTV as u16,
157                 &chanmon_cfgs[3].keys_manager, &secp_ctx
158         ).unwrap();
159
160         let bolt12_features =
161                 channelmanager::provided_bolt12_invoice_features(&UserConfig::default());
162         let route_params = RouteParameters::from_payment_params_and_value(
163                 PaymentParameters::blinded(vec![blinded_path]).with_bolt12_features(bolt12_features).unwrap(),
164                 amt_msat,
165         );
166         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
167         check_added_monitors(&nodes[0], 2);
168
169         let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
170         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
171         assert_eq!(events.len(), 2);
172
173         let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
174         pass_along_path(&nodes[0], expected_route[0], amt_msat, payment_hash.clone(),
175                 Some(payment_secret), ev.clone(), false, None);
176
177         let ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
178         pass_along_path(&nodes[0], expected_route[1], amt_msat, payment_hash.clone(),
179                 Some(payment_secret), ev.clone(), true, None);
180         claim_payment_along_route(&nodes[0], expected_route, false, payment_preimage);
181 }
182
183 #[test]
184 fn mpp_to_three_hop_blinded_paths() {
185         let chanmon_cfgs = create_chanmon_cfgs(6);
186         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
187         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
188         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
189
190         // Create this network topology so node 0 MPP's over 2 3-hop blinded paths:
191         //     n1 -- n3
192         //    /        \
193         // n0           n5
194         //    \        /
195         //     n2 -- n4
196         create_announced_chan_between_nodes(&nodes, 0, 1);
197         create_announced_chan_between_nodes(&nodes, 0, 2);
198         let chan_upd_1_3 = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents;
199         let chan_upd_2_4 = create_announced_chan_between_nodes(&nodes, 2, 4).0.contents;
200         let chan_upd_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5).0.contents;
201         let chan_upd_4_5 = create_announced_chan_between_nodes(&nodes, 4, 5).0.contents;
202
203         let amt_msat = 15_000_000;
204         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[5], Some(amt_msat), None);
205         let route_params = {
206                 let path_1_params = get_blinded_route_parameters(
207                         amt_msat, payment_secret, 1, 1_0000_0000, vec![
208                                 nodes[1].node.get_our_node_id(), nodes[3].node.get_our_node_id(),
209                                 nodes[5].node.get_our_node_id()
210                         ], &[&chan_upd_1_3, &chan_upd_3_5], &chanmon_cfgs[5].keys_manager
211                 );
212                 let path_2_params = get_blinded_route_parameters(
213                         amt_msat, payment_secret, 1, 1_0000_0000, vec![
214                                 nodes[2].node.get_our_node_id(), nodes[4].node.get_our_node_id(),
215                                 nodes[5].node.get_our_node_id()
216                         ], &[&chan_upd_2_4, &chan_upd_4_5], &chanmon_cfgs[5].keys_manager
217                 );
218                 let pay_params = PaymentParameters::blinded(
219                         vec![
220                                 path_1_params.payment_params.payee.blinded_route_hints()[0].clone(),
221                                 path_2_params.payment_params.payee.blinded_route_hints()[0].clone()
222                         ]
223                 )
224                         .with_bolt12_features(channelmanager::provided_bolt12_invoice_features(&UserConfig::default()))
225                         .unwrap();
226                 RouteParameters::from_payment_params_and_value(pay_params, amt_msat)
227         };
228
229         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(),
230                 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
231         check_added_monitors(&nodes[0], 2);
232
233         let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[3], &nodes[5]], &[&nodes[2], &nodes[4], &nodes[5]]];
234         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
235         assert_eq!(events.len(), 2);
236
237         let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
238         pass_along_path(&nodes[0], expected_route[0], amt_msat, payment_hash.clone(),
239                 Some(payment_secret), ev.clone(), false, None);
240
241         let ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
242         pass_along_path(&nodes[0], expected_route[1], amt_msat, payment_hash.clone(),
243                 Some(payment_secret), ev.clone(), true, None);
244         claim_payment_along_route(&nodes[0], expected_route, false, payment_preimage);
245 }
246
247 enum ForwardCheckFail {
248         // Fail a check on the inbound onion payload. In this case, we underflow when calculating the
249         // outgoing cltv_expiry.
250         InboundOnionCheck,
251         // The forwarding node's payload is encoded as a receive, i.e. the next hop HMAC is [0; 32].
252         ForwardPayloadEncodedAsReceive,
253         // Fail a check on the outbound channel. In this case, our next-hop peer is offline.
254         OutboundChannelCheck,
255 }
256
257 #[test]
258 fn forward_checks_failure() {
259         do_forward_checks_failure(ForwardCheckFail::InboundOnionCheck, true);
260         do_forward_checks_failure(ForwardCheckFail::InboundOnionCheck, false);
261         do_forward_checks_failure(ForwardCheckFail::ForwardPayloadEncodedAsReceive, true);
262         do_forward_checks_failure(ForwardCheckFail::ForwardPayloadEncodedAsReceive, false);
263         do_forward_checks_failure(ForwardCheckFail::OutboundChannelCheck, true);
264         do_forward_checks_failure(ForwardCheckFail::OutboundChannelCheck, false);
265 }
266
267 fn do_forward_checks_failure(check: ForwardCheckFail, intro_fails: bool) {
268         // Ensure we'll fail backwards properly if a forwarding check fails on initial update_add
269         // receipt.
270         let chanmon_cfgs = create_chanmon_cfgs(4);
271         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
272         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
273         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
274         // We need the session priv to construct a bogus onion packet later.
275         *nodes[0].keys_manager.override_random_bytes.lock().unwrap() = Some([3; 32]);
276         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
277         let chan_upd_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0).0.contents;
278         let chan_upd_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).0.contents;
279
280         let amt_msat = 5000;
281         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[3], Some(amt_msat), None);
282         let route_params = get_blinded_route_parameters(amt_msat, payment_secret, 1, 1_0000_0000,
283                 nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(),
284                 &[&chan_upd_1_2, &chan_upd_2_3], &chanmon_cfgs[3].keys_manager);
285
286         let route = get_route(&nodes[0], &route_params).unwrap();
287         node_cfgs[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
288         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
289         check_added_monitors(&nodes[0], 1);
290
291         macro_rules! cause_error {
292                 ($src_node_idx: expr, $target_node_idx: expr, $update_add: expr) => {
293                         match check {
294                                 ForwardCheckFail::InboundOnionCheck => {
295                                         $update_add.cltv_expiry = 10; // causes outbound CLTV expiry to underflow
296                                 },
297                                 ForwardCheckFail::ForwardPayloadEncodedAsReceive => {
298                                         let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
299                                         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
300                                         let cur_height = nodes[0].best_block_info().1;
301                                         let (mut onion_payloads, ..) = onion_utils::build_onion_payloads(
302                                                 &route.paths[0], amt_msat, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
303                                         // Remove the receive payload so the blinded forward payload is encoded as a final payload
304                                         // (i.e. next_hop_hmac == [0; 32])
305                                         onion_payloads.pop();
306                                         if $target_node_idx + 1 < nodes.len() {
307                                                 onion_payloads.pop();
308                                         }
309                                         $update_add.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
310                                 },
311                                 ForwardCheckFail::OutboundChannelCheck => {
312                                         // The intro node will see that the next-hop peer is disconnected and fail the HTLC backwards.
313                                         nodes[$src_node_idx].node.peer_disconnected(&nodes[$target_node_idx].node.get_our_node_id());
314                                 }
315                         }
316                 }
317         }
318
319         let mut updates_0_1 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
320         let update_add = &mut updates_0_1.update_add_htlcs[0];
321
322         if intro_fails {
323                 cause_error!(1, 2, update_add);
324         }
325
326         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
327         check_added_monitors!(nodes[1], 0);
328         do_commitment_signed_dance(&nodes[1], &nodes[0], &updates_0_1.commitment_signed, true, true);
329
330         if intro_fails {
331                 let mut updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
332                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
333                 do_commitment_signed_dance(&nodes[0], &nodes[1], &updates.commitment_signed, false, false);
334                 expect_payment_failed_conditions(&nodes[0], payment_hash, false,
335                         PaymentFailedConditions::new().expected_htlc_error_data(INVALID_ONION_BLINDING, &[0; 32]));
336                 return
337         }
338
339         expect_pending_htlcs_forwardable!(nodes[1]);
340         check_added_monitors!(nodes[1], 1);
341
342         let mut updates_1_2 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
343         let mut update_add = &mut updates_1_2.update_add_htlcs[0];
344
345         cause_error!(2, 3, update_add);
346
347         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add);
348         check_added_monitors!(nodes[2], 0);
349         do_commitment_signed_dance(&nodes[2], &nodes[1], &updates_1_2.commitment_signed, true, true);
350
351         let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
352         let update_malformed = &mut updates.update_fail_malformed_htlcs[0];
353         assert_eq!(update_malformed.failure_code, INVALID_ONION_BLINDING);
354         assert_eq!(update_malformed.sha256_of_onion, [0; 32]);
355
356         // Ensure the intro node will properly blind the error if its downstream node failed to do so.
357         update_malformed.sha256_of_onion = [1; 32];
358         update_malformed.failure_code = INVALID_ONION_BLINDING ^ 1;
359         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), update_malformed);
360         do_commitment_signed_dance(&nodes[1], &nodes[2], &updates.commitment_signed, true, false);
361
362         let mut updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
363         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
364         do_commitment_signed_dance(&nodes[0], &nodes[1], &updates.commitment_signed, false, false);
365         expect_payment_failed_conditions(&nodes[0], payment_hash, false,
366                 PaymentFailedConditions::new().expected_htlc_error_data(INVALID_ONION_BLINDING, &[0; 32]));
367 }
368
369 #[test]
370 fn failed_backwards_to_intro_node() {
371         // Ensure the intro node will error backwards properly even if the downstream node did not blind
372         // their error.
373         let chanmon_cfgs = create_chanmon_cfgs(3);
374         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
375         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
376         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
377         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
378         let chan_upd_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0).0.contents;
379
380         let amt_msat = 5000;
381         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[2], Some(amt_msat), None);
382         let route_params = get_blinded_route_parameters(amt_msat, payment_secret, 1, 1_0000_0000,
383                 nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(), &[&chan_upd_1_2],
384                 &chanmon_cfgs[2].keys_manager);
385
386         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
387         check_added_monitors(&nodes[0], 1);
388
389         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
390         assert_eq!(events.len(), 1);
391         let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
392         let mut payment_event = SendEvent::from_event(ev);
393
394         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
395         check_added_monitors!(nodes[1], 0);
396         do_commitment_signed_dance(&nodes[1], &nodes[0], &payment_event.commitment_msg, false, false);
397         expect_pending_htlcs_forwardable!(nodes[1]);
398         check_added_monitors!(&nodes[1], 1);
399
400         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
401         assert_eq!(events.len(), 1);
402         let ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
403         let mut payment_event = SendEvent::from_event(ev);
404
405         // Ensure the final node fails to handle the HTLC.
406         payment_event.msgs[0].onion_routing_packet.hop_data[0] ^= 1;
407         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
408         check_added_monitors!(nodes[2], 0);
409         do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event.commitment_msg, true, true);
410         nodes[2].node.process_pending_htlc_forwards();
411
412         let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
413         let mut update_malformed = &mut updates.update_fail_malformed_htlcs[0];
414         // Check that the final node encodes its failure correctly.
415         assert_eq!(update_malformed.failure_code, INVALID_ONION_BLINDING);
416         assert_eq!(update_malformed.sha256_of_onion, [0; 32]);
417
418         // Modify such the final hop does not correctly blind their error so we can ensure the intro node
419         // converts it to the correct error.
420         update_malformed.sha256_of_onion = [1; 32];
421         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), update_malformed);
422         do_commitment_signed_dance(&nodes[1], &nodes[2], &updates.commitment_signed, true, false);
423
424         let mut updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
425         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
426         do_commitment_signed_dance(&nodes[0], &nodes[1], &updates.commitment_signed, false, false);
427         expect_payment_failed_conditions(&nodes[0], payment_hash, false,
428                 PaymentFailedConditions::new().expected_htlc_error_data(INVALID_ONION_BLINDING, &[0; 32]));
429 }
430
431 enum ProcessPendingHTLCsCheck {
432         FwdPeerDisconnected,
433         FwdChannelClosed,
434 }
435
436 #[test]
437 fn forward_fail_in_process_pending_htlc_fwds() {
438         do_forward_fail_in_process_pending_htlc_fwds(ProcessPendingHTLCsCheck::FwdPeerDisconnected, true);
439         do_forward_fail_in_process_pending_htlc_fwds(ProcessPendingHTLCsCheck::FwdPeerDisconnected, false);
440         do_forward_fail_in_process_pending_htlc_fwds(ProcessPendingHTLCsCheck::FwdChannelClosed, true);
441         do_forward_fail_in_process_pending_htlc_fwds(ProcessPendingHTLCsCheck::FwdChannelClosed, false);
442 }
443 fn do_forward_fail_in_process_pending_htlc_fwds(check: ProcessPendingHTLCsCheck, intro_fails: bool) {
444         // Ensure the intro node will error backwards properly if the HTLC fails in
445         // process_pending_htlc_forwards.
446         let chanmon_cfgs = create_chanmon_cfgs(4);
447         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
448         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
449         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
450         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
451         let (chan_upd_1_2, chan_id_1_2) = {
452                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0);
453                 (chan.0.contents, chan.2)
454         };
455         let (chan_upd_2_3, chan_id_2_3) = {
456                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0);
457                 (chan.0.contents, chan.2)
458         };
459
460         let amt_msat = 5000;
461         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[2], Some(amt_msat), None);
462         let route_params = get_blinded_route_parameters(amt_msat, payment_secret, 1, 1_0000_0000,
463                 nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(), &[&chan_upd_1_2, &chan_upd_2_3],
464                 &chanmon_cfgs[2].keys_manager);
465
466         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
467         check_added_monitors(&nodes[0], 1);
468
469         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
470         assert_eq!(events.len(), 1);
471         let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
472         let mut payment_event = SendEvent::from_event(ev);
473
474         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
475         check_added_monitors!(nodes[1], 0);
476         do_commitment_signed_dance(&nodes[1], &nodes[0], &payment_event.commitment_msg, false, false);
477
478         macro_rules! cause_error {
479                 ($prev_node: expr, $curr_node: expr, $next_node: expr, $failed_chan_id: expr, $failed_scid: expr) => {
480                         match check {
481                                 ProcessPendingHTLCsCheck::FwdPeerDisconnected => {
482                                         // Disconnect the next-hop peer so when we go to forward in process_pending_htlc_forwards, the
483                                         // intro node will error backwards.
484                                         $curr_node.node.peer_disconnected(&$next_node.node.get_our_node_id());
485                                         expect_pending_htlcs_forwardable!($curr_node);
486                                         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!($curr_node,
487                                                 vec![HTLCDestination::NextHopChannel { node_id: Some($next_node.node.get_our_node_id()), channel_id: $failed_chan_id }]);
488                                 },
489                                 ProcessPendingHTLCsCheck::FwdChannelClosed => {
490                                         // Force close the next-hop channel so when we go to forward in process_pending_htlc_forwards,
491                                         // the intro node will error backwards.
492                                         $curr_node.node.force_close_broadcasting_latest_txn(&$failed_chan_id, &$next_node.node.get_our_node_id()).unwrap();
493                                         let events = $curr_node.node.get_and_clear_pending_events();
494                                         match events[0] {
495                                                 crate::events::Event::PendingHTLCsForwardable { .. } => {},
496                                                 _ => panic!("Unexpected event {:?}", events),
497                                         };
498                                         match events[1] {
499                                                 crate::events::Event::ChannelClosed { .. } => {},
500                                                 _ => panic!("Unexpected event {:?}", events),
501                                         }
502
503                                         $curr_node.node.process_pending_htlc_forwards();
504                                         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!($curr_node,
505                                                 vec![HTLCDestination::UnknownNextHop { requested_forward_scid: $failed_scid }]);
506                                         check_closed_broadcast(&$curr_node, 1, true);
507                                         check_added_monitors!($curr_node, 1);
508                                         $curr_node.node.process_pending_htlc_forwards();
509                                 },
510                         }
511                 }
512         }
513
514         if intro_fails {
515                 cause_error!(nodes[0], nodes[1], nodes[2], chan_id_1_2, chan_upd_1_2.short_channel_id);
516                 let mut updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
517                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
518                 check_added_monitors!(nodes[1], 1);
519                 do_commitment_signed_dance(&nodes[0], &nodes[1], &updates.commitment_signed, false, false);
520
521                 expect_payment_failed_conditions(&nodes[0], payment_hash, false,
522                         PaymentFailedConditions::new().expected_htlc_error_data(INVALID_ONION_BLINDING, &[0; 32]));
523                 return
524         }
525
526         expect_pending_htlcs_forwardable!(nodes[1]);
527         check_added_monitors!(nodes[1], 1);
528
529         let mut updates_1_2 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
530         let mut update_add = &mut updates_1_2.update_add_htlcs[0];
531         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add);
532         check_added_monitors!(nodes[2], 0);
533         do_commitment_signed_dance(&nodes[2], &nodes[1], &updates_1_2.commitment_signed, true, true);
534
535         cause_error!(nodes[1], nodes[2], nodes[3], chan_id_2_3, chan_upd_2_3.short_channel_id);
536         check_added_monitors!(nodes[2], 1);
537
538         let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
539         let update_malformed = &mut updates.update_fail_malformed_htlcs[0];
540         assert_eq!(update_malformed.failure_code, INVALID_ONION_BLINDING);
541         assert_eq!(update_malformed.sha256_of_onion, [0; 32]);
542
543         // Ensure the intro node will properly blind the error if its downstream node failed to do so.
544         update_malformed.sha256_of_onion = [1; 32];
545         update_malformed.failure_code = INVALID_ONION_BLINDING ^ 1;
546         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), update_malformed);
547         do_commitment_signed_dance(&nodes[1], &nodes[2], &updates.commitment_signed, true, false);
548
549         let mut updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
550         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
551         do_commitment_signed_dance(&nodes[0], &nodes[1], &updates.commitment_signed, false, false);
552         expect_payment_failed_conditions(&nodes[0], payment_hash, false,
553                 PaymentFailedConditions::new().expected_htlc_error_data(INVALID_ONION_BLINDING, &[0; 32]));
554 }
555
556 #[test]
557 fn blinded_intercept_payment() {
558         do_blinded_intercept_payment(true);
559         do_blinded_intercept_payment(false);
560 }
561 fn do_blinded_intercept_payment(intercept_node_fails: bool) {
562         let chanmon_cfgs = create_chanmon_cfgs(3);
563         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
564         let mut intercept_forwards_config = test_default_channel_config();
565         intercept_forwards_config.accept_intercept_htlcs = true;
566         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), None]);
567         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
568         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
569         let (channel_id, chan_upd) = {
570                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0);
571                 (chan.2, chan.0.contents)
572         };
573
574         let amt_msat = 5000;
575         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[2], Some(amt_msat), None);
576         let intercept_scid = nodes[1].node.get_intercept_scid();
577         let mut intercept_chan_upd = chan_upd;
578         intercept_chan_upd.short_channel_id = intercept_scid;
579         let route_params = get_blinded_route_parameters(amt_msat, payment_secret, 1, 1_0000_0000,
580                 nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(), &[&intercept_chan_upd],
581                 &chanmon_cfgs[2].keys_manager);
582
583         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(),
584         PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
585         check_added_monitors(&nodes[0], 1);
586         let payment_event = {
587                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
588                 assert_eq!(events.len(), 1);
589                 SendEvent::from_event(events.remove(0))
590         };
591         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
592         commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
593
594         let events = nodes[1].node.get_and_clear_pending_events();
595         assert_eq!(events.len(), 1);
596         let (intercept_id, expected_outbound_amount_msat) = match events[0] {
597                 crate::events::Event::HTLCIntercepted {
598                         intercept_id, payment_hash: pmt_hash,
599                         requested_next_hop_scid: short_channel_id, expected_outbound_amount_msat, ..
600                 } => {
601                         assert_eq!(pmt_hash, payment_hash);
602                         assert_eq!(short_channel_id, intercept_scid);
603                         (intercept_id, expected_outbound_amount_msat)
604                 },
605                 _ => panic!()
606         };
607
608         if intercept_node_fails {
609                 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
610                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
611                 nodes[1].node.process_pending_htlc_forwards();
612                 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
613                 check_added_monitors!(&nodes[1], 1);
614                 assert!(update_fail.update_fail_htlcs.len() == 1);
615                 let fail_msg = update_fail.update_fail_htlcs[0].clone();
616                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
617                 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
618                 expect_payment_failed_conditions(&nodes[0], payment_hash, false,
619                         PaymentFailedConditions::new().expected_htlc_error_data(INVALID_ONION_BLINDING, &[0; 32]));
620                 return
621         }
622
623         nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
624         expect_pending_htlcs_forwardable!(nodes[1]);
625
626         let payment_event = {
627                 {
628                         let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
629                         assert_eq!(added_monitors.len(), 1);
630                         added_monitors.clear();
631                 }
632                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
633                 assert_eq!(events.len(), 1);
634                 SendEvent::from_event(events.remove(0))
635         };
636         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
637         commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
638         expect_pending_htlcs_forwardable!(nodes[2]);
639
640         expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, None, nodes[2].node.get_our_node_id());
641         do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
642         expect_payment_sent(&nodes[0], payment_preimage, Some(Some(1000)), true, true);
643 }
644
645 #[test]
646 fn two_hop_blinded_path_success() {
647         let chanmon_cfgs = create_chanmon_cfgs(3);
648         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
649         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
650         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
651         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
652         let chan_upd_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0).0.contents;
653
654         let amt_msat = 5000;
655         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[2], Some(amt_msat), None);
656         let route_params = get_blinded_route_parameters(amt_msat, payment_secret, 1, 1_0000_0000,
657                 nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(), &[&chan_upd_1_2],
658                 &chanmon_cfgs[2].keys_manager);
659
660         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
661         check_added_monitors(&nodes[0], 1);
662         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], amt_msat, payment_hash, payment_secret);
663         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
664 }
665
666 #[test]
667 fn three_hop_blinded_path_success() {
668         let chanmon_cfgs = create_chanmon_cfgs(5);
669         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
670         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
671         let mut nodes = create_network(5, &node_cfgs, &node_chanmgrs);
672         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
673         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0);
674         let chan_upd_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).0.contents;
675         let chan_upd_3_4 = create_announced_chan_between_nodes_with_value(&nodes, 3, 4, 1_000_000, 0).0.contents;
676
677         // Get all our nodes onto the same height so payments don't fail for CLTV violations.
678         connect_blocks(&nodes[0], nodes[4].best_block_info().1 - nodes[0].best_block_info().1);
679         connect_blocks(&nodes[1], nodes[4].best_block_info().1 - nodes[1].best_block_info().1);
680         connect_blocks(&nodes[2], nodes[4].best_block_info().1 - nodes[2].best_block_info().1);
681         assert_eq!(nodes[4].best_block_info().1, nodes[3].best_block_info().1);
682
683         let amt_msat = 5000;
684         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[4], Some(amt_msat), None);
685         let route_params = get_blinded_route_parameters(amt_msat, payment_secret, 1, 1_0000_0000,
686                 nodes.iter().skip(2).map(|n| n.node.get_our_node_id()).collect(),
687                 &[&chan_upd_2_3, &chan_upd_3_4], &chanmon_cfgs[4].keys_manager);
688
689         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
690         check_added_monitors(&nodes[0], 1);
691         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2], &nodes[3], &nodes[4]]], amt_msat, payment_hash, payment_secret);
692         claim_payment(&nodes[0], &[&nodes[1], &nodes[2], &nodes[3], &nodes[4]], payment_preimage);
693 }
694
695 #[test]
696 fn three_hop_blinded_path_fail() {
697         // Test that an intermediate blinded forwarding node gets failed back to with
698         // malformed and also fails back themselves with malformed.
699         let chanmon_cfgs = create_chanmon_cfgs(4);
700         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
701         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
702         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
703         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
704         let chan_upd_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0).0.contents;
705         let chan_upd_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).0.contents;
706
707         let amt_msat = 5000;
708         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[3], Some(amt_msat), None);
709         let route_params = get_blinded_route_parameters(amt_msat, payment_secret, 1, 1_0000_0000,
710                 nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(),
711                 &[&chan_upd_1_2, &chan_upd_2_3], &chanmon_cfgs[3].keys_manager);
712
713         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
714         check_added_monitors(&nodes[0], 1);
715         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2], &nodes[3]]], amt_msat, payment_hash, payment_secret);
716
717         nodes[3].node.fail_htlc_backwards(&payment_hash);
718         expect_pending_htlcs_forwardable_conditions(
719                 nodes[3].node.get_and_clear_pending_events(), &[HTLCDestination::FailedPayment { payment_hash }]
720         );
721         nodes[3].node.process_pending_htlc_forwards();
722         check_added_monitors!(nodes[3], 1);
723
724         let updates_3_2 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
725         assert_eq!(updates_3_2.update_fail_malformed_htlcs.len(), 1);
726         let update_malformed = &updates_3_2.update_fail_malformed_htlcs[0];
727         assert_eq!(update_malformed.sha256_of_onion, [0; 32]);
728         assert_eq!(update_malformed.failure_code, INVALID_ONION_BLINDING);
729         nodes[2].node.handle_update_fail_malformed_htlc(&nodes[3].node.get_our_node_id(), update_malformed);
730         do_commitment_signed_dance(&nodes[2], &nodes[3], &updates_3_2.commitment_signed, true, false);
731
732         let updates_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
733         assert_eq!(updates_2_1.update_fail_malformed_htlcs.len(), 1);
734         let update_malformed = &updates_2_1.update_fail_malformed_htlcs[0];
735         assert_eq!(update_malformed.sha256_of_onion, [0; 32]);
736         assert_eq!(update_malformed.failure_code, INVALID_ONION_BLINDING);
737         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), update_malformed);
738         do_commitment_signed_dance(&nodes[1], &nodes[2], &updates_2_1.commitment_signed, true, false);
739
740         let updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
741         assert_eq!(updates_1_0.update_fail_htlcs.len(), 1);
742         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_1_0.update_fail_htlcs[0]);
743         do_commitment_signed_dance(&nodes[0], &nodes[1], &updates_1_0.commitment_signed, false, false);
744         expect_payment_failed_conditions(&nodes[0], payment_hash, false,
745                 PaymentFailedConditions::new().expected_htlc_error_data(INVALID_ONION_BLINDING, &[0; 32]));
746 }
747
748 #[derive(PartialEq)]
749 enum ReceiveCheckFail {
750         // The recipient fails the payment upon `PaymentClaimable`.
751         RecipientFail,
752         // Failure to decode the recipient's onion payload.
753         OnionDecodeFail,
754         // The incoming HTLC did not satisfy our requirements; in this case it underpaid us according to
755         // the expected receive amount in the onion.
756         ReceiveRequirements,
757         // The incoming HTLC errors when added to the Channel, in this case due to the HTLC being
758         // delivered out-of-order with a shutdown message.
759         ChannelCheck,
760         // The HTLC is successfully added to the inbound channel but fails receive checks in
761         // process_pending_htlc_forwards.
762         ProcessPendingHTLCsCheck,
763         // The HTLC violates the `PaymentConstraints` contained within the receiver's encrypted payload.
764         PaymentConstraints,
765 }
766
767 #[test]
768 fn multi_hop_receiver_fail() {
769         do_multi_hop_receiver_fail(ReceiveCheckFail::RecipientFail);
770         do_multi_hop_receiver_fail(ReceiveCheckFail::OnionDecodeFail);
771         do_multi_hop_receiver_fail(ReceiveCheckFail::ReceiveRequirements);
772         do_multi_hop_receiver_fail(ReceiveCheckFail::ChannelCheck);
773         do_multi_hop_receiver_fail(ReceiveCheckFail::ProcessPendingHTLCsCheck);
774         do_multi_hop_receiver_fail(ReceiveCheckFail::PaymentConstraints);
775 }
776
777 fn do_multi_hop_receiver_fail(check: ReceiveCheckFail) {
778         // Test that the receiver to a multihop blinded path fails back correctly.
779         let chanmon_cfgs = create_chanmon_cfgs(3);
780         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
781         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
782         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
783         // We need the session priv to construct an invalid onion packet later.
784         let session_priv = [3; 32];
785         *nodes[0].keys_manager.override_random_bytes.lock().unwrap() = Some(session_priv);
786         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
787         let (chan_upd_1_2, chan_id_1_2) = {
788                 let (chan_upd, _, channel_id, ..) = create_announced_chan_between_nodes_with_value(
789                         &nodes, 1, 2, 1_000_000, 0
790                 );
791                 (chan_upd.contents, channel_id)
792         };
793
794         let amt_msat = 5000;
795         let excess_final_cltv_delta_opt = if check == ReceiveCheckFail::ProcessPendingHTLCsCheck {
796                 // Set the final CLTV expiry too low to trigger the failure in process_pending_htlc_forwards.
797                 Some(TEST_FINAL_CLTV as u16 - 2)
798         } else { None };
799         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[2], Some(amt_msat), excess_final_cltv_delta_opt);
800         let mut route_params = get_blinded_route_parameters(amt_msat, payment_secret, 1, 1_0000_0000,
801                 nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(), &[&chan_upd_1_2],
802                 &chanmon_cfgs[2].keys_manager);
803
804         let route = if check == ReceiveCheckFail::ProcessPendingHTLCsCheck {
805                 let mut route = get_route(&nodes[0], &route_params).unwrap();
806                 // Set the final CLTV expiry too low to trigger the failure in process_pending_htlc_forwards.
807                 route.paths[0].hops.last_mut().map(|h| h.cltv_expiry_delta += excess_final_cltv_delta_opt.unwrap() as u32);
808                 route.paths[0].blinded_tail.as_mut().map(|bt| bt.excess_final_cltv_expiry_delta = excess_final_cltv_delta_opt.unwrap() as u32);
809                 route
810         } else if check == ReceiveCheckFail::PaymentConstraints {
811                 // Create a blinded path where the receiver's encrypted payload has an htlc_minimum_msat that is
812                 // violated by `amt_msat`, and stick it in the route_params without changing the corresponding
813                 // BlindedPayInfo (to ensure pathfinding still succeeds).
814                 let high_htlc_min_bp = {
815                         let mut high_htlc_minimum_upd = chan_upd_1_2.clone();
816                         high_htlc_minimum_upd.htlc_minimum_msat = amt_msat + 1000;
817                         let high_htlc_min_params = get_blinded_route_parameters(amt_msat, payment_secret, 1, 1_0000_0000,
818                                 nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(), &[&high_htlc_minimum_upd],
819                                 &chanmon_cfgs[2].keys_manager);
820                         if let Payee::Blinded { route_hints, .. } = high_htlc_min_params.payment_params.payee {
821                                 route_hints[0].1.clone()
822                         } else { panic!() }
823                 };
824                 if let Payee::Blinded { ref mut route_hints, .. } = route_params.payment_params.payee {
825                         route_hints[0].1 = high_htlc_min_bp;
826                 } else { panic!() }
827                 find_route(&nodes[0], &route_params).unwrap()
828         } else {
829                 find_route(&nodes[0], &route_params).unwrap()
830         };
831         node_cfgs[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
832         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
833         check_added_monitors(&nodes[0], 1);
834
835         let mut payment_event_0_1 = {
836                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
837                 assert_eq!(events.len(), 1);
838                 let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
839                 SendEvent::from_event(ev)
840         };
841         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_0_1.msgs[0]);
842         check_added_monitors!(nodes[1], 0);
843         do_commitment_signed_dance(&nodes[1], &nodes[0], &payment_event_0_1.commitment_msg, false, false);
844         expect_pending_htlcs_forwardable!(nodes[1]);
845         check_added_monitors!(&nodes[1], 1);
846
847         let mut payment_event_1_2 = {
848                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
849                 assert_eq!(events.len(), 1);
850                 let ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
851                 SendEvent::from_event(ev)
852         };
853
854         match check {
855                 ReceiveCheckFail::RecipientFail => {
856                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_1_2.msgs[0]);
857                         check_added_monitors!(nodes[2], 0);
858                         do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event_1_2.commitment_msg, true, true);
859                         expect_pending_htlcs_forwardable!(nodes[2]);
860                         check_payment_claimable(
861                                 &nodes[2].node.get_and_clear_pending_events()[0], payment_hash, payment_secret, amt_msat,
862                                 None, nodes[2].node.get_our_node_id()
863                         );
864                         nodes[2].node.fail_htlc_backwards(&payment_hash);
865                         expect_pending_htlcs_forwardable_conditions(
866                                 nodes[2].node.get_and_clear_pending_events(), &[HTLCDestination::FailedPayment { payment_hash }]
867                         );
868                         nodes[2].node.process_pending_htlc_forwards();
869                         check_added_monitors!(nodes[2], 1);
870                 },
871                 ReceiveCheckFail::OnionDecodeFail => {
872                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
873                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
874                         let cur_height = nodes[0].best_block_info().1;
875                         let (mut onion_payloads, ..) = onion_utils::build_onion_payloads(
876                                 &route.paths[0], amt_msat, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
877
878                         let update_add = &mut payment_event_1_2.msgs[0];
879                         onion_payloads.last_mut().map(|p| {
880                                 if let msgs::OutboundOnionPayload::BlindedReceive { ref mut intro_node_blinding_point, .. } = p {
881                                         // The receiver should error if both the update_add blinding_point and the
882                                         // intro_node_blinding_point are set.
883                                         assert!(intro_node_blinding_point.is_none() && update_add.blinding_point.is_some());
884                                         *intro_node_blinding_point = Some(PublicKey::from_slice(&[2; 33]).unwrap());
885                                 } else { panic!() }
886                         });
887                         update_add.onion_routing_packet = onion_utils::construct_onion_packet(
888                                 vec![onion_payloads.pop().unwrap()], vec![onion_keys.pop().unwrap()], [0; 32],
889                                 &payment_hash
890                         ).unwrap();
891                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update_add);
892                         check_added_monitors!(nodes[2], 0);
893                         do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event_1_2.commitment_msg, true, true);
894                 },
895                 ReceiveCheckFail::ReceiveRequirements => {
896                         let update_add = &mut payment_event_1_2.msgs[0];
897                         update_add.amount_msat -= 1;
898                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update_add);
899                         check_added_monitors!(nodes[2], 0);
900                         do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event_1_2.commitment_msg, true, true);
901                 },
902                 ReceiveCheckFail::ChannelCheck => {
903                         nodes[2].node.close_channel(&chan_id_1_2, &nodes[1].node.get_our_node_id()).unwrap();
904                         let node_2_shutdown = get_event_msg!(nodes[2], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
905                         nodes[1].node.handle_shutdown(&nodes[2].node.get_our_node_id(), &node_2_shutdown);
906                         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
907
908                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_1_2.msgs[0]);
909                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event_1_2.commitment_msg);
910                         check_added_monitors!(nodes[2], 1);
911
912                         nodes[2].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
913                         commitment_signed_dance!(nodes[2], nodes[1], (), false, true, false, false);
914                 },
915                 ReceiveCheckFail::ProcessPendingHTLCsCheck => {
916                         assert_eq!(payment_event_1_2.msgs[0].cltv_expiry, nodes[0].best_block_info().1 + 1 + excess_final_cltv_delta_opt.unwrap() as u32 + TEST_FINAL_CLTV);
917                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_1_2.msgs[0]);
918                         check_added_monitors!(nodes[2], 0);
919                         do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event_1_2.commitment_msg, true, true);
920                         expect_pending_htlcs_forwardable!(nodes[2]);
921                         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[2],
922                                 vec![HTLCDestination::FailedPayment { payment_hash }]);
923                         check_added_monitors!(nodes[2], 1);
924                 },
925                 ReceiveCheckFail::PaymentConstraints => {
926                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_1_2.msgs[0]);
927                         check_added_monitors!(nodes[2], 0);
928                         do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event_1_2.commitment_msg, true, true);
929                 }
930         }
931
932         let updates_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
933         assert_eq!(updates_2_1.update_fail_malformed_htlcs.len(), 1);
934         let update_malformed = &updates_2_1.update_fail_malformed_htlcs[0];
935         assert_eq!(update_malformed.sha256_of_onion, [0; 32]);
936         assert_eq!(update_malformed.failure_code, INVALID_ONION_BLINDING);
937         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), update_malformed);
938         do_commitment_signed_dance(&nodes[1], &nodes[2], &updates_2_1.commitment_signed, true, false);
939
940         let updates_1_0 = if check == ReceiveCheckFail::ChannelCheck {
941                 let events = nodes[1].node.get_and_clear_pending_msg_events();
942                 assert_eq!(events.len(), 2);
943                 events.into_iter().find_map(|ev| {
944                         match ev {
945                                 MessageSendEvent:: UpdateHTLCs { node_id, updates } => {
946                                         assert_eq!(node_id, nodes[0].node.get_our_node_id());
947                                         return Some(updates)
948                                 },
949                                 MessageSendEvent::SendClosingSigned { .. } => None,
950                                 _ => panic!()
951                         }
952                 }).unwrap()
953         } else { get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()) };
954         assert_eq!(updates_1_0.update_fail_htlcs.len(), 1);
955         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_1_0.update_fail_htlcs[0]);
956         do_commitment_signed_dance(&nodes[0], &nodes[1], &updates_1_0.commitment_signed, false, false);
957         expect_payment_failed_conditions(&nodes[0], payment_hash, false,
958                 PaymentFailedConditions::new().expected_htlc_error_data(INVALID_ONION_BLINDING, &[0; 32]));
959 }
960
961 #[test]
962 fn blinded_path_retries() {
963         let chanmon_cfgs = create_chanmon_cfgs(4);
964         // Make one blinded path's fees slightly higher so they are tried in a deterministic order.
965         let mut higher_fee_chan_cfg = test_default_channel_config();
966         higher_fee_chan_cfg.channel_config.forwarding_fee_base_msat += 1;
967         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
968         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, Some(higher_fee_chan_cfg), None]);
969         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
970
971         // Create this network topology so nodes[0] has a blinded route hint to retry over.
972         //      n1
973         //    /    \
974         // n0       n3
975         //    \    /
976         //      n2
977         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
978         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
979         let chan_1_3 = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0);
980         let chan_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0);
981
982         let amt_msat = 5000;
983         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[3], Some(amt_msat), None);
984         let route_params = {
985                 let pay_params = PaymentParameters::blinded(
986                         vec![
987                                 blinded_payment_path(payment_secret, 1, 1_0000_0000,
988                                         vec![nodes[1].node.get_our_node_id(), nodes[3].node.get_our_node_id()], &[&chan_1_3.0.contents],
989                                         &chanmon_cfgs[3].keys_manager
990                                 ),
991                                 blinded_payment_path(payment_secret, 1, 1_0000_0000,
992                                         vec![nodes[2].node.get_our_node_id(), nodes[3].node.get_our_node_id()], &[&chan_2_3.0.contents],
993                                         &chanmon_cfgs[3].keys_manager
994                                 ),
995                         ]
996                 )
997                         .with_bolt12_features(channelmanager::provided_bolt12_invoice_features(&UserConfig::default()))
998                         .unwrap();
999                 RouteParameters::from_payment_params_and_value(pay_params, amt_msat)
1000         };
1001
1002         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(2)).unwrap();
1003         check_added_monitors(&nodes[0], 1);
1004         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]]], amt_msat, payment_hash, payment_secret);
1005
1006         macro_rules! fail_payment_back {
1007                 ($intro_node: expr) => {
1008                         nodes[3].node.fail_htlc_backwards(&payment_hash);
1009                         expect_pending_htlcs_forwardable_conditions(
1010                                 nodes[3].node.get_and_clear_pending_events(), &[HTLCDestination::FailedPayment { payment_hash }]
1011                         );
1012                         nodes[3].node.process_pending_htlc_forwards();
1013                         check_added_monitors!(nodes[3], 1);
1014
1015                         let updates = get_htlc_update_msgs!(nodes[3], $intro_node.node.get_our_node_id());
1016                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 1);
1017                         let update_malformed = &updates.update_fail_malformed_htlcs[0];
1018                         assert_eq!(update_malformed.sha256_of_onion, [0; 32]);
1019                         assert_eq!(update_malformed.failure_code, INVALID_ONION_BLINDING);
1020                         $intro_node.node.handle_update_fail_malformed_htlc(&nodes[3].node.get_our_node_id(), update_malformed);
1021                         do_commitment_signed_dance(&$intro_node, &nodes[3], &updates.commitment_signed, true, false);
1022
1023                         let updates =  get_htlc_update_msgs!($intro_node, nodes[0].node.get_our_node_id());
1024                         assert_eq!(updates.update_fail_htlcs.len(), 1);
1025                         nodes[0].node.handle_update_fail_htlc(&$intro_node.node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1026                         do_commitment_signed_dance(&nodes[0], &$intro_node, &updates.commitment_signed, false, false);
1027
1028                         let mut events = nodes[0].node.get_and_clear_pending_events();
1029                         assert_eq!(events.len(), 2);
1030                         match events[0] {
1031                                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
1032                                         assert_eq!(payment_hash, ev_payment_hash);
1033                                         assert_eq!(payment_failed_permanently, false);
1034                                 },
1035                                 _ => panic!("Unexpected event"),
1036                         }
1037                         match events[1] {
1038                                 Event::PendingHTLCsForwardable { .. } => {},
1039                                 _ => panic!("Unexpected event"),
1040                         }
1041                         nodes[0].node.process_pending_htlc_forwards();
1042                 }
1043         }
1044
1045         fail_payment_back!(nodes[1]);
1046
1047         // Pass the retry along.
1048         check_added_monitors!(nodes[0], 1);
1049         let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1050         assert_eq!(msg_events.len(), 1);
1051         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
1052
1053         fail_payment_back!(nodes[2]);
1054         let evs = nodes[0].node.get_and_clear_pending_events();
1055         assert_eq!(evs.len(), 1);
1056         match evs[0] {
1057                 Event::PaymentFailed { payment_hash: ev_payment_hash, reason, .. } => {
1058                         assert_eq!(ev_payment_hash, payment_hash);
1059                         // We have 1 retry attempt remaining, but we're out of blinded paths to try.
1060                         assert_eq!(reason, Some(PaymentFailureReason::RouteNotFound));
1061                 },
1062                 _ => panic!()
1063         }
1064 }
1065
1066 #[test]
1067 fn min_htlc() {
1068         // The min htlc of a blinded path is the max (htlc_min - following_fees) along the path. Make sure
1069         // the payment succeeds when we calculate the min htlc this way.
1070         let chanmon_cfgs = create_chanmon_cfgs(4);
1071         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1072         let mut node_1_cfg = test_default_channel_config();
1073         node_1_cfg.channel_handshake_config.our_htlc_minimum_msat = 2000;
1074         node_1_cfg.channel_config.forwarding_fee_base_msat = 1000;
1075         node_1_cfg.channel_config.forwarding_fee_proportional_millionths = 100_000;
1076         let mut node_2_cfg = test_default_channel_config();
1077         node_2_cfg.channel_handshake_config.our_htlc_minimum_msat = 5000;
1078         node_2_cfg.channel_config.forwarding_fee_base_msat = 200;
1079         node_2_cfg.channel_config.forwarding_fee_proportional_millionths = 150_000;
1080         let mut node_3_cfg = test_default_channel_config();
1081         node_3_cfg.channel_handshake_config.our_htlc_minimum_msat = 2000;
1082         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, Some(node_1_cfg), Some(node_2_cfg), Some(node_3_cfg)]);
1083         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1084         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
1085         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0);
1086         let chan_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0);
1087
1088         let min_htlc_msat = {
1089                 // The min htlc for this setup is nodes[2]'s htlc_minimum_msat minus the
1090                 // following fees.
1091                 let post_base_fee = chan_2_3.1.contents.htlc_minimum_msat - chan_2_3.0.contents.fee_base_msat as u64;
1092                 let prop_fee = chan_2_3.0.contents.fee_proportional_millionths as u64;
1093                 (post_base_fee * 1_000_000 + 1_000_000 + prop_fee - 1) / (prop_fee + 1_000_000)
1094         };
1095         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[3], Some(min_htlc_msat), None);
1096         let mut route_params = get_blinded_route_parameters(
1097                 min_htlc_msat, payment_secret, chan_1_2.1.contents.htlc_minimum_msat,
1098                 chan_1_2.1.contents.htlc_maximum_msat, vec![nodes[1].node.get_our_node_id(),
1099                 nodes[2].node.get_our_node_id(), nodes[3].node.get_our_node_id()],
1100                 &[&chan_1_2.0.contents, &chan_2_3.0.contents], &chanmon_cfgs[3].keys_manager);
1101         assert_eq!(min_htlc_msat,
1102                 route_params.payment_params.payee.blinded_route_hints()[0].0.htlc_minimum_msat);
1103
1104         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0)).unwrap();
1105         check_added_monitors(&nodes[0], 1);
1106         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2], &nodes[3]]], min_htlc_msat, payment_hash, payment_secret);
1107         claim_payment(&nodes[0], &[&nodes[1], &nodes[2], &nodes[3]], payment_preimage);
1108
1109         // Paying 1 less than the min fails.
1110         for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS + 1 {
1111                 nodes[0].node.timer_tick_occurred();
1112         }
1113         if let Payee::Blinded { ref mut route_hints, .. } = route_params.payment_params.payee {
1114                 route_hints[0].0.htlc_minimum_msat -= 1;
1115         } else { panic!() }
1116         route_params.final_value_msat -= 1;
1117         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
1118         check_added_monitors(&nodes[0], 1);
1119
1120         let mut payment_event_0_1 = {
1121                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1122                 assert_eq!(events.len(), 1);
1123                 let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
1124                 SendEvent::from_event(ev)
1125         };
1126         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_0_1.msgs[0]);
1127         check_added_monitors!(nodes[1], 0);
1128         do_commitment_signed_dance(&nodes[1], &nodes[0], &payment_event_0_1.commitment_msg, true, true);
1129         let mut updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1130         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1131         do_commitment_signed_dance(&nodes[0], &nodes[1], &updates.commitment_signed, false, false);
1132         expect_payment_failed_conditions(&nodes[0], payment_hash, false,
1133                 PaymentFailedConditions::new().expected_htlc_error_data(INVALID_ONION_BLINDING, &[0; 32]));
1134 }
1135
1136 #[test]
1137 fn conditionally_round_fwd_amt() {
1138         // Previously, the (rng-found) feerates below caught a bug where an intermediate node would
1139         // calculate an amt_to_forward that underpaid them by 1 msat, caused by rounding up the outbound
1140         // amount on top of an already rounded-up total routing fee. Ensure that we'll conditionally round
1141         // down intermediate nodes' outbound amounts based on whether rounding up will result in
1142         // undercharging for relay.
1143         let chanmon_cfgs = create_chanmon_cfgs(5);
1144         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1145
1146         let mut node_1_cfg = test_default_channel_config();
1147         node_1_cfg.channel_config.forwarding_fee_base_msat = 247371;
1148         node_1_cfg.channel_config.forwarding_fee_proportional_millionths = 86552;
1149
1150         let mut node_2_cfg = test_default_channel_config();
1151         node_2_cfg.channel_config.forwarding_fee_base_msat = 198921;
1152         node_2_cfg.channel_config.forwarding_fee_proportional_millionths = 681759;
1153
1154         let mut node_3_cfg = test_default_channel_config();
1155         node_3_cfg.channel_config.forwarding_fee_base_msat = 132845;
1156         node_3_cfg.channel_config.forwarding_fee_proportional_millionths = 552561;
1157
1158         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, Some(node_1_cfg), Some(node_2_cfg), Some(node_3_cfg), None]);
1159         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1160         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
1161         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0);
1162         let chan_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0);
1163         let chan_3_4 = create_announced_chan_between_nodes_with_value(&nodes, 3, 4, 1_000_000, 0);
1164
1165         let amt_msat = 100_000;
1166         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[4], Some(amt_msat), None);
1167         let mut route_params = get_blinded_route_parameters(amt_msat, payment_secret,
1168                 chan_1_2.1.contents.htlc_minimum_msat, chan_1_2.1.contents.htlc_maximum_msat,
1169                 vec![nodes[1].node.get_our_node_id(), nodes[2].node.get_our_node_id(),
1170                 nodes[3].node.get_our_node_id(), nodes[4].node.get_our_node_id()],
1171                 &[&chan_1_2.0.contents, &chan_2_3.0.contents, &chan_3_4.0.contents],
1172                 &chanmon_cfgs[4].keys_manager);
1173         route_params.max_total_routing_fee_msat = None;
1174
1175         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
1176         check_added_monitors(&nodes[0], 1);
1177         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2], &nodes[3], &nodes[4]]], amt_msat, payment_hash, payment_secret);
1178         nodes[4].node.claim_funds(payment_preimage);
1179         let expected_path = &[&nodes[1], &nodes[2], &nodes[3], &nodes[4]];
1180         let expected_route = &[&expected_path[..]];
1181         let mut args = ClaimAlongRouteArgs::new(&nodes[0], &expected_route[..], payment_preimage)
1182                 .allow_1_msat_fee_overpay();
1183         let expected_fee = pass_claimed_payment_along_route(args);
1184         expect_payment_sent(&nodes[0], payment_preimage, Some(Some(expected_fee)), true, true);
1185 }
1186
1187 #[test]
1188 fn blinded_keysend() {
1189         let mut mpp_keysend_config = test_default_channel_config();
1190         mpp_keysend_config.accept_mpp_keysend = true;
1191         let chanmon_cfgs = create_chanmon_cfgs(3);
1192         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1193         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, Some(mpp_keysend_config)]);
1194         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1195         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
1196         let chan_upd_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0).0.contents;
1197
1198         let amt_msat = 5000;
1199         let (keysend_preimage, _, payment_secret) = get_payment_preimage_hash(&nodes[2], None, None);
1200         let route_params = get_blinded_route_parameters(amt_msat, payment_secret, 1,
1201                 1_0000_0000,
1202                 nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(),
1203                 &[&chan_upd_1_2], &chanmon_cfgs[2].keys_manager);
1204
1205         let payment_hash = nodes[0].node.send_spontaneous_payment_with_retry(Some(keysend_preimage), RecipientOnionFields::spontaneous_empty(), PaymentId(keysend_preimage.0), route_params, Retry::Attempts(0)).unwrap();
1206         check_added_monitors(&nodes[0], 1);
1207
1208         let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[2]]];
1209         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1210         assert_eq!(events.len(), 1);
1211
1212         let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
1213         pass_along_path(&nodes[0], expected_route[0], amt_msat, payment_hash, Some(payment_secret), ev.clone(), true, Some(keysend_preimage));
1214         claim_payment_along_route(&nodes[0], expected_route, false, keysend_preimage);
1215 }
1216
1217 #[test]
1218 fn blinded_mpp_keysend() {
1219         let mut mpp_keysend_config = test_default_channel_config();
1220         mpp_keysend_config.accept_mpp_keysend = true;
1221         let chanmon_cfgs = create_chanmon_cfgs(4);
1222         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1223         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(mpp_keysend_config)]);
1224         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1225
1226         create_announced_chan_between_nodes(&nodes, 0, 1);
1227         create_announced_chan_between_nodes(&nodes, 0, 2);
1228         let chan_1_3 = create_announced_chan_between_nodes(&nodes, 1, 3);
1229         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
1230
1231         let amt_msat = 15_000_000;
1232         let (keysend_preimage, _, payment_secret) = get_payment_preimage_hash(&nodes[3], None, None);
1233         let route_params = {
1234                 let pay_params = PaymentParameters::blinded(
1235                         vec![
1236                                 blinded_payment_path(payment_secret, 1, 1_0000_0000,
1237                                         vec![nodes[1].node.get_our_node_id(), nodes[3].node.get_our_node_id()], &[&chan_1_3.0.contents],
1238                                         &chanmon_cfgs[3].keys_manager
1239                                 ),
1240                                 blinded_payment_path(payment_secret, 1, 1_0000_0000,
1241                                         vec![nodes[2].node.get_our_node_id(), nodes[3].node.get_our_node_id()], &[&chan_2_3.0.contents],
1242                                         &chanmon_cfgs[3].keys_manager
1243                                 ),
1244                         ]
1245                 )
1246                         .with_bolt12_features(channelmanager::provided_bolt12_invoice_features(&UserConfig::default()))
1247                         .unwrap();
1248                 RouteParameters::from_payment_params_and_value(pay_params, amt_msat)
1249         };
1250
1251         let payment_hash = nodes[0].node.send_spontaneous_payment_with_retry(Some(keysend_preimage), RecipientOnionFields::spontaneous_empty(), PaymentId(keysend_preimage.0), route_params, Retry::Attempts(0)).unwrap();
1252         check_added_monitors!(nodes[0], 2);
1253
1254         let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
1255         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1256         assert_eq!(events.len(), 2);
1257
1258         let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
1259         pass_along_path(&nodes[0], expected_route[0], amt_msat, payment_hash.clone(),
1260                 Some(payment_secret), ev.clone(), false, Some(keysend_preimage));
1261
1262         let ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
1263         pass_along_path(&nodes[0], expected_route[1], amt_msat, payment_hash.clone(),
1264                 Some(payment_secret), ev.clone(), true, Some(keysend_preimage));
1265         claim_payment_along_route(&nodes[0], expected_route, false, keysend_preimage);
1266 }
1267
1268 #[test]
1269 fn custom_tlvs_to_blinded_path() {
1270         let chanmon_cfgs = create_chanmon_cfgs(2);
1271         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1272         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1273         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1274         let chan_upd = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0).0.contents;
1275
1276         let amt_msat = 5000;
1277         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(amt_msat), None);
1278         let payee_tlvs = ReceiveTlvs {
1279                 payment_secret,
1280                 payment_constraints: PaymentConstraints {
1281                         max_cltv_expiry: u32::max_value(),
1282                         htlc_minimum_msat: chan_upd.htlc_minimum_msat,
1283                 },
1284         };
1285         let mut secp_ctx = Secp256k1::new();
1286         let blinded_path = BlindedPath::one_hop_for_payment(
1287                 nodes[1].node.get_our_node_id(), payee_tlvs, TEST_FINAL_CLTV as u16,
1288                 &chanmon_cfgs[1].keys_manager, &secp_ctx
1289         ).unwrap();
1290
1291         let route_params = RouteParameters::from_payment_params_and_value(
1292                 PaymentParameters::blinded(vec![blinded_path]),
1293                 amt_msat,
1294         );
1295
1296         let recipient_onion_fields = RecipientOnionFields::spontaneous_empty()
1297                 .with_custom_tlvs(vec![((1 << 16) + 1, vec![42, 42])])
1298                 .unwrap();
1299         nodes[0].node.send_payment(payment_hash, recipient_onion_fields.clone(),
1300                 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
1301         check_added_monitors(&nodes[0], 1);
1302
1303         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1304         assert_eq!(events.len(), 1);
1305         let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
1306
1307         let path = &[&nodes[1]];
1308         let args = PassAlongPathArgs::new(&nodes[0], path, amt_msat, payment_hash, ev)
1309                 .with_payment_secret(payment_secret)
1310                 .with_custom_tlvs(recipient_onion_fields.custom_tlvs.clone());
1311         do_pass_along_path(args);
1312         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
1313 }