]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/onion_route_tests.rs
51a3e048149a5b28ff966edf3c438e78efea61d8
[rust-lightning] / lightning / src / ln / onion_route_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests of the onion error messages/codes which are returned when routing a payment fails.
11 //! These tests work by standing up full nodes and route payments across the network, checking the
12 //! returned errors decode to the correct thing.
13
14 use chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
15 use chain::keysinterface::{KeysInterface, Recipient};
16 use ln::{PaymentHash, PaymentSecret};
17 use ln::channelmanager::{HTLCForwardInfo, CLTV_FAR_FAR_AWAY, MIN_CLTV_EXPIRY_DELTA, PendingHTLCInfo, PendingHTLCRouting};
18 use ln::onion_utils;
19 use routing::gossip::{NetworkUpdate, RoutingFees, NodeId};
20 use routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintHop};
21 use ln::features::{InitFeatures, InvoiceFeatures, NodeFeatures};
22 use ln::msgs;
23 use ln::msgs::{ChannelMessageHandler, ChannelUpdate, OptionalField};
24 use ln::wire::Encode;
25 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider};
26 use util::ser::{Writeable, Writer};
27 use util::{byte_utils, test_utils};
28 use util::config::UserConfig;
29
30 use bitcoin::hash_types::BlockHash;
31
32 use bitcoin::hashes::Hash;
33 use bitcoin::hashes::sha256::Hash as Sha256;
34
35 use bitcoin::secp256k1;
36 use bitcoin::secp256k1::Secp256k1;
37 use bitcoin::secp256k1::{PublicKey, SecretKey};
38
39 use io;
40 use prelude::*;
41 use core::default::Default;
42
43 use ln::functional_test_utils::*;
44
45 fn run_onion_failure_test<F1,F2>(_name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash, payment_secret: &PaymentSecret, callback_msg: F1, callback_node: F2, expected_retryable: bool, expected_error_code: Option<u16>, expected_channel_update: Option<NetworkUpdate>, expected_short_channel_id: Option<u64>)
46         where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
47                                 F2: FnMut(),
48 {
49         run_onion_failure_test_with_fail_intercept(_name, test_case, nodes, route, payment_hash, payment_secret, callback_msg, |_|{}, callback_node, expected_retryable, expected_error_code, expected_channel_update, expected_short_channel_id);
50 }
51
52 // test_case
53 // 0: node1 fails backward
54 // 1: final node fails backward
55 // 2: payment completed but the user rejects the payment
56 // 3: final node fails backward (but tamper onion payloads from node0)
57 // 100: trigger error in the intermediate node and tamper returning fail_htlc
58 // 200: trigger error in the final node and tamper returning fail_htlc
59 fn run_onion_failure_test_with_fail_intercept<F1,F2,F3>(_name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash, payment_secret: &PaymentSecret, mut callback_msg: F1, mut callback_fail: F2, mut callback_node: F3, expected_retryable: bool, expected_error_code: Option<u16>, expected_channel_update: Option<NetworkUpdate>, expected_short_channel_id: Option<u64>)
60         where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
61                                 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
62                                 F3: FnMut(),
63 {
64         macro_rules! expect_event {
65                 ($node: expr, $event_type: path) => {{
66                         let events = $node.node.get_and_clear_pending_events();
67                         assert_eq!(events.len(), 1);
68                         match events[0] {
69                                 $event_type { .. } => {},
70                                 _ => panic!("Unexpected event"),
71                         }
72                 }}
73         }
74
75         macro_rules! expect_htlc_forward {
76                 ($node: expr) => {{
77                         expect_event!($node, Event::PendingHTLCsForwardable);
78                         $node.node.process_pending_htlc_forwards();
79                 }}
80         }
81
82         // 0 ~~> 2 send payment
83         nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(*payment_secret)).unwrap();
84         check_added_monitors!(nodes[0], 1);
85         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
86         // temper update_add (0 => 1)
87         let mut update_add_0 = update_0.update_add_htlcs[0].clone();
88         if test_case == 0 || test_case == 3 || test_case == 100 {
89                 callback_msg(&mut update_add_0);
90                 callback_node();
91         }
92         // 0 => 1 update_add & CS
93         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
94         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
95
96         let update_1_0 = match test_case {
97                 0|100 => { // intermediate node failure; fail backward to 0
98                         let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
99                         assert!(update_1_0.update_fail_htlcs.len()+update_1_0.update_fail_malformed_htlcs.len()==1 && (update_1_0.update_fail_htlcs.len()==1 || update_1_0.update_fail_malformed_htlcs.len()==1));
100                         update_1_0
101                 },
102                 1|2|3|200 => { // final node failure; forwarding to 2
103                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
104                         // forwarding on 1
105                         if test_case != 200 {
106                                 callback_node();
107                         }
108                         expect_htlc_forward!(&nodes[1]);
109
110                         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
111                         check_added_monitors!(&nodes[1], 1);
112                         assert_eq!(update_1.update_add_htlcs.len(), 1);
113                         // tamper update_add (1 => 2)
114                         let mut update_add_1 = update_1.update_add_htlcs[0].clone();
115                         if test_case != 3 && test_case != 200 {
116                                 callback_msg(&mut update_add_1);
117                         }
118
119                         // 1 => 2
120                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
121                         commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
122
123                         if test_case == 2 || test_case == 200 {
124                                 expect_htlc_forward!(&nodes[2]);
125                                 expect_event!(&nodes[2], Event::PaymentReceived);
126                                 callback_node();
127                                 expect_pending_htlcs_forwardable!(nodes[2]);
128                         }
129
130                         let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
131                         if test_case == 2 || test_case == 200 {
132                                 check_added_monitors!(&nodes[2], 1);
133                         }
134                         assert!(update_2_1.update_fail_htlcs.len() == 1);
135
136                         let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
137                         if test_case == 200 {
138                                 callback_fail(&mut fail_msg);
139                         }
140
141                         // 2 => 1
142                         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg);
143                         commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
144
145                         // backward fail on 1
146                         let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
147                         assert!(update_1_0.update_fail_htlcs.len() == 1);
148                         update_1_0
149                 },
150                 _ => unreachable!(),
151         };
152
153         // 1 => 0 commitment_signed_dance
154         if update_1_0.update_fail_htlcs.len() > 0 {
155                 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
156                 if test_case == 100 {
157                         callback_fail(&mut fail_msg);
158                 }
159                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
160         } else {
161                 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]);
162         };
163
164         commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
165
166         let events = nodes[0].node.get_and_clear_pending_events();
167         assert_eq!(events.len(), 1);
168         if let &Event::PaymentPathFailed { ref rejected_by_dest, ref network_update, ref all_paths_failed, ref short_channel_id, ref error_code, .. } = &events[0] {
169                 assert_eq!(*rejected_by_dest, !expected_retryable);
170                 assert_eq!(*all_paths_failed, true);
171                 assert_eq!(*error_code, expected_error_code);
172                 if expected_channel_update.is_some() {
173                         match network_update {
174                                 Some(update) => match update {
175                                         &NetworkUpdate::ChannelUpdateMessage { .. } => {
176                                                 if let NetworkUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
177                                                         panic!("channel_update not found!");
178                                                 }
179                                         },
180                                         &NetworkUpdate::ChannelFailure { ref short_channel_id, ref is_permanent } => {
181                                                 if let NetworkUpdate::ChannelFailure { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
182                                                         assert!(*short_channel_id == *expected_short_channel_id);
183                                                         assert!(*is_permanent == *expected_is_permanent);
184                                                 } else {
185                                                         panic!("Unexpected message event");
186                                                 }
187                                         },
188                                         &NetworkUpdate::NodeFailure { ref node_id, ref is_permanent } => {
189                                                 if let NetworkUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
190                                                         assert!(*node_id == *expected_node_id);
191                                                         assert!(*is_permanent == *expected_is_permanent);
192                                                 } else {
193                                                         panic!("Unexpected message event");
194                                                 }
195                                         },
196                                 }
197                                 None => panic!("Expected channel update"),
198                         }
199                 } else {
200                         assert!(network_update.is_none());
201                 }
202                 if let Some(expected_short_channel_id) = expected_short_channel_id {
203                         match short_channel_id {
204                                 Some(short_channel_id) => assert_eq!(*short_channel_id, expected_short_channel_id),
205                                 None => panic!("Expected short channel id"),
206                         }
207                 } else {
208                         assert!(short_channel_id.is_none());
209                 }
210         } else {
211                 panic!("Unexpected event");
212         }
213 }
214
215 impl msgs::ChannelUpdate {
216         fn dummy(short_channel_id: u64) -> msgs::ChannelUpdate {
217                 use bitcoin::secp256k1::ffi::Signature as FFISignature;
218                 use bitcoin::secp256k1::ecdsa::Signature;
219                 msgs::ChannelUpdate {
220                         signature: Signature::from(unsafe { FFISignature::new() }),
221                         contents: msgs::UnsignedChannelUpdate {
222                                 chain_hash: BlockHash::hash(&vec![0u8][..]),
223                                 short_channel_id,
224                                 timestamp: 0,
225                                 flags: 0,
226                                 cltv_expiry_delta: 0,
227                                 htlc_minimum_msat: 0,
228                                 htlc_maximum_msat: OptionalField::Absent,
229                                 fee_base_msat: 0,
230                                 fee_proportional_millionths: 0,
231                                 excess_data: vec![],
232                         }
233                 }
234         }
235 }
236
237 struct BogusOnionHopData {
238         data: Vec<u8>
239 }
240 impl BogusOnionHopData {
241         fn new(orig: msgs::OnionHopData) -> Self {
242                 Self { data: orig.encode() }
243         }
244 }
245 impl Writeable for BogusOnionHopData {
246         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
247                 writer.write_all(&self.data[..])
248         }
249 }
250
251 const BADONION: u16 = 0x8000;
252 const PERM: u16 = 0x4000;
253 const NODE: u16 = 0x2000;
254 const UPDATE: u16 = 0x1000;
255
256 #[test]
257 fn test_fee_failures() {
258         // Tests that the fee required when forwarding remains consistent over time. This was
259         // previously broken, with forwarding fees floating based on the fee estimator at the time of
260         // forwarding.
261         //
262         // When this test was written, the default base fee floated based on the HTLC count.
263         // It is now fixed, so we simply set the fee to the expected value here.
264         let mut config = test_default_channel_config();
265         config.channel_options.forwarding_fee_base_msat = 196;
266
267         let chanmon_cfgs = create_chanmon_cfgs(3);
268         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
269         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config), Some(config), Some(config)]);
270         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
271         let channels = [create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()), create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known())];
272
273         // positive case
274         let (route, payment_hash_success, payment_preimage_success, payment_secret_success) = get_route_and_payment_hash!(nodes[0], nodes[2], 40_000);
275         nodes[0].node.send_payment(&route, payment_hash_success, &Some(payment_secret_success)).unwrap();
276         check_added_monitors!(nodes[0], 1);
277         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 40_000, payment_hash_success, payment_secret_success);
278         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_success);
279
280         // If the hop gives fee_insufficient but enough fees were provided, then the previous hop
281         // malleated the payment before forwarding, taking funds when they shouldn't have.
282         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
283         let short_channel_id = channels[0].0.contents.short_channel_id;
284         run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
285                 msg.amount_msat -= 1;
286         }, || {}, true, Some(UPDATE|12), Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: true}), Some(short_channel_id));
287
288         // In an earlier version, we spuriously failed to forward payments if the expected feerate
289         // changed between the channel open and the payment.
290         {
291                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
292                 *feerate_lock *= 2;
293         }
294
295         let (payment_preimage_success, payment_hash_success, payment_secret_success) = get_payment_preimage_hash!(nodes[2]);
296         nodes[0].node.send_payment(&route, payment_hash_success, &Some(payment_secret_success)).unwrap();
297         check_added_monitors!(nodes[0], 1);
298         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 40_000, payment_hash_success, payment_secret_success);
299         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_success);
300 }
301
302 #[test]
303 fn test_onion_failure() {
304         // When we check for amount_below_minimum below, we want to test that we're using the *right*
305         // amount, thus we need different htlc_minimum_msat values. We set node[2]'s htlc_minimum_msat
306         // to 2000, which is above the default value of 1000 set in create_node_chanmgrs.
307         // This exposed a previous bug because we were using the wrong value all the way down in
308         // Channel::get_counterparty_htlc_minimum_msat().
309         let mut node_2_cfg: UserConfig = Default::default();
310         node_2_cfg.own_channel_config.our_htlc_minimum_msat = 2000;
311         node_2_cfg.own_channel_config.announced_channel = true;
312         node_2_cfg.peer_channel_config_limits.force_announced_channel_preference = false;
313
314         // When this test was written, the default base fee floated based on the HTLC count.
315         // It is now fixed, so we simply set the fee to the expected value here.
316         let mut config = test_default_channel_config();
317         config.channel_options.forwarding_fee_base_msat = 196;
318
319         let chanmon_cfgs = create_chanmon_cfgs(3);
320         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
321         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config), Some(config), Some(node_2_cfg)]);
322         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
323         let channels = [create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()), create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known())];
324         for node in nodes.iter() {
325                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([3; 32]);
326         }
327         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 40000);
328         // positive case
329         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000);
330
331         // intermediate node failure
332         let short_channel_id = channels[1].0.contents.short_channel_id;
333         run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
334                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
335                 let cur_height = nodes[0].best_block_info().1 + 1;
336                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
337                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height, &None).unwrap();
338                 let mut new_payloads = Vec::new();
339                 for payload in onion_payloads.drain(..) {
340                         new_payloads.push(BogusOnionHopData::new(payload));
341                 }
342                 // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
343                 // describing a length-1 TLV payload, which is obviously bogus.
344                 new_payloads[0].data[0] = 1;
345                 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
346         }, ||{}, true, Some(PERM|22), Some(NetworkUpdate::ChannelFailure{short_channel_id, is_permanent: true}), Some(short_channel_id));
347
348         // final node failure
349         let short_channel_id = channels[1].0.contents.short_channel_id;
350         run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, &payment_secret, |msg| {
351                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
352                 let cur_height = nodes[0].best_block_info().1 + 1;
353                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
354                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height, &None).unwrap();
355                 let mut new_payloads = Vec::new();
356                 for payload in onion_payloads.drain(..) {
357                         new_payloads.push(BogusOnionHopData::new(payload));
358                 }
359                 // break the last-hop payload by swapping the realm (0) byte for a byte describing a
360                 // length-1 TLV payload, which is obviously bogus.
361                 new_payloads[1].data[0] = 1;
362                 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
363         }, ||{}, false, Some(PERM|22), Some(NetworkUpdate::ChannelFailure{short_channel_id, is_permanent: true}), Some(short_channel_id));
364
365         // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
366         // receiving simulated fail messages
367         // intermediate node failure
368         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
369                 // trigger error
370                 msg.amount_msat -= 1;
371         }, |msg| {
372                 // and tamper returning error message
373                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
374                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
375                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), NODE|2, &[0;0]);
376         }, ||{}, true, Some(NODE|2), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: false}), Some(route.paths[0][0].short_channel_id));
377
378         // final node failure
379         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
380                 // and tamper returning error message
381                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
382                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
383                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[1].shared_secret.as_ref(), NODE|2, &[0;0]);
384         }, ||{
385                 nodes[2].node.fail_htlc_backwards(&payment_hash);
386         }, true, Some(NODE|2), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: false}), Some(route.paths[0][1].short_channel_id));
387         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
388
389         // intermediate node failure
390         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
391                 msg.amount_msat -= 1;
392         }, |msg| {
393                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
394                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
395                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), PERM|NODE|2, &[0;0]);
396         }, ||{}, true, Some(PERM|NODE|2), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}), Some(route.paths[0][0].short_channel_id));
397
398         // final node failure
399         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
400                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
401                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
402                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[1].shared_secret.as_ref(), PERM|NODE|2, &[0;0]);
403         }, ||{
404                 nodes[2].node.fail_htlc_backwards(&payment_hash);
405         }, false, Some(PERM|NODE|2), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}), Some(route.paths[0][1].short_channel_id));
406         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
407
408         // intermediate node failure
409         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
410                 msg.amount_msat -= 1;
411         }, |msg| {
412                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
413                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
414                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), PERM|NODE|3, &[0;0]);
415         }, ||{
416                 nodes[2].node.fail_htlc_backwards(&payment_hash);
417         }, true, Some(PERM|NODE|3), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}), Some(route.paths[0][0].short_channel_id));
418
419         // final node failure
420         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
421                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
422                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
423                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[1].shared_secret.as_ref(), PERM|NODE|3, &[0;0]);
424         }, ||{
425                 nodes[2].node.fail_htlc_backwards(&payment_hash);
426         }, false, Some(PERM|NODE|3), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}), Some(route.paths[0][1].short_channel_id));
427         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
428
429         // Our immediate peer sent UpdateFailMalformedHTLC because it couldn't understand the onion in
430         // the UpdateAddHTLC that we sent.
431         let short_channel_id = channels[0].0.contents.short_channel_id;
432         run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
433                 Some(BADONION|PERM|4), None, Some(short_channel_id));
434
435         run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
436                 Some(BADONION|PERM|5), None, Some(short_channel_id));
437
438         run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
439                 Some(BADONION|PERM|6), None, Some(short_channel_id));
440
441         let short_channel_id = channels[1].0.contents.short_channel_id;
442         let chan_update = ChannelUpdate::dummy(short_channel_id);
443
444         let mut err_data = Vec::new();
445         err_data.extend_from_slice(&(chan_update.serialized_length() as u16 + 2).to_be_bytes());
446         err_data.extend_from_slice(&ChannelUpdate::TYPE.to_be_bytes());
447         err_data.extend_from_slice(&chan_update.encode());
448         run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
449                 msg.amount_msat -= 1;
450         }, |msg| {
451                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
452                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
453                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), UPDATE|7, &err_data);
454         }, ||{}, true, Some(UPDATE|7), Some(NetworkUpdate::ChannelUpdateMessage{msg: chan_update.clone()}), Some(short_channel_id));
455
456         // Check we can still handle onion failures that include channel updates without a type prefix
457         let err_data_without_type = chan_update.encode_with_len();
458         run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
459                 msg.amount_msat -= 1;
460         }, |msg| {
461                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
462                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
463                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), UPDATE|7, &err_data_without_type);
464         }, ||{}, true, Some(UPDATE|7), Some(NetworkUpdate::ChannelUpdateMessage{msg: chan_update}), Some(short_channel_id));
465
466         let short_channel_id = channels[1].0.contents.short_channel_id;
467         run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
468                 msg.amount_msat -= 1;
469         }, |msg| {
470                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
471                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
472                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), PERM|8, &[0;0]);
473                 // short_channel_id from the processing node
474         }, ||{}, true, Some(PERM|8), Some(NetworkUpdate::ChannelFailure{short_channel_id, is_permanent: true}), Some(short_channel_id));
475
476         let short_channel_id = channels[1].0.contents.short_channel_id;
477         run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
478                 msg.amount_msat -= 1;
479         }, |msg| {
480                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
481                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
482                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), PERM|9, &[0;0]);
483                 // short_channel_id from the processing node
484         }, ||{}, true, Some(PERM|9), Some(NetworkUpdate::ChannelFailure{short_channel_id, is_permanent: true}), Some(short_channel_id));
485
486         let mut bogus_route = route.clone();
487         bogus_route.paths[0][1].short_channel_id -= 1;
488         let short_channel_id = bogus_route.paths[0][1].short_channel_id;
489         run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, &payment_secret, |_| {}, ||{}, true, Some(PERM|10),
490           Some(NetworkUpdate::ChannelFailure{short_channel_id, is_permanent:true}), Some(short_channel_id));
491
492         let short_channel_id = channels[1].0.contents.short_channel_id;
493         let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_counterparty_htlc_minimum_msat() - 1;
494         let mut bogus_route = route.clone();
495         let route_len = bogus_route.paths[0].len();
496         bogus_route.paths[0][route_len-1].fee_msat = amt_to_forward;
497         run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, &payment_secret, |_| {}, ||{}, true, Some(UPDATE|11), Some(NetworkUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy(short_channel_id)}), Some(short_channel_id));
498
499         // Clear pending payments so that the following positive test has the correct payment hash.
500         for node in nodes.iter() {
501                 node.node.clear_pending_payments();
502         }
503
504         // Test a positive test-case with one extra msat, meeting the minimum.
505         bogus_route.paths[0][route_len-1].fee_msat = amt_to_forward + 1;
506         let preimage = send_along_route(&nodes[0], bogus_route, &[&nodes[1], &nodes[2]], amt_to_forward+1).0;
507         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], preimage);
508
509         //TODO: with new config API, we will be able to generate both valid and
510         //invalid channel_update cases.
511         let short_channel_id = channels[0].0.contents.short_channel_id;
512         run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
513                 msg.amount_msat -= 1;
514         }, || {}, true, Some(UPDATE|12), Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: true}), Some(short_channel_id));
515
516         let short_channel_id = channels[0].0.contents.short_channel_id;
517         run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
518                 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
519                 msg.cltv_expiry -= 1;
520         }, || {}, true, Some(UPDATE|13), Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: true}), Some(short_channel_id));
521
522         let short_channel_id = channels[1].0.contents.short_channel_id;
523         run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
524                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
525                 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
526                 connect_blocks(&nodes[1], height - nodes[1].best_block_info().1);
527                 connect_blocks(&nodes[2], height - nodes[2].best_block_info().1);
528         }, ||{}, true, Some(UPDATE|14), Some(NetworkUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy(short_channel_id)}), Some(short_channel_id));
529
530         run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
531                 nodes[2].node.fail_htlc_backwards(&payment_hash);
532         }, false, Some(PERM|15), None, None);
533         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
534
535         run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, &payment_secret, |msg| {
536                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
537                 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
538                 connect_blocks(&nodes[1], height - nodes[1].best_block_info().1);
539                 connect_blocks(&nodes[2], height - nodes[2].best_block_info().1);
540         }, || {}, true, Some(17), None, None);
541
542         run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
543                 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
544                         for f in pending_forwards.iter_mut() {
545                                 match f {
546                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
547                                                 forward_info.outgoing_cltv_value += 1,
548                                         _ => {},
549                                 }
550                         }
551                 }
552         }, true, Some(18), None, Some(channels[1].0.contents.short_channel_id));
553
554         run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
555                 // violate amt_to_forward > msg.amount_msat
556                 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
557                         for f in pending_forwards.iter_mut() {
558                                 match f {
559                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
560                                                 forward_info.amt_to_forward -= 1,
561                                         _ => {},
562                                 }
563                         }
564                 }
565         }, true, Some(19), None, Some(channels[1].0.contents.short_channel_id));
566
567         let short_channel_id = channels[1].0.contents.short_channel_id;
568         run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
569                 // disconnect event to the channel between nodes[1] ~ nodes[2]
570                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
571                 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
572         }, true, Some(UPDATE|20), Some(NetworkUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy(short_channel_id)}), Some(short_channel_id));
573         reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
574
575         run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
576                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
577                 let mut route = route.clone();
578                 let height = nodes[2].best_block_info().1;
579                 route.paths[0][1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.paths[0][0].cltv_expiry_delta + 1;
580                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
581                 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, height, &None).unwrap();
582                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
583                 msg.cltv_expiry = htlc_cltv;
584                 msg.onion_routing_packet = onion_packet;
585         }, ||{}, true, Some(21), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}), Some(route.paths[0][0].short_channel_id));
586
587         run_onion_failure_test_with_fail_intercept("mpp_timeout", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
588                 // Tamper returning error message
589                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
590                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
591                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[1].shared_secret.as_ref(), 23, &[0;0]);
592         }, ||{
593                 nodes[2].node.fail_htlc_backwards(&payment_hash);
594         }, true, Some(23), None, None);
595 }
596
597 #[test]
598 fn test_default_to_onion_payload_tlv_format() {
599         // Tests that we default to creating tlv format onion payloads when no `NodeAnnouncementInfo`
600         // `features` for a node in the `network_graph` exists, or when the node isn't in the
601         // `network_graph`, and no other known `features` for the node exists.
602         let mut priv_channels_conf = UserConfig::default();
603         priv_channels_conf.own_channel_config.announced_channel = false;
604         let chanmon_cfgs = create_chanmon_cfgs(5);
605         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
606         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, Some(priv_channels_conf)]);
607         let mut nodes = create_network(5, &node_cfgs, &node_chanmgrs);
608
609         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
610         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
611         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
612         create_unannounced_chan_between_nodes_with_value(&nodes, 3, 4, 100000, 10001, InitFeatures::known(), InitFeatures::known());
613
614         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id());
615         let origin_node = &nodes[0];
616         let network_graph = origin_node.network_graph;
617
618         // Clears all the `NodeAnnouncementInfo` for all nodes of `nodes[0]`'s `network_graph`, so that
619         // their `features` aren't used when creating the `route`.
620         network_graph.clear_nodes_announcement_info();
621
622         let (announced_route, _, _, _) = get_route_and_payment_hash!(
623                 origin_node, nodes[3], payment_params, 10_000, TEST_FINAL_CLTV);
624
625         let hops = &announced_route.paths[0];
626         // Assert that the hop between `nodes[1]` and `nodes[2]` defaults to supporting variable length
627         // onions, as `nodes[0]` has no `NodeAnnouncementInfo` `features` for `node[2]`
628         assert!(hops[1].node_features.supports_variable_length_onion());
629         // Assert that the hop between `nodes[2]` and `nodes[3]` defaults to supporting variable length
630         // onions, as `nodes[0]` has no `NodeAnnouncementInfo` `features` for `node[3]`, and no `InvoiceFeatures`
631         // for the `payment_params`, which would otherwise have been used.
632         assert!(hops[2].node_features.supports_variable_length_onion());
633         // Note that we do not assert that `hops[0]` (the channel between `nodes[0]` and `nodes[1]`)
634         // supports variable length onions, as the `InitFeatures` exchanged in the init message
635         // between the nodes will be used when creating the route. We therefore do not default to
636         // supporting variable length onions for that hop, as the `InitFeatures` in this case are
637         // `InitFeatures::known()`.
638
639         let unannounced_chan = &nodes[4].node.list_usable_channels()[0];
640
641         let last_hop = RouteHint(vec![RouteHintHop {
642                 src_node_id: nodes[3].node.get_our_node_id(),
643                 short_channel_id: unannounced_chan.short_channel_id.unwrap(),
644                 fees: RoutingFees {
645                         base_msat: 0,
646                         proportional_millionths: 0,
647                 },
648                 cltv_expiry_delta: 42,
649                 htlc_minimum_msat: None,
650                 htlc_maximum_msat: None,
651         }]);
652
653         let unannounced_chan_params = PaymentParameters::from_node_id(nodes[4].node.get_our_node_id()).with_route_hints(vec![last_hop]);
654         let (unannounced_route, _, _, _) = get_route_and_payment_hash!(
655                 origin_node, nodes[4], unannounced_chan_params, 10_000, TEST_FINAL_CLTV);
656
657         let unannounced_chan_hop = &unannounced_route.paths[0][3];
658         // Ensure that `nodes[4]` doesn't exist in `nodes[0]`'s `network_graph`, as it's not public.
659         assert!(&network_graph.read_only().nodes().get(&NodeId::from_pubkey(&nodes[4].node.get_our_node_id())).is_none());
660         // Assert that the hop between `nodes[3]` and `nodes[4]` defaults to supporting variable length
661         // onions, even though `nodes[4]` as `nodes[0]` doesn't exists in `nodes[0]`'s `network_graph`,
662         // and no `InvoiceFeatures` for the `payment_params` exists, which would otherwise have been
663         // used.
664         assert!(unannounced_chan_hop.node_features.supports_variable_length_onion());
665
666         let cur_height = nodes[0].best_block_info().1 + 1;
667         let (announced_route_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&announced_route.paths[0], 40000, &None, cur_height, &None).unwrap();
668         let (unannounced_route_paylods, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&unannounced_route.paths[0], 40000, &None, cur_height, &None).unwrap();
669
670         for onion_payloads in vec![announced_route_payloads, unannounced_route_paylods] {
671                 for onion_payload in onion_payloads.iter() {
672                         match onion_payload.format {
673                                 msgs::OnionHopDataFormat::Legacy {..} => {
674                                         panic!("Generated a `msgs::OnionHopDataFormat::Legacy` payload, even though that shouldn't have happend.");
675                                 }
676                                 _ => {}
677                         }
678                 }
679         }
680 }
681
682 #[test]
683 fn test_do_not_default_to_onion_payload_tlv_format_when_unsupported() {
684         // Tests that we do not default to creating tlv onions if either of these types features
685         // exists, which specifies no support for variable length onions for a specific hop, when
686         // creating a route:
687         // 1. `InitFeatures` to the counterparty node exchanged with the init message to the node.
688         // 2. `NodeFeatures` in the `NodeAnnouncementInfo` of a node in sender node's `network_graph`.
689         // 3. `InvoiceFeatures` specified by the receiving node, when no `NodeAnnouncementInfo`
690         // `features` exists for the receiver in the sender's `network_graph`.
691         let chanmon_cfgs = create_chanmon_cfgs(4);
692         let mut node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
693
694         // Set `node[1]` config to `InitFeatures::empty()` which return `false` for
695         // `supports_variable_length_onion()`
696         let mut node_1_cfg = &mut node_cfgs[1];
697         node_1_cfg.features = InitFeatures::empty();
698
699         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
700         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
701
702         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
703         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
704         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
705
706         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
707                 .with_features(InvoiceFeatures::empty());
708         let origin_node = &nodes[0];
709         let network_graph = origin_node.network_graph;
710         network_graph.clear_nodes_announcement_info();
711
712         // Set `NodeAnnouncementInfo` `features` which do not support variable length onions for
713         // `nodes[2]` in `nodes[0]`'s `network_graph`.
714         let nodes_2_unsigned_node_announcement = msgs::UnsignedNodeAnnouncement {
715                 features: NodeFeatures::empty(),
716                 timestamp: 0,
717                 node_id: nodes[2].node.get_our_node_id(),
718                 rgb: [32; 3],
719                 alias: [16;32],
720                 addresses: Vec::new(),
721                 excess_address_data: Vec::new(),
722                 excess_data: Vec::new(),
723         };
724         let _res = network_graph.update_node_from_unsigned_announcement(&nodes_2_unsigned_node_announcement);
725
726         let (route, _, _, _) = get_route_and_payment_hash!(
727                 origin_node, nodes[3], payment_params, 10_000, TEST_FINAL_CLTV);
728
729         let hops = &route.paths[0];
730
731         // Assert that the hop between `nodes[0]` and `nodes[1]` doesn't support variable length
732         // onions, as as the `InitFeatures` exchanged (`InitFeatures::empty()`) in the init message
733         // between the nodes when setting up the channel is used when creating the `route` and that we
734         // therefore do not default to supporting variable length onions. Despite `nodes[0]` having no
735         // `NodeAnnouncementInfo` `features` for `node[1]`.
736         assert!(!hops[0].node_features.supports_variable_length_onion());
737         // Assert that the hop between `nodes[1]` and `nodes[2]` uses the `features` from
738         // `nodes_2_unsigned_node_announcement` that doesn't support variable length onions.
739         assert!(!hops[1].node_features.supports_variable_length_onion());
740         // Assert that the hop between `nodes[2]` and `nodes[3]` uses the `InvoiceFeatures` set to the
741         // `payment_params`, that doesn't support variable length onions. We therefore do not end up
742         // defaulting to supporting variable length onions, despite `nodes[0]` having no
743         // `NodeAnnouncementInfo` `features` for `node[3]`.
744         assert!(!hops[2].node_features.supports_variable_length_onion());
745
746         let cur_height = nodes[0].best_block_info().1 + 1;
747         let (onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height, &None).unwrap();
748
749         for onion_payload in onion_payloads.iter() {
750                 match onion_payload.format {
751                         msgs::OnionHopDataFormat::Legacy {..} => {}
752                         _ => {
753                                 panic!("Should have only have generated `msgs::OnionHopDataFormat::Legacy` payloads");
754                         }
755                 }
756         }
757 }
758
759 macro_rules! get_phantom_route {
760         ($nodes: expr, $amt: expr, $channel: expr) => {{
761                 let secp_ctx = Secp256k1::new();
762                 let phantom_secret = $nodes[1].keys_manager.get_node_secret(Recipient::PhantomNode).unwrap();
763                 let phantom_pubkey = PublicKey::from_secret_key(&secp_ctx, &phantom_secret);
764                 let phantom_route_hint = $nodes[1].node.get_phantom_route_hints();
765                 let payment_params = PaymentParameters::from_node_id(phantom_pubkey)
766                         .with_features(InvoiceFeatures::known())
767                         .with_route_hints(vec![RouteHint(vec![
768                                         RouteHintHop {
769                                                 src_node_id: $nodes[0].node.get_our_node_id(),
770                                                 short_channel_id: $channel.0.contents.short_channel_id,
771                                                 fees: RoutingFees {
772                                                         base_msat: $channel.0.contents.fee_base_msat,
773                                                         proportional_millionths: $channel.0.contents.fee_proportional_millionths,
774                                                 },
775                                                 cltv_expiry_delta: $channel.0.contents.cltv_expiry_delta,
776                                                 htlc_minimum_msat: None,
777                                                 htlc_maximum_msat: None,
778                                         },
779                                         RouteHintHop {
780                                                 src_node_id: phantom_route_hint.real_node_pubkey,
781                                                 short_channel_id: phantom_route_hint.phantom_scid,
782                                                 fees: RoutingFees {
783                                                         base_msat: 0,
784                                                         proportional_millionths: 0,
785                                                 },
786                                                 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
787                                                 htlc_minimum_msat: None,
788                                                 htlc_maximum_msat: None,
789                                         }
790                 ])]);
791                 let scorer = test_utils::TestScorer::with_penalty(0);
792                 let network_graph = $nodes[0].network_graph.read_only();
793                 (get_route(
794                         &$nodes[0].node.get_our_node_id(), &payment_params, &network_graph,
795                         Some(&$nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
796                         $amt, TEST_FINAL_CLTV, $nodes[0].logger, &scorer, &[0u8; 32]
797                 ).unwrap(), phantom_route_hint.phantom_scid)
798         }
799 }}
800
801 #[test]
802 fn test_phantom_onion_hmac_failure() {
803         let chanmon_cfgs = create_chanmon_cfgs(2);
804         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
805         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
806         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
807
808         let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
809
810         // Get the route.
811         let recv_value_msat = 10_000;
812         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
813         let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
814
815         // Route the HTLC through to the destination.
816         nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
817         check_added_monitors!(nodes[0], 1);
818         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
819         let mut update_add = update_0.update_add_htlcs[0].clone();
820
821         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
822         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
823
824         // Modify the payload so the phantom hop's HMAC is bogus.
825         let sha256_of_onion = {
826                 let mut channel_state = nodes[1].node.channel_state.lock().unwrap();
827                 let mut pending_forward = channel_state.forward_htlcs.get_mut(&phantom_scid).unwrap();
828                 match pending_forward[0] {
829                         HTLCForwardInfo::AddHTLC {
830                                 forward_info: PendingHTLCInfo {
831                                         routing: PendingHTLCRouting::Forward { ref mut onion_packet, .. },
832                                         ..
833                                 }, ..
834                         } => {
835                                 onion_packet.hmac[onion_packet.hmac.len() - 1] ^= 1;
836                                 Sha256::hash(&onion_packet.hop_data).into_inner().to_vec()
837                         },
838                         _ => panic!("Unexpected forward"),
839                 }
840         };
841         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
842         nodes[1].node.process_pending_htlc_forwards();
843         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
844         nodes[1].node.process_pending_htlc_forwards();
845         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
846         check_added_monitors!(&nodes[1], 1);
847         assert!(update_1.update_fail_htlcs.len() == 1);
848         let fail_msg = update_1.update_fail_htlcs[0].clone();
849         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
850         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
851
852         // Ensure the payment fails with the expected error.
853         let mut fail_conditions = PaymentFailedConditions::new()
854                 .blamed_scid(phantom_scid)
855                 .blamed_chan_closed(true)
856                 .expected_htlc_error_data(0x8000 | 0x4000 | 5, &sha256_of_onion);
857         expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
858 }
859
860 #[test]
861 fn test_phantom_invalid_onion_payload() {
862         let chanmon_cfgs = create_chanmon_cfgs(2);
863         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
864         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
865         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
866
867         let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
868
869         // Get the route.
870         let recv_value_msat = 10_000;
871         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
872         let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
873
874         // We'll use the session priv later when constructing an invalid onion packet.
875         let session_priv = [3; 32];
876         *nodes[0].keys_manager.override_random_bytes.lock().unwrap() = Some(session_priv);
877         nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
878         check_added_monitors!(nodes[0], 1);
879         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
880         let mut update_add = update_0.update_add_htlcs[0].clone();
881
882         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
883         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
884
885         // Modify the onion packet to have an invalid payment amount.
886         for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
887                 for f in pending_forwards.iter_mut() {
888                         match f {
889                                 &mut HTLCForwardInfo::AddHTLC {
890                                         forward_info: PendingHTLCInfo {
891                                                 routing: PendingHTLCRouting::Forward { ref mut onion_packet, .. },
892                                                 ..
893                                         }, ..
894                                 } => {
895                                         // Construct the onion payloads for the entire route and an invalid amount.
896                                         let height = nodes[0].best_block_info().1;
897                                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
898                                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
899                                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], msgs::MAX_VALUE_MSAT + 1, &Some(payment_secret), height + 1, &None).unwrap();
900                                         // We only want to construct the onion packet for the last hop, not the entire route, so
901                                         // remove the first hop's payload and its keys.
902                                         onion_keys.remove(0);
903                                         onion_payloads.remove(0);
904
905                                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
906                                         onion_packet.hop_data = new_onion_packet.hop_data;
907                                         onion_packet.hmac = new_onion_packet.hmac;
908                                 },
909                                 _ => panic!("Unexpected forward"),
910                         }
911                 }
912         }
913         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
914         nodes[1].node.process_pending_htlc_forwards();
915         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
916         nodes[1].node.process_pending_htlc_forwards();
917         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
918         check_added_monitors!(&nodes[1], 1);
919         assert!(update_1.update_fail_htlcs.len() == 1);
920         let fail_msg = update_1.update_fail_htlcs[0].clone();
921         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
922         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
923
924         // Ensure the payment fails with the expected error.
925         let error_data = Vec::new();
926         let mut fail_conditions = PaymentFailedConditions::new()
927                 .blamed_scid(phantom_scid)
928                 .blamed_chan_closed(true)
929                 .expected_htlc_error_data(0x4000 | 22, &error_data);
930         expect_payment_failed_conditions(&nodes[0], payment_hash, true, fail_conditions);
931 }
932
933 #[test]
934 fn test_phantom_final_incorrect_cltv_expiry() {
935         let chanmon_cfgs = create_chanmon_cfgs(2);
936         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
937         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
938         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
939
940         let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
941
942         // Get the route.
943         let recv_value_msat = 10_000;
944         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
945         let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
946
947         // Route the HTLC through to the destination.
948         nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
949         check_added_monitors!(nodes[0], 1);
950         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
951         let mut update_add = update_0.update_add_htlcs[0].clone();
952
953         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
954         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
955
956         // Modify the payload so the phantom hop's HMAC is bogus.
957         for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
958                 for f in pending_forwards.iter_mut() {
959                         match f {
960                                 &mut HTLCForwardInfo::AddHTLC {
961                                         forward_info: PendingHTLCInfo { ref mut outgoing_cltv_value, .. }, ..
962                                 } => {
963                                         *outgoing_cltv_value += 1;
964                                 },
965                                 _ => panic!("Unexpected forward"),
966                         }
967                 }
968         }
969         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
970         nodes[1].node.process_pending_htlc_forwards();
971         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
972         nodes[1].node.process_pending_htlc_forwards();
973         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
974         check_added_monitors!(&nodes[1], 1);
975         assert!(update_1.update_fail_htlcs.len() == 1);
976         let fail_msg = update_1.update_fail_htlcs[0].clone();
977         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
978         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
979
980         // Ensure the payment fails with the expected error.
981         let expected_cltv = 82;
982         let error_data = byte_utils::be32_to_array(expected_cltv).to_vec();
983         let mut fail_conditions = PaymentFailedConditions::new()
984                 .blamed_scid(phantom_scid)
985                 .expected_htlc_error_data(18, &error_data);
986         expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
987 }
988
989 #[test]
990 fn test_phantom_failure_too_low_cltv() {
991         let chanmon_cfgs = create_chanmon_cfgs(2);
992         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
993         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
994         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
995
996         let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
997
998         // Get the route.
999         let recv_value_msat = 10_000;
1000         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
1001         let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
1002
1003         // Modify the route to have a too-low cltv.
1004         route.paths[0][1].cltv_expiry_delta = 5;
1005
1006         // Route the HTLC through to the destination.
1007         nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
1008         check_added_monitors!(nodes[0], 1);
1009         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1010         let mut update_add = update_0.update_add_htlcs[0].clone();
1011
1012         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1013         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1014
1015         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1016         nodes[1].node.process_pending_htlc_forwards();
1017         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1018         nodes[1].node.process_pending_htlc_forwards();
1019         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1020         check_added_monitors!(&nodes[1], 1);
1021         assert!(update_1.update_fail_htlcs.len() == 1);
1022         let fail_msg = update_1.update_fail_htlcs[0].clone();
1023         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1024         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1025
1026         // Ensure the payment fails with the expected error.
1027         let error_data = Vec::new();
1028         let mut fail_conditions = PaymentFailedConditions::new()
1029                 .blamed_scid(phantom_scid)
1030                 .expected_htlc_error_data(17, &error_data);
1031         expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1032 }
1033
1034 #[test]
1035 fn test_phantom_failure_too_low_recv_amt() {
1036         let chanmon_cfgs = create_chanmon_cfgs(2);
1037         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1038         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1039         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1040
1041         let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1042
1043         // Get the route with a too-low amount.
1044         let recv_amt_msat = 10_000;
1045         let bad_recv_amt_msat = recv_amt_msat - 10;
1046         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_amt_msat));
1047         let (mut route, phantom_scid) = get_phantom_route!(nodes, bad_recv_amt_msat, channel);
1048
1049         // Route the HTLC through to the destination.
1050         nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
1051         check_added_monitors!(nodes[0], 1);
1052         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1053         let mut update_add = update_0.update_add_htlcs[0].clone();
1054
1055         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1056         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1057
1058         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1059         nodes[1].node.process_pending_htlc_forwards();
1060         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1061         nodes[1].node.process_pending_htlc_forwards();
1062         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1063         nodes[1].node.process_pending_htlc_forwards();
1064         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1065         check_added_monitors!(&nodes[1], 1);
1066         assert!(update_1.update_fail_htlcs.len() == 1);
1067         let fail_msg = update_1.update_fail_htlcs[0].clone();
1068         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1069         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1070
1071         // Ensure the payment fails with the expected error.
1072         let mut error_data = byte_utils::be64_to_array(bad_recv_amt_msat).to_vec();
1073         error_data.extend_from_slice(
1074                 &byte_utils::be32_to_array(nodes[1].node.best_block.read().unwrap().height()),
1075         );
1076         let mut fail_conditions = PaymentFailedConditions::new()
1077                 .blamed_scid(phantom_scid)
1078                 .expected_htlc_error_data(0x4000 | 15, &error_data);
1079         expect_payment_failed_conditions(&nodes[0], payment_hash, true, fail_conditions);
1080 }
1081
1082 #[test]
1083 fn test_phantom_dust_exposure_failure() {
1084         // Set the max dust exposure to the dust limit.
1085         let max_dust_exposure = 546;
1086         let mut receiver_config = UserConfig::default();
1087         receiver_config.channel_options.max_dust_htlc_exposure_msat = max_dust_exposure;
1088         receiver_config.own_channel_config.announced_channel = true;
1089
1090         let chanmon_cfgs = create_chanmon_cfgs(2);
1091         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1092         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(receiver_config)]);
1093         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1094
1095         let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1096
1097         // Get the route with an amount exceeding the dust exposure threshold of nodes[1].
1098         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(max_dust_exposure + 1));
1099         let (mut route, _) = get_phantom_route!(nodes, max_dust_exposure + 1, channel);
1100
1101         // Route the HTLC through to the destination.
1102         nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
1103         check_added_monitors!(nodes[0], 1);
1104         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1105         let mut update_add = update_0.update_add_htlcs[0].clone();
1106
1107         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1108         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1109
1110         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1111         assert!(update_1.update_fail_htlcs.len() == 1);
1112         let fail_msg = update_1.update_fail_htlcs[0].clone();
1113         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1114         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1115
1116         // Ensure the payment fails with the expected error.
1117         let mut err_data = Vec::new();
1118         err_data.extend_from_slice(&(channel.1.serialized_length() as u16 + 2).to_be_bytes());
1119         err_data.extend_from_slice(&ChannelUpdate::TYPE.to_be_bytes());
1120         err_data.extend_from_slice(&channel.1.encode());
1121
1122         let mut fail_conditions = PaymentFailedConditions::new()
1123                 .blamed_scid(channel.0.contents.short_channel_id)
1124                 .blamed_chan_closed(false)
1125                 .expected_htlc_error_data(0x1000 | 7, &err_data);
1126                 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1127 }
1128
1129 #[test]
1130 fn test_phantom_failure_reject_payment() {
1131         // Test that the user can successfully fail back a phantom node payment.
1132         let chanmon_cfgs = create_chanmon_cfgs(2);
1133         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1134         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1135         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1136
1137         let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1138
1139         // Get the route with a too-low amount.
1140         let recv_amt_msat = 10_000;
1141         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_amt_msat));
1142         let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_amt_msat, channel);
1143
1144         // Route the HTLC through to the destination.
1145         nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
1146         check_added_monitors!(nodes[0], 1);
1147         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1148         let mut update_add = update_0.update_add_htlcs[0].clone();
1149
1150         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1151         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1152
1153         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1154         nodes[1].node.process_pending_htlc_forwards();
1155         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1156         nodes[1].node.process_pending_htlc_forwards();
1157         expect_payment_received!(nodes[1], payment_hash, payment_secret, recv_amt_msat);
1158         nodes[1].node.fail_htlc_backwards(&payment_hash);
1159         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1160         nodes[1].node.process_pending_htlc_forwards();
1161
1162         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1163         check_added_monitors!(&nodes[1], 1);
1164         assert!(update_1.update_fail_htlcs.len() == 1);
1165         let fail_msg = update_1.update_fail_htlcs[0].clone();
1166         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1167         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1168
1169         // Ensure the payment fails with the expected error.
1170         let mut error_data = byte_utils::be64_to_array(recv_amt_msat).to_vec();
1171         error_data.extend_from_slice(
1172                 &byte_utils::be32_to_array(nodes[1].node.best_block.read().unwrap().height()),
1173         );
1174         let mut fail_conditions = PaymentFailedConditions::new()
1175                 .blamed_scid(phantom_scid)
1176                 .expected_htlc_error_data(0x4000 | 15, &error_data);
1177         expect_payment_failed_conditions(&nodes[0], payment_hash, true, fail_conditions);
1178 }