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