]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/blinded_payment_tests.rs
22fe1b1a3571e3a141285eb2c483fc4e87af070a
[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::{HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
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;
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, node_ids: Vec<PublicKey>,
32         channel_upds: &[&msgs::UnsignedChannelUpdate], keys_manager: &test_utils::TestKeysInterface
33 ) -> (BlindedPayInfo, BlindedPath) {
34         let mut intermediate_nodes = Vec::new();
35         for (node_id, chan_upd) in node_ids.iter().zip(channel_upds) {
36                 intermediate_nodes.push(ForwardNode {
37                         node_id: *node_id,
38                         tlvs: ForwardTlvs {
39                                 short_channel_id: chan_upd.short_channel_id,
40                                 payment_relay: PaymentRelay {
41                                         cltv_expiry_delta: chan_upd.cltv_expiry_delta,
42                                         fee_proportional_millionths: chan_upd.fee_proportional_millionths,
43                                         fee_base_msat: chan_upd.fee_base_msat,
44                                 },
45                                 payment_constraints: PaymentConstraints {
46                                         max_cltv_expiry: u32::max_value(),
47                                         htlc_minimum_msat: chan_upd.htlc_minimum_msat,
48                                 },
49                                 features: BlindedHopFeatures::empty(),
50                         },
51                         htlc_maximum_msat: chan_upd.htlc_maximum_msat,
52                 });
53         }
54         let payee_tlvs = ReceiveTlvs {
55                 payment_secret,
56                 payment_constraints: PaymentConstraints {
57                         max_cltv_expiry: u32::max_value(),
58                         htlc_minimum_msat: channel_upds.last().unwrap().htlc_minimum_msat,
59                 },
60         };
61         let mut secp_ctx = Secp256k1::new();
62         BlindedPath::new_for_payment(
63                 &intermediate_nodes[..], *node_ids.last().unwrap(), payee_tlvs,
64                 channel_upds.last().unwrap().htlc_maximum_msat, keys_manager, &secp_ctx
65         ).unwrap()
66 }
67
68 pub fn get_blinded_route_parameters(
69         amt_msat: u64, payment_secret: PaymentSecret, node_ids: Vec<PublicKey>,
70         channel_upds: &[&msgs::UnsignedChannelUpdate], keys_manager: &test_utils::TestKeysInterface
71 ) -> RouteParameters {
72         RouteParameters::from_payment_params_and_value(
73                 PaymentParameters::blinded(vec![
74                         blinded_payment_path(payment_secret, node_ids, channel_upds, keys_manager)
75                 ]), amt_msat
76         )
77 }
78
79 #[test]
80 fn one_hop_blinded_path() {
81         do_one_hop_blinded_path(true);
82         do_one_hop_blinded_path(false);
83 }
84
85 fn do_one_hop_blinded_path(success: bool) {
86         let chanmon_cfgs = create_chanmon_cfgs(2);
87         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
88         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
89         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
90         let chan_upd = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0).0.contents;
91
92         let amt_msat = 5000;
93         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(amt_msat), None);
94         let payee_tlvs = ReceiveTlvs {
95                 payment_secret,
96                 payment_constraints: PaymentConstraints {
97                         max_cltv_expiry: u32::max_value(),
98                         htlc_minimum_msat: chan_upd.htlc_minimum_msat,
99                 },
100         };
101         let mut secp_ctx = Secp256k1::new();
102         let blinded_path = BlindedPath::one_hop_for_payment(
103                 nodes[1].node.get_our_node_id(), payee_tlvs, &chanmon_cfgs[1].keys_manager, &secp_ctx
104         ).unwrap();
105
106         let route_params = RouteParameters::from_payment_params_and_value(
107                 PaymentParameters::blinded(vec![blinded_path]),
108                 amt_msat,
109         );
110         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(),
111         PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
112         check_added_monitors(&nodes[0], 1);
113         pass_along_route(&nodes[0], &[&[&nodes[1]]], amt_msat, payment_hash, payment_secret);
114         if success {
115                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
116         } else {
117                 fail_payment(&nodes[0], &[&nodes[1]], payment_hash);
118         }
119 }
120
121 #[test]
122 fn mpp_to_one_hop_blinded_path() {
123         let chanmon_cfgs = create_chanmon_cfgs(4);
124         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
125         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
126         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
127         let mut secp_ctx = Secp256k1::new();
128
129         create_announced_chan_between_nodes(&nodes, 0, 1);
130         create_announced_chan_between_nodes(&nodes, 0, 2);
131         let chan_upd_1_3 = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents;
132         create_announced_chan_between_nodes(&nodes, 2, 3).0.contents;
133
134         let amt_msat = 15_000_000;
135         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[3], Some(amt_msat), None);
136         let payee_tlvs = ReceiveTlvs {
137                 payment_secret,
138                 payment_constraints: PaymentConstraints {
139                         max_cltv_expiry: u32::max_value(),
140                         htlc_minimum_msat: chan_upd_1_3.htlc_minimum_msat,
141                 },
142         };
143         let blinded_path = BlindedPath::one_hop_for_payment(
144                 nodes[3].node.get_our_node_id(), payee_tlvs, &chanmon_cfgs[3].keys_manager, &secp_ctx
145         ).unwrap();
146
147         let bolt12_features =
148                 channelmanager::provided_bolt12_invoice_features(&UserConfig::default());
149         let route_params = RouteParameters::from_payment_params_and_value(
150                 PaymentParameters::blinded(vec![blinded_path]).with_bolt12_features(bolt12_features).unwrap(),
151                 amt_msat,
152         );
153         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
154         check_added_monitors(&nodes[0], 2);
155
156         let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
157         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
158         assert_eq!(events.len(), 2);
159
160         let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
161         pass_along_path(&nodes[0], expected_route[0], amt_msat, payment_hash.clone(),
162                 Some(payment_secret), ev.clone(), false, None);
163
164         let ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
165         pass_along_path(&nodes[0], expected_route[1], amt_msat, payment_hash.clone(),
166                 Some(payment_secret), ev.clone(), true, None);
167         claim_payment_along_route(&nodes[0], expected_route, false, payment_preimage);
168 }
169
170 enum ForwardCheckFail {
171         // Fail a check on the inbound onion payload. In this case, we underflow when calculating the
172         // outgoing cltv_expiry.
173         InboundOnionCheck,
174         // The forwarding node's payload is encoded as a receive, i.e. the next hop HMAC is [0; 32].
175         ForwardPayloadEncodedAsReceive,
176         // Fail a check on the outbound channel. In this case, our next-hop peer is offline.
177         OutboundChannelCheck,
178 }
179
180 #[test]
181 fn forward_checks_failure() {
182         do_forward_checks_failure(ForwardCheckFail::InboundOnionCheck);
183         do_forward_checks_failure(ForwardCheckFail::ForwardPayloadEncodedAsReceive);
184         do_forward_checks_failure(ForwardCheckFail::OutboundChannelCheck);
185 }
186
187 fn do_forward_checks_failure(check: ForwardCheckFail) {
188         // Ensure we'll fail backwards properly if a forwarding check fails on initial update_add
189         // receipt.
190         let chanmon_cfgs = create_chanmon_cfgs(3);
191         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
192         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
193         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
194         // We need the session priv to construct a bogus onion packet later.
195         *nodes[0].keys_manager.override_random_bytes.lock().unwrap() = Some([3; 32]);
196         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
197         let chan_upd_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0).0.contents;
198
199         let amt_msat = 5000;
200         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[2], Some(amt_msat), None);
201         let route_params = get_blinded_route_parameters(amt_msat, payment_secret,
202                 nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(), &[&chan_upd_1_2],
203                 &chanmon_cfgs[2].keys_manager);
204
205         let route = get_route(&nodes[0], &route_params).unwrap();
206         node_cfgs[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
207         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
208         check_added_monitors(&nodes[0], 1);
209
210         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
211         assert_eq!(events.len(), 1);
212         let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
213         let mut payment_event = SendEvent::from_event(ev);
214
215         let mut update_add = &mut payment_event.msgs[0];
216         match check {
217                 ForwardCheckFail::InboundOnionCheck => {
218                         update_add.cltv_expiry = 10; // causes outbound CLTV expiry to underflow
219                 },
220                 ForwardCheckFail::ForwardPayloadEncodedAsReceive => {
221                         let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
222                         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
223                         let cur_height = nodes[0].best_block_info().1;
224                         let (mut onion_payloads, ..) = onion_utils::build_onion_payloads(
225                                 &route.paths[0], amt_msat, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
226                         // Remove the receive payload so the blinded forward payload is encoded as a final payload
227                         // (i.e. next_hop_hmac == [0; 32])
228                         onion_payloads.pop();
229                         update_add.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
230                 },
231                 ForwardCheckFail::OutboundChannelCheck => {
232                         // The intro node will see that the next-hop peer is disconnected and fail the HTLC backwards.
233                         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
234                 },
235         }
236         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
237         check_added_monitors!(nodes[1], 0);
238         do_commitment_signed_dance(&nodes[1], &nodes[0], &payment_event.commitment_msg, true, true);
239
240         let mut updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
241         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
242         do_commitment_signed_dance(&nodes[0], &nodes[1], &updates.commitment_signed, false, false);
243         expect_payment_failed_conditions(&nodes[0], payment_hash, false,
244                 PaymentFailedConditions::new().expected_htlc_error_data(INVALID_ONION_BLINDING, &[0; 32]));
245 }
246
247 #[test]
248 fn failed_backwards_to_intro_node() {
249         // Ensure the intro node will error backwards properly even if the downstream node did not blind
250         // their error.
251         let chanmon_cfgs = create_chanmon_cfgs(3);
252         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
253         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
254         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
255         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
256         let chan_upd_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0).0.contents;
257
258         let amt_msat = 5000;
259         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[2], Some(amt_msat), None);
260         let route_params = get_blinded_route_parameters(amt_msat, payment_secret,
261                 nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(), &[&chan_upd_1_2],
262                 &chanmon_cfgs[2].keys_manager);
263
264         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
265         check_added_monitors(&nodes[0], 1);
266
267         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
268         assert_eq!(events.len(), 1);
269         let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
270         let mut payment_event = SendEvent::from_event(ev);
271
272         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
273         check_added_monitors!(nodes[1], 0);
274         do_commitment_signed_dance(&nodes[1], &nodes[0], &payment_event.commitment_msg, false, false);
275         expect_pending_htlcs_forwardable!(nodes[1]);
276         check_added_monitors!(&nodes[1], 1);
277
278         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
279         assert_eq!(events.len(), 1);
280         let ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
281         let mut payment_event = SendEvent::from_event(ev);
282
283         // Ensure the final node fails to handle the HTLC.
284         payment_event.msgs[0].onion_routing_packet.hop_data[0] ^= 1;
285         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
286         check_added_monitors!(nodes[2], 0);
287         do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event.commitment_msg, true, true);
288         nodes[2].node.process_pending_htlc_forwards();
289
290         let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
291         let mut update_malformed = &mut updates.update_fail_malformed_htlcs[0];
292         // Check that the final node encodes its failure correctly.
293         assert_eq!(update_malformed.failure_code, INVALID_ONION_BLINDING);
294         assert_eq!(update_malformed.sha256_of_onion, [0; 32]);
295
296         // Modify such the final hop does not correctly blind their error so we can ensure the intro node
297         // converts it to the correct error.
298         update_malformed.sha256_of_onion = [1; 32];
299         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), update_malformed);
300         do_commitment_signed_dance(&nodes[1], &nodes[2], &updates.commitment_signed, true, false);
301
302         let mut updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
303         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
304         do_commitment_signed_dance(&nodes[0], &nodes[1], &updates.commitment_signed, false, false);
305         expect_payment_failed_conditions(&nodes[0], payment_hash, false,
306                 PaymentFailedConditions::new().expected_htlc_error_data(INVALID_ONION_BLINDING, &[0; 32]));
307 }
308
309 enum ProcessPendingHTLCsCheck {
310         FwdPeerDisconnected,
311         FwdChannelClosed,
312 }
313
314 #[test]
315 fn forward_fail_in_process_pending_htlc_fwds() {
316         do_forward_fail_in_process_pending_htlc_fwds(ProcessPendingHTLCsCheck::FwdPeerDisconnected);
317         do_forward_fail_in_process_pending_htlc_fwds(ProcessPendingHTLCsCheck::FwdChannelClosed);
318 }
319 fn do_forward_fail_in_process_pending_htlc_fwds(check: ProcessPendingHTLCsCheck) {
320         // Ensure the intro node will error backwards properly if the HTLC fails in
321         // process_pending_htlc_forwards.
322         let chanmon_cfgs = create_chanmon_cfgs(3);
323         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
324         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
325         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
326         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
327         let (chan_upd_1_2, channel_id) = {
328                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0);
329                 (chan.0.contents, chan.2)
330         };
331
332         let amt_msat = 5000;
333         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[2], Some(amt_msat), None);
334         let route_params = get_blinded_route_parameters(amt_msat, payment_secret,
335                 nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(), &[&chan_upd_1_2],
336                 &chanmon_cfgs[2].keys_manager);
337
338         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
339         check_added_monitors(&nodes[0], 1);
340
341         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
342         assert_eq!(events.len(), 1);
343         let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
344         let mut payment_event = SendEvent::from_event(ev);
345
346         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
347         check_added_monitors!(nodes[1], 0);
348         do_commitment_signed_dance(&nodes[1], &nodes[0], &payment_event.commitment_msg, false, false);
349
350         match check {
351                 ProcessPendingHTLCsCheck::FwdPeerDisconnected => {
352                         // Disconnect the next-hop peer so when we go to forward in process_pending_htlc_forwards, the
353                         // intro node will error backwards.
354                         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
355                         expect_pending_htlcs_forwardable!(nodes[1]);
356                         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
357                                 vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id }]);
358                 },
359                 ProcessPendingHTLCsCheck::FwdChannelClosed => {
360                         // Force close the next-hop channel so when we go to forward in process_pending_htlc_forwards,
361                         // the intro node will error backwards.
362                         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
363                         let events = nodes[1].node.get_and_clear_pending_events();
364                         match events[0] {
365                                 crate::events::Event::PendingHTLCsForwardable { .. } => {},
366                                 _ => panic!("Unexpected event {:?}", events),
367                         };
368                         match events[1] {
369                                 crate::events::Event::ChannelClosed { .. } => {},
370                                 _ => panic!("Unexpected event {:?}", events),
371                         }
372
373                         nodes[1].node.process_pending_htlc_forwards();
374                         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
375                                 vec![HTLCDestination::UnknownNextHop { requested_forward_scid: chan_upd_1_2.short_channel_id }]);
376                         check_closed_broadcast(&nodes[1], 1, true);
377                         check_added_monitors!(nodes[1], 1);
378                         nodes[1].node.process_pending_htlc_forwards();
379                 },
380         }
381
382         let mut updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
383         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
384         check_added_monitors!(nodes[1], 1);
385         do_commitment_signed_dance(&nodes[0], &nodes[1], &updates.commitment_signed, false, false);
386
387         expect_payment_failed_conditions(&nodes[0], payment_hash, false,
388                 PaymentFailedConditions::new().expected_htlc_error_data(INVALID_ONION_BLINDING, &[0; 32]));
389 }
390
391 #[test]
392 fn blinded_intercept_payment() {
393         do_blinded_intercept_payment(true);
394         do_blinded_intercept_payment(false);
395 }
396 fn do_blinded_intercept_payment(intercept_node_fails: bool) {
397         let chanmon_cfgs = create_chanmon_cfgs(3);
398         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
399         let mut intercept_forwards_config = test_default_channel_config();
400         intercept_forwards_config.accept_intercept_htlcs = true;
401         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), None]);
402         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
403         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
404         let (channel_id, chan_upd) = {
405                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0);
406                 (chan.2, chan.0.contents)
407         };
408
409         let amt_msat = 5000;
410         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[2], Some(amt_msat), None);
411         let intercept_scid = nodes[1].node.get_intercept_scid();
412         let mut intercept_chan_upd = chan_upd;
413         intercept_chan_upd.short_channel_id = intercept_scid;
414         let route_params = get_blinded_route_parameters(amt_msat, payment_secret,
415                 nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(), &[&intercept_chan_upd],
416                 &chanmon_cfgs[2].keys_manager);
417
418         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(),
419         PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
420         check_added_monitors(&nodes[0], 1);
421         let payment_event = {
422                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
423                 assert_eq!(events.len(), 1);
424                 SendEvent::from_event(events.remove(0))
425         };
426         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
427         commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
428
429         let events = nodes[1].node.get_and_clear_pending_events();
430         assert_eq!(events.len(), 1);
431         let (intercept_id, expected_outbound_amount_msat) = match events[0] {
432                 crate::events::Event::HTLCIntercepted {
433                         intercept_id, payment_hash: pmt_hash,
434                         requested_next_hop_scid: short_channel_id, expected_outbound_amount_msat, ..
435                 } => {
436                         assert_eq!(pmt_hash, payment_hash);
437                         assert_eq!(short_channel_id, intercept_scid);
438                         (intercept_id, expected_outbound_amount_msat)
439                 },
440                 _ => panic!()
441         };
442
443         if intercept_node_fails {
444                 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
445                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
446                 nodes[1].node.process_pending_htlc_forwards();
447                 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
448                 check_added_monitors!(&nodes[1], 1);
449                 assert!(update_fail.update_fail_htlcs.len() == 1);
450                 let fail_msg = update_fail.update_fail_htlcs[0].clone();
451                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
452                 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
453                 expect_payment_failed_conditions(&nodes[0], payment_hash, false,
454                         PaymentFailedConditions::new().expected_htlc_error_data(INVALID_ONION_BLINDING, &[0; 32]));
455                 return
456         }
457
458         nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
459         expect_pending_htlcs_forwardable!(nodes[1]);
460
461         let payment_event = {
462                 {
463                         let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
464                         assert_eq!(added_monitors.len(), 1);
465                         added_monitors.clear();
466                 }
467                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
468                 assert_eq!(events.len(), 1);
469                 SendEvent::from_event(events.remove(0))
470         };
471         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
472         commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
473         expect_pending_htlcs_forwardable!(nodes[2]);
474
475         expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, None, nodes[2].node.get_our_node_id());
476         do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
477         expect_payment_sent(&nodes[0], payment_preimage, Some(Some(1000)), true, true);
478 }
479
480 #[test]
481 fn two_hop_blinded_path_success() {
482         let chanmon_cfgs = create_chanmon_cfgs(3);
483         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
484         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
485         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
486         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
487         let chan_upd_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0).0.contents;
488
489         let amt_msat = 5000;
490         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[2], Some(amt_msat), None);
491         let route_params = get_blinded_route_parameters(amt_msat, payment_secret,
492                 nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(), &[&chan_upd_1_2],
493                 &chanmon_cfgs[2].keys_manager);
494
495         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
496         check_added_monitors(&nodes[0], 1);
497         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], amt_msat, payment_hash, payment_secret);
498         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
499 }
500
501 #[derive(PartialEq)]
502 enum ReceiveCheckFail {
503         // The recipient fails the payment upon `PaymentClaimable`.
504         RecipientFail,
505         // Failure to decode the recipient's onion payload.
506         OnionDecodeFail,
507         // The incoming HTLC did not satisfy our requirements; in this case it underpaid us according to
508         // the expected receive amount in the onion.
509         ReceiveRequirements,
510         // The incoming HTLC errors when added to the Channel, in this case due to the HTLC being
511         // delivered out-of-order with a shutdown message.
512         ChannelCheck,
513         // The HTLC is successfully added to the inbound channel but fails receive checks in
514         // process_pending_htlc_forwards.
515         ProcessPendingHTLCsCheck,
516         // The HTLC violates the `PaymentConstraints` contained within the receiver's encrypted payload.
517         PaymentConstraints,
518 }
519
520 #[test]
521 fn multi_hop_receiver_fail() {
522         do_multi_hop_receiver_fail(ReceiveCheckFail::RecipientFail);
523         do_multi_hop_receiver_fail(ReceiveCheckFail::OnionDecodeFail);
524         do_multi_hop_receiver_fail(ReceiveCheckFail::ReceiveRequirements);
525         do_multi_hop_receiver_fail(ReceiveCheckFail::ChannelCheck);
526         do_multi_hop_receiver_fail(ReceiveCheckFail::ProcessPendingHTLCsCheck);
527         do_multi_hop_receiver_fail(ReceiveCheckFail::PaymentConstraints);
528 }
529
530 fn do_multi_hop_receiver_fail(check: ReceiveCheckFail) {
531         // Test that the receiver to a multihop blinded path fails back correctly.
532         let chanmon_cfgs = create_chanmon_cfgs(3);
533         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
534         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
535         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
536         // We need the session priv to construct an invalid onion packet later.
537         let session_priv = [3; 32];
538         *nodes[0].keys_manager.override_random_bytes.lock().unwrap() = Some(session_priv);
539         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
540         let (chan_upd_1_2, chan_id_1_2) = {
541                 let (chan_upd, _, channel_id, ..) = create_announced_chan_between_nodes_with_value(
542                         &nodes, 1, 2, 1_000_000, 0
543                 );
544                 (chan_upd.contents, channel_id)
545         };
546
547         let amt_msat = 5000;
548         let final_cltv_delta = if check == ReceiveCheckFail::ProcessPendingHTLCsCheck {
549                 // Set the final CLTV expiry too low to trigger the failure in process_pending_htlc_forwards.
550                 Some(TEST_FINAL_CLTV as u16 - 2)
551         } else { None };
552         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[2], Some(amt_msat), final_cltv_delta);
553         let mut route_params = get_blinded_route_parameters(amt_msat, payment_secret,
554                 nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(), &[&chan_upd_1_2],
555                 &chanmon_cfgs[2].keys_manager);
556
557         let route = if check == ReceiveCheckFail::ProcessPendingHTLCsCheck {
558                 let mut route = get_route(&nodes[0], &route_params).unwrap();
559                 // Set the final CLTV expiry too low to trigger the failure in process_pending_htlc_forwards.
560                 route.paths[0].blinded_tail.as_mut().map(|bt| bt.excess_final_cltv_expiry_delta = TEST_FINAL_CLTV - 2);
561                 route
562         } else if check == ReceiveCheckFail::PaymentConstraints {
563                 // Create a blinded path where the receiver's encrypted payload has an htlc_minimum_msat that is
564                 // violated by `amt_msat`, and stick it in the route_params without changing the corresponding
565                 // BlindedPayInfo (to ensure pathfinding still succeeds).
566                 let high_htlc_min_bp = {
567                         let mut high_htlc_minimum_upd = chan_upd_1_2.clone();
568                         high_htlc_minimum_upd.htlc_minimum_msat = amt_msat + 1000;
569                         let high_htlc_min_params = get_blinded_route_parameters(amt_msat, payment_secret,
570                                 nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(), &[&high_htlc_minimum_upd],
571                                 &chanmon_cfgs[2].keys_manager);
572                         if let Payee::Blinded { route_hints, .. } = high_htlc_min_params.payment_params.payee {
573                                 route_hints[0].1.clone()
574                         } else { panic!() }
575                 };
576                 if let Payee::Blinded { ref mut route_hints, .. } = route_params.payment_params.payee {
577                         route_hints[0].1 = high_htlc_min_bp;
578                 } else { panic!() }
579                 find_route(&nodes[0], &route_params).unwrap()
580         } else {
581                 find_route(&nodes[0], &route_params).unwrap()
582         };
583         node_cfgs[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
584         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
585         check_added_monitors(&nodes[0], 1);
586
587         let mut payment_event_0_1 = {
588                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
589                 assert_eq!(events.len(), 1);
590                 let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
591                 SendEvent::from_event(ev)
592         };
593         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_0_1.msgs[0]);
594         check_added_monitors!(nodes[1], 0);
595         do_commitment_signed_dance(&nodes[1], &nodes[0], &payment_event_0_1.commitment_msg, false, false);
596         expect_pending_htlcs_forwardable!(nodes[1]);
597         check_added_monitors!(&nodes[1], 1);
598
599         let mut payment_event_1_2 = {
600                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
601                 assert_eq!(events.len(), 1);
602                 let ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
603                 SendEvent::from_event(ev)
604         };
605
606         match check {
607                 ReceiveCheckFail::RecipientFail => {
608                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_1_2.msgs[0]);
609                         check_added_monitors!(nodes[2], 0);
610                         do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event_1_2.commitment_msg, true, true);
611                         expect_pending_htlcs_forwardable!(nodes[2]);
612                         check_payment_claimable(
613                                 &nodes[2].node.get_and_clear_pending_events()[0], payment_hash, payment_secret, amt_msat,
614                                 None, nodes[2].node.get_our_node_id()
615                         );
616                         nodes[2].node.fail_htlc_backwards(&payment_hash);
617                         expect_pending_htlcs_forwardable_conditions(
618                                 nodes[2].node.get_and_clear_pending_events(), &[HTLCDestination::FailedPayment { payment_hash }]
619                         );
620                         nodes[2].node.process_pending_htlc_forwards();
621                         check_added_monitors!(nodes[2], 1);
622                 },
623                 ReceiveCheckFail::OnionDecodeFail => {
624                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
625                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
626                         let cur_height = nodes[0].best_block_info().1;
627                         let (mut onion_payloads, ..) = onion_utils::build_onion_payloads(
628                                 &route.paths[0], amt_msat, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
629
630                         let update_add = &mut payment_event_1_2.msgs[0];
631                         onion_payloads.last_mut().map(|p| {
632                                 if let msgs::OutboundOnionPayload::BlindedReceive { ref mut intro_node_blinding_point, .. } = p {
633                                         // The receiver should error if both the update_add blinding_point and the
634                                         // intro_node_blinding_point are set.
635                                         assert!(intro_node_blinding_point.is_none() && update_add.blinding_point.is_some());
636                                         *intro_node_blinding_point = Some(PublicKey::from_slice(&[2; 33]).unwrap());
637                                 } else { panic!() }
638                         });
639                         update_add.onion_routing_packet = onion_utils::construct_onion_packet(
640                                 vec![onion_payloads.pop().unwrap()], vec![onion_keys.pop().unwrap()], [0; 32],
641                                 &payment_hash
642                         ).unwrap();
643                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update_add);
644                         check_added_monitors!(nodes[2], 0);
645                         do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event_1_2.commitment_msg, true, true);
646                 },
647                 ReceiveCheckFail::ReceiveRequirements => {
648                         let update_add = &mut payment_event_1_2.msgs[0];
649                         update_add.amount_msat -= 1;
650                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update_add);
651                         check_added_monitors!(nodes[2], 0);
652                         do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event_1_2.commitment_msg, true, true);
653                 },
654                 ReceiveCheckFail::ChannelCheck => {
655                         nodes[2].node.close_channel(&chan_id_1_2, &nodes[1].node.get_our_node_id()).unwrap();
656                         let node_2_shutdown = get_event_msg!(nodes[2], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
657                         nodes[1].node.handle_shutdown(&nodes[2].node.get_our_node_id(), &node_2_shutdown);
658                         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
659
660                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_1_2.msgs[0]);
661                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event_1_2.commitment_msg);
662                         check_added_monitors!(nodes[2], 1);
663
664                         nodes[2].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
665                         commitment_signed_dance!(nodes[2], nodes[1], (), false, true, false, false);
666                 },
667                 ReceiveCheckFail::ProcessPendingHTLCsCheck => {
668                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_1_2.msgs[0]);
669                         check_added_monitors!(nodes[2], 0);
670                         do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event_1_2.commitment_msg, true, true);
671                         expect_pending_htlcs_forwardable!(nodes[2]);
672                         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[2],
673                                 vec![HTLCDestination::FailedPayment { payment_hash }]);
674                         check_added_monitors!(nodes[2], 1);
675                 },
676                 ReceiveCheckFail::PaymentConstraints => {
677                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_1_2.msgs[0]);
678                         check_added_monitors!(nodes[2], 0);
679                         do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event_1_2.commitment_msg, true, true);
680                 }
681         }
682
683         let updates_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
684         assert_eq!(updates_2_1.update_fail_malformed_htlcs.len(), 1);
685         let update_malformed = &updates_2_1.update_fail_malformed_htlcs[0];
686         assert_eq!(update_malformed.sha256_of_onion, [0; 32]);
687         assert_eq!(update_malformed.failure_code, INVALID_ONION_BLINDING);
688         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), update_malformed);
689         do_commitment_signed_dance(&nodes[1], &nodes[2], &updates_2_1.commitment_signed, true, false);
690
691         let updates_1_0 = if check == ReceiveCheckFail::ChannelCheck {
692                 let events = nodes[1].node.get_and_clear_pending_msg_events();
693                 assert_eq!(events.len(), 2);
694                 events.into_iter().find_map(|ev| {
695                         match ev {
696                                 MessageSendEvent:: UpdateHTLCs { node_id, updates } => {
697                                         assert_eq!(node_id, nodes[0].node.get_our_node_id());
698                                         return Some(updates)
699                                 },
700                                 MessageSendEvent::SendClosingSigned { .. } => None,
701                                 _ => panic!()
702                         }
703                 }).unwrap()
704         } else { get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()) };
705         assert_eq!(updates_1_0.update_fail_htlcs.len(), 1);
706         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_1_0.update_fail_htlcs[0]);
707         do_commitment_signed_dance(&nodes[0], &nodes[1], &updates_1_0.commitment_signed, false, false);
708         expect_payment_failed_conditions(&nodes[0], payment_hash, false,
709                 PaymentFailedConditions::new().expected_htlc_error_data(INVALID_ONION_BLINDING, &[0; 32]));
710 }