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