Merge pull request #2967 from tnull/2024-03-refactor-drop-handle-message
[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 crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
15 use crate::sign::{EntropySource, NodeSigner, Recipient};
16 use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentFailureReason};
17 use crate::ln::{PaymentHash, PaymentSecret};
18 use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
19 use crate::ln::channelmanager::{HTLCForwardInfo, FailureCode, CLTV_FAR_FAR_AWAY, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA, PendingAddHTLCInfo, PendingHTLCInfo, PendingHTLCRouting, PaymentId, RecipientOnionFields};
20 use crate::ln::onion_utils;
21 use crate::routing::gossip::{NetworkUpdate, RoutingFees};
22 use crate::routing::router::{get_route, PaymentParameters, Route, RouteParameters, RouteHint, RouteHintHop};
23 use crate::ln::features::{InitFeatures, Bolt11InvoiceFeatures};
24 use crate::ln::msgs;
25 use crate::ln::msgs::{ChannelMessageHandler, ChannelUpdate, OutboundTrampolinePayload};
26 use crate::ln::wire::Encode;
27 use crate::util::ser::{Writeable, Writer, BigSize};
28 use crate::util::test_utils;
29 use crate::util::config::{UserConfig, ChannelConfig, MaxDustHTLCExposure};
30 use crate::util::errors::APIError;
31
32 use bitcoin::blockdata::constants::ChainHash;
33 use bitcoin::hashes::{Hash, HashEngine};
34 use bitcoin::hashes::hmac::{Hmac, HmacEngine};
35 use bitcoin::hashes::sha256::Hash as Sha256;
36
37 use bitcoin::secp256k1;
38 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
39
40 use crate::io;
41 use crate::prelude::*;
42 use core::default::Default;
43 use bitcoin::hashes::hex::FromHex;
44
45 use crate::ln::functional_test_utils::*;
46
47 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>)
48         where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
49                                 F2: FnMut(),
50 {
51         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);
52 }
53
54 // test_case
55 // 0: node1 fails backward
56 // 1: final node fails backward
57 // 2: payment completed but the user rejects the payment
58 // 3: final node fails backward (but tamper onion payloads from node0)
59 // 100: trigger error in the intermediate node and tamper returning fail_htlc
60 // 200: trigger error in the final node and tamper returning fail_htlc
61 fn run_onion_failure_test_with_fail_intercept<F1,F2,F3>(
62         _name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash,
63         payment_secret: &PaymentSecret, mut callback_msg: F1, mut callback_fail: F2,
64         mut callback_node: F3, expected_retryable: bool, expected_error_code: Option<u16>,
65         expected_channel_update: Option<NetworkUpdate>, expected_short_channel_id: Option<u64>
66 )
67         where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
68                                 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
69                                 F3: FnMut(),
70 {
71         macro_rules! expect_event {
72                 ($node: expr, $event_type: path) => {{
73                         let events = $node.node.get_and_clear_pending_events();
74                         assert_eq!(events.len(), 1);
75                         match events[0] {
76                                 $event_type { .. } => {},
77                                 _ => panic!("Unexpected event"),
78                         }
79                 }}
80         }
81
82         macro_rules! expect_htlc_forward {
83                 ($node: expr) => {{
84                         expect_event!($node, Event::PendingHTLCsForwardable);
85                         $node.node.process_pending_htlc_forwards();
86                 }}
87         }
88
89         // 0 ~~> 2 send payment
90         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
91         nodes[0].node.send_payment_with_route(&route, *payment_hash,
92                 RecipientOnionFields::secret_only(*payment_secret), payment_id).unwrap();
93         check_added_monitors!(nodes[0], 1);
94         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
95         // temper update_add (0 => 1)
96         let mut update_add_0 = update_0.update_add_htlcs[0].clone();
97         if test_case == 0 || test_case == 3 || test_case == 100 {
98                 callback_msg(&mut update_add_0);
99                 callback_node();
100         }
101         // 0 => 1 update_add & CS
102         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
103         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
104
105         let update_1_0 = match test_case {
106                 0|100 => { // intermediate node failure; fail backward to 0
107                         let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
108                         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));
109                         update_1_0
110                 },
111                 1|2|3|200 => { // final node failure; forwarding to 2
112                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
113                         // forwarding on 1
114                         if test_case != 200 {
115                                 callback_node();
116                         }
117                         expect_htlc_forward!(&nodes[1]);
118
119                         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
120                         check_added_monitors!(&nodes[1], 1);
121                         assert_eq!(update_1.update_add_htlcs.len(), 1);
122                         // tamper update_add (1 => 2)
123                         let mut update_add_1 = update_1.update_add_htlcs[0].clone();
124                         if test_case != 3 && test_case != 200 {
125                                 callback_msg(&mut update_add_1);
126                         }
127
128                         // 1 => 2
129                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
130                         commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
131
132                         if test_case == 2 || test_case == 200 {
133                                 expect_htlc_forward!(&nodes[2]);
134                                 expect_event!(&nodes[2], Event::PaymentClaimable);
135                                 callback_node();
136                                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
137                         }
138
139                         let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
140                         if test_case == 2 || test_case == 200 {
141                                 check_added_monitors!(&nodes[2], 1);
142                         }
143                         assert!(update_2_1.update_fail_htlcs.len() == 1);
144
145                         let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
146                         if test_case == 200 {
147                                 callback_fail(&mut fail_msg);
148                         }
149
150                         // 2 => 1
151                         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg);
152                         commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
153
154                         // backward fail on 1
155                         let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
156                         assert!(update_1_0.update_fail_htlcs.len() == 1);
157                         update_1_0
158                 },
159                 _ => unreachable!(),
160         };
161
162         // 1 => 0 commitment_signed_dance
163         if update_1_0.update_fail_htlcs.len() > 0 {
164                 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
165                 if test_case == 100 {
166                         callback_fail(&mut fail_msg);
167                 }
168                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
169         } else {
170                 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]);
171         };
172
173         commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
174
175         let events = nodes[0].node.get_and_clear_pending_events();
176         assert_eq!(events.len(), 2);
177         if let &Event::PaymentPathFailed { ref payment_failed_permanently, ref short_channel_id, ref error_code, failure: PathFailure::OnPath { ref network_update }, .. } = &events[0] {
178                 assert_eq!(*payment_failed_permanently, !expected_retryable);
179                 assert_eq!(*error_code, expected_error_code);
180                 if expected_channel_update.is_some() {
181                         match network_update {
182                                 Some(update) => match update {
183                                         &NetworkUpdate::ChannelUpdateMessage { .. } => {
184                                                 if let NetworkUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
185                                                         panic!("channel_update not found!");
186                                                 }
187                                         },
188                                         &NetworkUpdate::ChannelFailure { ref short_channel_id, ref is_permanent } => {
189                                                 if let NetworkUpdate::ChannelFailure { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
190                                                         assert!(*short_channel_id == *expected_short_channel_id);
191                                                         assert!(*is_permanent == *expected_is_permanent);
192                                                 } else {
193                                                         panic!("Unexpected message event");
194                                                 }
195                                         },
196                                         &NetworkUpdate::NodeFailure { ref node_id, ref is_permanent } => {
197                                                 if let NetworkUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
198                                                         assert!(*node_id == *expected_node_id);
199                                                         assert!(*is_permanent == *expected_is_permanent);
200                                                 } else {
201                                                         panic!("Unexpected message event");
202                                                 }
203                                         },
204                                 }
205                                 None => panic!("Expected channel update"),
206                         }
207                 } else {
208                         assert!(network_update.is_none());
209                 }
210                 if let Some(expected_short_channel_id) = expected_short_channel_id {
211                         match short_channel_id {
212                                 Some(short_channel_id) => assert_eq!(*short_channel_id, expected_short_channel_id),
213                                 None => panic!("Expected short channel id"),
214                         }
215                 } else {
216                         assert!(short_channel_id.is_none());
217                 }
218         } else {
219                 panic!("Unexpected event");
220         }
221         match events[1] {
222                 Event::PaymentFailed { payment_hash: ev_payment_hash, payment_id: ev_payment_id, reason: ref ev_reason } => {
223                         assert_eq!(*payment_hash, ev_payment_hash);
224                         assert_eq!(payment_id, ev_payment_id);
225                         assert_eq!(if expected_retryable {
226                                 PaymentFailureReason::RetriesExhausted
227                         } else {
228                                 PaymentFailureReason::RecipientRejected
229                         }, ev_reason.unwrap());
230                 }
231                 _ => panic!("Unexpected second event"),
232         }
233 }
234
235 impl msgs::ChannelUpdate {
236         fn dummy(short_channel_id: u64) -> msgs::ChannelUpdate {
237                 use bitcoin::hash_types::BlockHash;
238                 use bitcoin::secp256k1::ffi::Signature as FFISignature;
239                 use bitcoin::secp256k1::ecdsa::Signature;
240                 msgs::ChannelUpdate {
241                         signature: Signature::from(unsafe { FFISignature::new() }),
242                         contents: msgs::UnsignedChannelUpdate {
243                                 chain_hash: ChainHash::from(BlockHash::hash(&vec![0u8][..]).as_ref()),
244                                 short_channel_id,
245                                 timestamp: 0,
246                                 flags: 0,
247                                 cltv_expiry_delta: 0,
248                                 htlc_minimum_msat: 0,
249                                 htlc_maximum_msat: msgs::MAX_VALUE_MSAT,
250                                 fee_base_msat: 0,
251                                 fee_proportional_millionths: 0,
252                                 excess_data: vec![],
253                         }
254                 }
255         }
256 }
257
258 struct BogusOnionHopData {
259         data: Vec<u8>
260 }
261 impl BogusOnionHopData {
262         fn new(orig: msgs::OutboundOnionPayload) -> Self {
263                 Self { data: orig.encode() }
264         }
265 }
266 impl Writeable for BogusOnionHopData {
267         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
268                 writer.write_all(&self.data[..])
269         }
270 }
271
272 const BADONION: u16 = 0x8000;
273 const PERM: u16 = 0x4000;
274 const NODE: u16 = 0x2000;
275 const UPDATE: u16 = 0x1000;
276
277 #[test]
278 fn test_fee_failures() {
279         // Tests that the fee required when forwarding remains consistent over time. This was
280         // previously broken, with forwarding fees floating based on the fee estimator at the time of
281         // forwarding.
282         //
283         // When this test was written, the default base fee floated based on the HTLC count.
284         // It is now fixed, so we simply set the fee to the expected value here.
285         let mut config = test_default_channel_config();
286         config.channel_config.forwarding_fee_base_msat = 196;
287
288         let chanmon_cfgs = create_chanmon_cfgs(3);
289         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
290         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config), Some(config), Some(config)]);
291         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
292         let channels = [create_announced_chan_between_nodes(&nodes, 0, 1), create_announced_chan_between_nodes(&nodes, 1, 2)];
293
294         // positive case
295         let (route, payment_hash_success, payment_preimage_success, payment_secret_success) = get_route_and_payment_hash!(nodes[0], nodes[2], 40_000);
296         nodes[0].node.send_payment_with_route(&route, payment_hash_success,
297                 RecipientOnionFields::secret_only(payment_secret_success), PaymentId(payment_hash_success.0)).unwrap();
298         check_added_monitors!(nodes[0], 1);
299         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 40_000, payment_hash_success, payment_secret_success);
300         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_success);
301
302         // If the hop gives fee_insufficient but enough fees were provided, then the previous hop
303         // malleated the payment before forwarding, taking funds when they shouldn't have.
304         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
305         let short_channel_id = channels[0].0.contents.short_channel_id;
306         run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
307                 msg.amount_msat -= 1;
308         }, || {}, true, Some(UPDATE|12), Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: true}), Some(short_channel_id));
309
310         // In an earlier version, we spuriously failed to forward payments if the expected feerate
311         // changed between the channel open and the payment.
312         {
313                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
314                 *feerate_lock *= 2;
315         }
316
317         let (payment_preimage_success, payment_hash_success, payment_secret_success) = get_payment_preimage_hash!(nodes[2]);
318         nodes[0].node.send_payment_with_route(&route, payment_hash_success,
319                 RecipientOnionFields::secret_only(payment_secret_success), PaymentId(payment_hash_success.0)).unwrap();
320         check_added_monitors!(nodes[0], 1);
321         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 40_000, payment_hash_success, payment_secret_success);
322         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_success);
323 }
324
325 #[test]
326 fn test_onion_failure() {
327         // When we check for amount_below_minimum below, we want to test that we're using the *right*
328         // amount, thus we need different htlc_minimum_msat values. We set node[2]'s htlc_minimum_msat
329         // to 2000, which is above the default value of 1000 set in create_node_chanmgrs.
330         // This exposed a previous bug because we were using the wrong value all the way down in
331         // Channel::get_counterparty_htlc_minimum_msat().
332         let mut node_2_cfg: UserConfig = Default::default();
333         node_2_cfg.channel_handshake_config.our_htlc_minimum_msat = 2000;
334         node_2_cfg.channel_handshake_config.announced_channel = true;
335         node_2_cfg.channel_handshake_limits.force_announced_channel_preference = false;
336
337         // When this test was written, the default base fee floated based on the HTLC count.
338         // It is now fixed, so we simply set the fee to the expected value here.
339         let mut config = test_default_channel_config();
340         config.channel_config.forwarding_fee_base_msat = 196;
341
342         let chanmon_cfgs = create_chanmon_cfgs(3);
343         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
344         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config), Some(config), Some(node_2_cfg)]);
345         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
346         let channels = [create_announced_chan_between_nodes(&nodes, 0, 1), create_announced_chan_between_nodes(&nodes, 1, 2)];
347         for node in nodes.iter() {
348                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([3; 32]);
349         }
350         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 40000);
351         // positive case
352         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000);
353
354         // intermediate node failure
355         let short_channel_id = channels[1].0.contents.short_channel_id;
356         run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
357                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
358                 let cur_height = nodes[0].best_block_info().1 + 1;
359                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
360                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(
361                         &route.paths[0], 40000, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
362                 let mut new_payloads = Vec::new();
363                 for payload in onion_payloads.drain(..) {
364                         new_payloads.push(BogusOnionHopData::new(payload));
365                 }
366                 // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
367                 // describing a length-1 TLV payload, which is obviously bogus.
368                 new_payloads[0].data[0] = 1;
369                 msg.onion_routing_packet = onion_utils::construct_onion_packet_with_writable_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
370         }, ||{}, true, Some(PERM|22), Some(NetworkUpdate::ChannelFailure{short_channel_id, is_permanent: true}), Some(short_channel_id));
371
372         // final node failure
373         let short_channel_id = channels[1].0.contents.short_channel_id;
374         run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, &payment_secret, |msg| {
375                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
376                 let cur_height = nodes[0].best_block_info().1 + 1;
377                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
378                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(
379                         &route.paths[0], 40000, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
380                 let mut new_payloads = Vec::new();
381                 for payload in onion_payloads.drain(..) {
382                         new_payloads.push(BogusOnionHopData::new(payload));
383                 }
384                 // break the last-hop payload by swapping the realm (0) byte for a byte describing a
385                 // length-1 TLV payload, which is obviously bogus.
386                 new_payloads[1].data[0] = 1;
387                 msg.onion_routing_packet = onion_utils::construct_onion_packet_with_writable_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
388         }, ||{}, false, Some(PERM|22), Some(NetworkUpdate::ChannelFailure{short_channel_id, is_permanent: true}), Some(short_channel_id));
389
390         // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
391         // receiving simulated fail messages
392         // intermediate node failure
393         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
394                 // trigger error
395                 msg.amount_msat -= 1;
396         }, |msg| {
397                 // and tamper returning error message
398                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
399                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
400                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), NODE|2, &[0;0]);
401         }, ||{}, true, Some(NODE|2), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0].hops[0].pubkey, is_permanent: false}), Some(route.paths[0].hops[0].short_channel_id));
402
403         // final node failure
404         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
405                 // and tamper returning error message
406                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
407                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
408                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[1].shared_secret.as_ref(), NODE|2, &[0;0]);
409         }, ||{
410                 nodes[2].node.fail_htlc_backwards(&payment_hash);
411         }, true, Some(NODE|2), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0].hops[1].pubkey, is_permanent: false}), Some(route.paths[0].hops[1].short_channel_id));
412         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
413
414         // intermediate node failure
415         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
416                 msg.amount_msat -= 1;
417         }, |msg| {
418                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
419                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
420                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), PERM|NODE|2, &[0;0]);
421         }, ||{}, true, Some(PERM|NODE|2), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0].hops[0].pubkey, is_permanent: true}), Some(route.paths[0].hops[0].short_channel_id));
422
423         // final node failure
424         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
425                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
426                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
427                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[1].shared_secret.as_ref(), PERM|NODE|2, &[0;0]);
428         }, ||{
429                 nodes[2].node.fail_htlc_backwards(&payment_hash);
430         }, false, Some(PERM|NODE|2), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0].hops[1].pubkey, is_permanent: true}), Some(route.paths[0].hops[1].short_channel_id));
431         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
432
433         // intermediate node failure
434         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
435                 msg.amount_msat -= 1;
436         }, |msg| {
437                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
438                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
439                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), PERM|NODE|3, &[0;0]);
440         }, ||{
441                 nodes[2].node.fail_htlc_backwards(&payment_hash);
442         }, true, Some(PERM|NODE|3), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0].hops[0].pubkey, is_permanent: true}), Some(route.paths[0].hops[0].short_channel_id));
443
444         // final node failure
445         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
446                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
447                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
448                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[1].shared_secret.as_ref(), PERM|NODE|3, &[0;0]);
449         }, ||{
450                 nodes[2].node.fail_htlc_backwards(&payment_hash);
451         }, false, Some(PERM|NODE|3), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0].hops[1].pubkey, is_permanent: true}), Some(route.paths[0].hops[1].short_channel_id));
452         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
453
454         // Our immediate peer sent UpdateFailMalformedHTLC because it couldn't understand the onion in
455         // the UpdateAddHTLC that we sent.
456         let short_channel_id = channels[0].0.contents.short_channel_id;
457         run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
458                 Some(BADONION|PERM|4), None, Some(short_channel_id));
459
460         run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
461                 Some(BADONION|PERM|5), None, Some(short_channel_id));
462
463         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,
464                 Some(BADONION|PERM|6), None, Some(short_channel_id));
465
466         let short_channel_id = channels[1].0.contents.short_channel_id;
467         let chan_update = ChannelUpdate::dummy(short_channel_id);
468
469         let mut err_data = Vec::new();
470         err_data.extend_from_slice(&(chan_update.serialized_length() as u16 + 2).to_be_bytes());
471         err_data.extend_from_slice(&ChannelUpdate::TYPE.to_be_bytes());
472         err_data.extend_from_slice(&chan_update.encode());
473         run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
474                 msg.amount_msat -= 1;
475         }, |msg| {
476                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
477                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
478                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), UPDATE|7, &err_data);
479         }, ||{}, true, Some(UPDATE|7), Some(NetworkUpdate::ChannelUpdateMessage{msg: chan_update.clone()}), Some(short_channel_id));
480
481         // Check we can still handle onion failures that include channel updates without a type prefix
482         let err_data_without_type = chan_update.encode_with_len();
483         run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
484                 msg.amount_msat -= 1;
485         }, |msg| {
486                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
487                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
488                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), UPDATE|7, &err_data_without_type);
489         }, ||{}, true, Some(UPDATE|7), Some(NetworkUpdate::ChannelUpdateMessage{msg: chan_update}), Some(short_channel_id));
490
491         let short_channel_id = channels[1].0.contents.short_channel_id;
492         run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
493                 msg.amount_msat -= 1;
494         }, |msg| {
495                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
496                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
497                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), PERM|8, &[0;0]);
498                 // short_channel_id from the processing node
499         }, ||{}, true, Some(PERM|8), Some(NetworkUpdate::ChannelFailure{short_channel_id, is_permanent: true}), Some(short_channel_id));
500
501         let short_channel_id = channels[1].0.contents.short_channel_id;
502         run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
503                 msg.amount_msat -= 1;
504         }, |msg| {
505                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
506                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
507                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), PERM|9, &[0;0]);
508                 // short_channel_id from the processing node
509         }, ||{}, true, Some(PERM|9), Some(NetworkUpdate::ChannelFailure{short_channel_id, is_permanent: true}), Some(short_channel_id));
510
511         let mut bogus_route = route.clone();
512         bogus_route.paths[0].hops[1].short_channel_id -= 1;
513         let short_channel_id = bogus_route.paths[0].hops[1].short_channel_id;
514         run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, &payment_secret, |_| {}, ||{}, true, Some(PERM|10),
515           Some(NetworkUpdate::ChannelFailure{short_channel_id, is_permanent:true}), Some(short_channel_id));
516
517         let short_channel_id = channels[1].0.contents.short_channel_id;
518         let amt_to_forward = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
519                 .unwrap().lock().unwrap().channel_by_id.get(&channels[1].2).unwrap()
520                 .context().get_counterparty_htlc_minimum_msat() - 1;
521         let mut bogus_route = route.clone();
522         let route_len = bogus_route.paths[0].hops.len();
523         bogus_route.paths[0].hops[route_len-1].fee_msat = amt_to_forward;
524         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));
525
526         // Clear pending payments so that the following positive test has the correct payment hash.
527         for node in nodes.iter() {
528                 node.node.clear_pending_payments();
529         }
530
531         // Test a positive test-case with one extra msat, meeting the minimum.
532         bogus_route.paths[0].hops[route_len-1].fee_msat = amt_to_forward + 1;
533         let preimage = send_along_route(&nodes[0], bogus_route, &[&nodes[1], &nodes[2]], amt_to_forward+1).0;
534         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], preimage);
535
536         let short_channel_id = channels[0].0.contents.short_channel_id;
537         run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
538                 msg.amount_msat -= 1;
539         }, || {}, true, Some(UPDATE|12), Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: true}), Some(short_channel_id));
540
541         let short_channel_id = channels[0].0.contents.short_channel_id;
542         run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
543                 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
544                 msg.cltv_expiry -= 1;
545         }, || {}, true, Some(UPDATE|13), Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: true}), Some(short_channel_id));
546
547         let short_channel_id = channels[1].0.contents.short_channel_id;
548         run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
549                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
550                 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
551                 connect_blocks(&nodes[1], height - nodes[1].best_block_info().1);
552                 connect_blocks(&nodes[2], height - nodes[2].best_block_info().1);
553         }, ||{}, true, Some(UPDATE|14), Some(NetworkUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy(short_channel_id)}), Some(short_channel_id));
554
555         run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
556                 nodes[2].node.fail_htlc_backwards(&payment_hash);
557         }, false, Some(PERM|15), None, None);
558         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
559
560         run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, &payment_secret, |msg| {
561                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
562                 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
563                 connect_blocks(&nodes[1], height - nodes[1].best_block_info().1);
564                 connect_blocks(&nodes[2], height - nodes[2].best_block_info().1);
565         }, || {}, false, Some(0x4000 | 15), None, None);
566
567         run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
568                 for (_, pending_forwards) in nodes[1].node.forward_htlcs.lock().unwrap().iter_mut() {
569                         for f in pending_forwards.iter_mut() {
570                                 match f {
571                                         &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) =>
572                                                 forward_info.outgoing_cltv_value -= 1,
573                                         _ => {},
574                                 }
575                         }
576                 }
577         }, true, Some(18), None, Some(channels[1].0.contents.short_channel_id));
578
579         run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
580                 // violate amt_to_forward > msg.amount_msat
581                 for (_, pending_forwards) in nodes[1].node.forward_htlcs.lock().unwrap().iter_mut() {
582                         for f in pending_forwards.iter_mut() {
583                                 match f {
584                                         &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) =>
585                                                 forward_info.outgoing_amt_msat -= 1,
586                                         _ => {},
587                                 }
588                         }
589                 }
590         }, true, Some(19), None, Some(channels[1].0.contents.short_channel_id));
591
592         let short_channel_id = channels[1].0.contents.short_channel_id;
593         run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
594                 // disconnect event to the channel between nodes[1] ~ nodes[2]
595                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
596                 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
597         }, true, Some(UPDATE|7), Some(NetworkUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy(short_channel_id)}), Some(short_channel_id));
598         run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
599                 // disconnect event to the channel between nodes[1] ~ nodes[2]
600                 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
601                         nodes[1].node.timer_tick_occurred();
602                         nodes[2].node.timer_tick_occurred();
603                 }
604                 nodes[1].node.get_and_clear_pending_msg_events();
605                 nodes[2].node.get_and_clear_pending_msg_events();
606         }, true, Some(UPDATE|20), Some(NetworkUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy(short_channel_id)}), Some(short_channel_id));
607         reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[2]));
608
609         run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
610                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
611                 let mut route = route.clone();
612                 let height = nodes[2].best_block_info().1;
613                 route.paths[0].hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.paths[0].hops[0].cltv_expiry_delta + 1;
614                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
615                 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(
616                         &route.paths[0], 40000, RecipientOnionFields::spontaneous_empty(), height, &None).unwrap();
617                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
618                 msg.cltv_expiry = htlc_cltv;
619                 msg.onion_routing_packet = onion_packet;
620         }, ||{}, true, Some(21), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0].hops[0].pubkey, is_permanent: true}), Some(route.paths[0].hops[0].short_channel_id));
621
622         run_onion_failure_test_with_fail_intercept("mpp_timeout", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
623                 // Tamper returning error message
624                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
625                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
626                 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[1].shared_secret.as_ref(), 23, &[0;0]);
627         }, ||{
628                 nodes[2].node.fail_htlc_backwards(&payment_hash);
629         }, true, Some(23), None, None);
630
631         run_onion_failure_test_with_fail_intercept("bogus err packet with valid hmac", 200, &nodes,
632                 &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
633                         let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
634                         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
635                         let mut decoded_err_packet = msgs::DecodedOnionErrorPacket {
636                                 failuremsg: vec![0],
637                                 pad: vec![0; 255],
638                                 hmac: [0; 32],
639                         };
640                         let um = onion_utils::gen_um_from_shared_secret(&onion_keys[1].shared_secret.as_ref());
641                         let mut hmac = HmacEngine::<Sha256>::new(&um);
642                         hmac.input(&decoded_err_packet.encode()[32..]);
643                         decoded_err_packet.hmac = Hmac::from_engine(hmac).to_byte_array();
644                         msg.reason = onion_utils::encrypt_failure_packet(
645                                 &onion_keys[1].shared_secret.as_ref(), &decoded_err_packet.encode()[..])
646                 }, || nodes[2].node.fail_htlc_backwards(&payment_hash), false, None,
647                 Some(NetworkUpdate::NodeFailure { node_id: route.paths[0].hops[1].pubkey, is_permanent: true }),
648                 Some(channels[1].0.contents.short_channel_id));
649         run_onion_failure_test_with_fail_intercept("0-length channel update in intermediate node UPDATE onion failure",
650                 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
651                         msg.amount_msat -= 1;
652                 }, |msg| {
653                         let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
654                         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
655                         let mut decoded_err_packet = msgs::DecodedOnionErrorPacket {
656                                 failuremsg: vec![
657                                         0x10, 0x7, // UPDATE|7
658                                         0x0, 0x0 // 0-len channel update
659                                 ],
660                                 pad: vec![0; 255 - 4 /* 4-byte error message */],
661                                 hmac: [0; 32],
662                         };
663                         let um = onion_utils::gen_um_from_shared_secret(&onion_keys[0].shared_secret.as_ref());
664                         let mut hmac = HmacEngine::<Sha256>::new(&um);
665                         hmac.input(&decoded_err_packet.encode()[32..]);
666                         decoded_err_packet.hmac = Hmac::from_engine(hmac).to_byte_array();
667                         msg.reason = onion_utils::encrypt_failure_packet(
668                                 &onion_keys[0].shared_secret.as_ref(), &decoded_err_packet.encode()[..])
669                 }, || {}, true, Some(0x1000|7),
670                 Some(NetworkUpdate::ChannelFailure {
671                         short_channel_id: channels[1].0.contents.short_channel_id,
672                         is_permanent: false,
673                 }),
674                 Some(channels[1].0.contents.short_channel_id));
675         run_onion_failure_test_with_fail_intercept("0-length channel update in final node UPDATE onion failure",
676                 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
677                         let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
678                         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
679                         let mut decoded_err_packet = msgs::DecodedOnionErrorPacket {
680                                 failuremsg: vec![
681                                         0x10, 0x7, // UPDATE|7
682                                         0x0, 0x0 // 0-len channel update
683                                 ],
684                                 pad: vec![0; 255 - 4 /* 4-byte error message */],
685                                 hmac: [0; 32],
686                         };
687                         let um = onion_utils::gen_um_from_shared_secret(&onion_keys[1].shared_secret.as_ref());
688                         let mut hmac = HmacEngine::<Sha256>::new(&um);
689                         hmac.input(&decoded_err_packet.encode()[32..]);
690                         decoded_err_packet.hmac = Hmac::from_engine(hmac).to_byte_array();
691                         msg.reason = onion_utils::encrypt_failure_packet(
692                                 &onion_keys[1].shared_secret.as_ref(), &decoded_err_packet.encode()[..])
693                 }, || nodes[2].node.fail_htlc_backwards(&payment_hash), true, Some(0x1000|7),
694                 Some(NetworkUpdate::ChannelFailure {
695                         short_channel_id: channels[1].0.contents.short_channel_id,
696                         is_permanent: false,
697                 }),
698                 Some(channels[1].0.contents.short_channel_id));
699 }
700
701 #[test]
702 fn test_overshoot_final_cltv() {
703         let chanmon_cfgs = create_chanmon_cfgs(3);
704         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
705         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None; 3]);
706         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
707         create_announced_chan_between_nodes(&nodes, 0, 1);
708         create_announced_chan_between_nodes(&nodes, 1, 2);
709         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 40000);
710
711         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
712         nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id).unwrap();
713
714         check_added_monitors!(nodes[0], 1);
715         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
716         let mut update_add_0 = update_0.update_add_htlcs[0].clone();
717         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
718         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
719
720         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
721         for (_, pending_forwards) in nodes[1].node.forward_htlcs.lock().unwrap().iter_mut() {
722                 for f in pending_forwards.iter_mut() {
723                         match f {
724                                 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) =>
725                                         forward_info.outgoing_cltv_value += 1,
726                                 _ => {},
727                         }
728                 }
729         }
730         expect_pending_htlcs_forwardable!(nodes[1]);
731
732         check_added_monitors!(&nodes[1], 1);
733         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
734         let mut update_add_1 = update_1.update_add_htlcs[0].clone();
735         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
736         commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
737
738         expect_pending_htlcs_forwardable!(nodes[2]);
739         expect_payment_claimable!(nodes[2], payment_hash, payment_secret, 40_000);
740         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
741 }
742
743 fn do_test_onion_failure_stale_channel_update(announced_channel: bool) {
744         // Create a network of three nodes and two channels connecting them. We'll be updating the
745         // HTLC relay policy of the second channel, causing forwarding failures at the first hop.
746         let mut config = UserConfig::default();
747         config.channel_handshake_config.announced_channel = announced_channel;
748         config.channel_handshake_limits.force_announced_channel_preference = false;
749         config.accept_forwards_to_priv_channels = !announced_channel;
750         config.channel_config.max_dust_htlc_exposure = MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253);
751         let chanmon_cfgs = create_chanmon_cfgs(3);
752         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
753         let persister;
754         let chain_monitor;
755         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(config), None]);
756         let channel_manager_1_deserialized;
757         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
758
759         let other_channel = create_chan_between_nodes(
760                 &nodes[0], &nodes[1],
761         );
762         let channel_to_update = if announced_channel {
763                 let channel = create_announced_chan_between_nodes(
764                         &nodes, 1, 2,
765                 );
766                 (channel.2, channel.0.contents.short_channel_id)
767         } else {
768                 let channel = create_unannounced_chan_between_nodes_with_value(
769                         &nodes, 1, 2, 100000, 10001,
770                 );
771                 (channel.0.channel_id, channel.0.short_channel_id_alias.unwrap())
772         };
773         let channel_to_update_counterparty = &nodes[2].node.get_our_node_id();
774
775         let default_config = ChannelConfig::default();
776
777         // A test payment should succeed as the ChannelConfig has not been changed yet.
778         const PAYMENT_AMT: u64 = 40000;
779         let (route, payment_hash, payment_preimage, payment_secret) = if announced_channel {
780                 get_route_and_payment_hash!(nodes[0], nodes[2], PAYMENT_AMT)
781         } else {
782                 let hop_hints = vec![RouteHint(vec![RouteHintHop {
783                         src_node_id: nodes[1].node.get_our_node_id(),
784                         short_channel_id: channel_to_update.1,
785                         fees: RoutingFees {
786                                 base_msat: default_config.forwarding_fee_base_msat,
787                                 proportional_millionths: default_config.forwarding_fee_proportional_millionths,
788                         },
789                         cltv_expiry_delta: default_config.cltv_expiry_delta,
790                         htlc_maximum_msat: None,
791                         htlc_minimum_msat: None,
792                 }])];
793                 let payment_params = PaymentParameters::from_node_id(*channel_to_update_counterparty, TEST_FINAL_CLTV)
794                         .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap()
795                         .with_route_hints(hop_hints).unwrap();
796                 get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, PAYMENT_AMT)
797         };
798         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[2]]], PAYMENT_AMT,
799                 payment_hash, payment_secret);
800         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
801
802         // Closure to force expiry of a channel's previous config.
803         let expire_prev_config = || {
804                 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
805                         nodes[1].node.timer_tick_occurred();
806                 }
807         };
808
809         // Closure to update and retrieve the latest ChannelUpdate.
810         let update_and_get_channel_update = |config: &ChannelConfig, expect_new_update: bool,
811                 prev_update: Option<&msgs::ChannelUpdate>, should_expire_prev_config: bool| -> Option<msgs::ChannelUpdate> {
812                 nodes[1].node.update_channel_config(
813                         channel_to_update_counterparty, &[channel_to_update.0], config,
814                 ).unwrap();
815                 let events = nodes[1].node.get_and_clear_pending_msg_events();
816                 assert_eq!(events.len(), expect_new_update as usize);
817                 if !expect_new_update {
818                         return None;
819                 }
820                 let new_update = match &events[0] {
821                         MessageSendEvent::BroadcastChannelUpdate { msg } => {
822                                 assert!(announced_channel);
823                                 msg.clone()
824                         },
825                         MessageSendEvent::SendChannelUpdate { node_id, msg } => {
826                                 assert_eq!(node_id, channel_to_update_counterparty);
827                                 assert!(!announced_channel);
828                                 msg.clone()
829                         },
830                         _ => panic!("expected Broadcast/SendChannelUpdate event"),
831                 };
832                 if prev_update.is_some() {
833                         assert!(new_update.contents.timestamp > prev_update.unwrap().contents.timestamp)
834                 }
835                 if should_expire_prev_config {
836                         expire_prev_config();
837                 }
838                 Some(new_update)
839         };
840
841         // We'll be attempting to route payments using the default ChannelUpdate for channels. This will
842         // lead to onion failures at the first hop once we update the ChannelConfig for the
843         // second hop.
844         let expect_onion_failure = |name: &str, error_code: u16, channel_update: &msgs::ChannelUpdate| {
845                 let short_channel_id = channel_to_update.1;
846                 let network_update = NetworkUpdate::ChannelUpdateMessage { msg: channel_update.clone() };
847                 run_onion_failure_test(
848                         name, 0, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {}, true,
849                         Some(error_code), Some(network_update), Some(short_channel_id),
850                 );
851         };
852
853         // Updates to cltv_expiry_delta below MIN_CLTV_EXPIRY_DELTA should fail with APIMisuseError.
854         let mut invalid_config = default_config.clone();
855         invalid_config.cltv_expiry_delta = 0;
856         match nodes[1].node.update_channel_config(
857                 channel_to_update_counterparty, &[channel_to_update.0], &invalid_config,
858         ) {
859                 Err(APIError::APIMisuseError{ .. }) => {},
860                 _ => panic!("unexpected result applying invalid cltv_expiry_delta"),
861         }
862
863         // Increase the base fee which should trigger a new ChannelUpdate.
864         let mut config = nodes[1].node.list_usable_channels().iter()
865                 .find(|channel| channel.channel_id == channel_to_update.0).unwrap()
866                 .config.unwrap();
867         config.forwarding_fee_base_msat = u32::max_value();
868         let msg = update_and_get_channel_update(&config, true, None, false).unwrap();
869
870         // The old policy should still be in effect until a new block is connected.
871         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[2]]], PAYMENT_AMT,
872                 payment_hash, payment_secret);
873         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
874
875         // Connect a block, which should expire the previous config, leading to a failure when
876         // forwarding the HTLC.
877         expire_prev_config();
878         expect_onion_failure("fee_insufficient", UPDATE|12, &msg);
879
880         // Redundant updates should not trigger a new ChannelUpdate.
881         assert!(update_and_get_channel_update(&config, false, None, false).is_none());
882
883         // Similarly, updates that do not have an affect on ChannelUpdate should not trigger a new one.
884         config.force_close_avoidance_max_fee_satoshis *= 2;
885         assert!(update_and_get_channel_update(&config, false, None, false).is_none());
886
887         // Reset the base fee to the default and increase the proportional fee which should trigger a
888         // new ChannelUpdate.
889         config.forwarding_fee_base_msat = default_config.forwarding_fee_base_msat;
890         config.cltv_expiry_delta = u16::max_value();
891         let msg = update_and_get_channel_update(&config, true, Some(&msg), true).unwrap();
892         expect_onion_failure("incorrect_cltv_expiry", UPDATE|13, &msg);
893
894         // Reset the proportional fee and increase the CLTV expiry delta which should trigger a new
895         // ChannelUpdate.
896         config.cltv_expiry_delta = default_config.cltv_expiry_delta;
897         config.forwarding_fee_proportional_millionths = u32::max_value();
898         let msg = update_and_get_channel_update(&config, true, Some(&msg), true).unwrap();
899         expect_onion_failure("fee_insufficient", UPDATE|12, &msg);
900
901         // To test persistence of the updated config, we'll re-initialize the ChannelManager.
902         let config_after_restart = {
903                 let chan_1_monitor_serialized = get_monitor!(nodes[1], other_channel.3).encode();
904                 let chan_2_monitor_serialized = get_monitor!(nodes[1], channel_to_update.0).encode();
905                 reload_node!(nodes[1], *nodes[1].node.get_current_default_configuration(), &nodes[1].node.encode(),
906                         &[&chan_1_monitor_serialized, &chan_2_monitor_serialized], persister, chain_monitor, channel_manager_1_deserialized);
907                 nodes[1].node.list_channels().iter()
908                         .find(|channel| channel.channel_id == channel_to_update.0).unwrap()
909                         .config.unwrap()
910         };
911         assert_eq!(config, config_after_restart);
912 }
913
914 #[test]
915 fn test_onion_failure_stale_channel_update() {
916         do_test_onion_failure_stale_channel_update(false);
917         do_test_onion_failure_stale_channel_update(true);
918 }
919
920 #[test]
921 fn test_always_create_tlv_format_onion_payloads() {
922         // Verify that we always generate tlv onion format payloads, even if the features specifically
923         // specifies no support for variable length onions, as the legacy payload format has been
924         // deprecated in BOLT4.
925         let chanmon_cfgs = create_chanmon_cfgs(3);
926         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
927
928         // Set `node[1]`'s init features to features which return `false` for
929         // `supports_variable_length_onion()`
930         let mut no_variable_length_onion_features = InitFeatures::empty();
931         no_variable_length_onion_features.set_static_remote_key_required();
932         *node_cfgs[1].override_init_features.borrow_mut() = Some(no_variable_length_onion_features);
933
934         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
935         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
936
937         create_announced_chan_between_nodes(&nodes, 0, 1);
938         create_announced_chan_between_nodes(&nodes, 1, 2);
939
940         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
941                 .with_bolt11_features(Bolt11InvoiceFeatures::empty()).unwrap();
942         let (route, _payment_hash, _payment_preimage, _payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, 40000);
943
944         let hops = &route.paths[0].hops;
945         // Asserts that the first hop to `node[1]` signals no support for variable length onions.
946         assert!(!hops[0].node_features.supports_variable_length_onion());
947         // Asserts that the first hop to `node[1]` signals no support for variable length onions.
948         assert!(!hops[1].node_features.supports_variable_length_onion());
949
950         let cur_height = nodes[0].best_block_info().1 + 1;
951         let (onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(
952                 &route.paths[0], 40000, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
953
954         match onion_payloads[0] {
955                 msgs::OutboundOnionPayload::Forward {..} => {},
956                 _ => { panic!(
957                         "Should have generated a `msgs::OnionHopDataFormat::NonFinalNode` payload for `hops[0]`,
958                         despite that the features signals no support for variable length onions"
959                 )}
960         }
961         match onion_payloads[1] {
962                 msgs::OutboundOnionPayload::Receive {..} => {},
963                 _ => {panic!(
964                         "Should have generated a `msgs::OnionHopDataFormat::FinalNode` payload for `hops[1]`,
965                         despite that the features signals no support for variable length onions"
966                 )}
967         }
968 }
969
970 #[test]
971 fn test_trampoline_onion_payload_serialization() {
972         // As per https://github.com/lightning/bolts/blob/c01d2e6267d4a8d1095f0f1188970055a9a22d29/bolt04/trampoline-payment-onion-test.json#L3
973         let trampoline_payload = OutboundTrampolinePayload::Forward {
974                 amt_to_forward: 100000000,
975                 outgoing_cltv_value: 800000,
976                 outgoing_node_id: PublicKey::from_slice(&<Vec<u8>>::from_hex("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()).unwrap(),
977         };
978
979         let slice_to_hex = |slice: &[u8]| {
980                 slice.iter()
981                         .map(|b| format!("{:02x}", b).to_string())
982                         .collect::<String>()
983         };
984
985         let carol_payload_hex = slice_to_hex(&trampoline_payload.encode());
986         assert_eq!(carol_payload_hex, "2e020405f5e10004030c35000e2102edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145");
987 }
988
989 fn do_test_fail_htlc_backwards_with_reason(failure_code: FailureCode) {
990
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         create_announced_chan_between_nodes(&nodes, 0, 1);
997
998         let payment_amount = 100_000;
999         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_amount);
1000         nodes[0].node.send_payment_with_route(&route, payment_hash,
1001                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1002         check_added_monitors!(nodes[0], 1);
1003
1004         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1005         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
1006         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1007         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1008
1009         expect_pending_htlcs_forwardable!(nodes[1]);
1010         expect_payment_claimable!(nodes[1], payment_hash, payment_secret, payment_amount);
1011         nodes[1].node.fail_htlc_backwards_with_reason(&payment_hash, failure_code);
1012
1013         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash }]);
1014         check_added_monitors!(nodes[1], 1);
1015
1016         let events = nodes[1].node.get_and_clear_pending_msg_events();
1017         assert_eq!(events.len(), 1);
1018         let (update_fail_htlc, commitment_signed) = match events[0] {
1019                 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
1020                         assert!(update_add_htlcs.is_empty());
1021                         assert!(update_fulfill_htlcs.is_empty());
1022                         assert_eq!(update_fail_htlcs.len(), 1);
1023                         assert!(update_fail_malformed_htlcs.is_empty());
1024                         assert!(update_fee.is_none());
1025                         (update_fail_htlcs[0].clone(), commitment_signed)
1026                 },
1027                 _ => panic!("Unexpected event"),
1028         };
1029
1030         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
1031         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
1032
1033         let failure_data = match failure_code {
1034                 FailureCode::TemporaryNodeFailure => vec![],
1035                 FailureCode::RequiredNodeFeatureMissing => vec![],
1036                 FailureCode::IncorrectOrUnknownPaymentDetails => {
1037                         let mut htlc_msat_height_data = (payment_amount as u64).to_be_bytes().to_vec();
1038                         htlc_msat_height_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
1039                         htlc_msat_height_data
1040                 },
1041                 FailureCode::InvalidOnionPayload(data) => {
1042                         match data {
1043                                 Some((typ, offset)) => [BigSize(typ).encode(), offset.encode()].concat(),
1044                                 None => Vec::new(),
1045                         }
1046                 }
1047         };
1048
1049         let failure_code = failure_code.into();
1050         let permanent_flag = 0x4000;
1051         let permanent_fail = (failure_code & permanent_flag) != 0;
1052         expect_payment_failed!(nodes[0], payment_hash, permanent_fail, failure_code, failure_data);
1053
1054 }
1055
1056 #[test]
1057 fn test_fail_htlc_backwards_with_reason() {
1058         do_test_fail_htlc_backwards_with_reason(FailureCode::TemporaryNodeFailure);
1059         do_test_fail_htlc_backwards_with_reason(FailureCode::RequiredNodeFeatureMissing);
1060         do_test_fail_htlc_backwards_with_reason(FailureCode::IncorrectOrUnknownPaymentDetails);
1061         do_test_fail_htlc_backwards_with_reason(FailureCode::InvalidOnionPayload(Some((1 << 16, 42))));
1062         do_test_fail_htlc_backwards_with_reason(FailureCode::InvalidOnionPayload(None));
1063 }
1064
1065 macro_rules! get_phantom_route {
1066         ($nodes: expr, $amt: expr, $channel: expr) => {{
1067                 let phantom_pubkey = $nodes[1].keys_manager.get_node_id(Recipient::PhantomNode).unwrap();
1068                 let phantom_route_hint = $nodes[1].node.get_phantom_route_hints();
1069                 let payment_params = PaymentParameters::from_node_id(phantom_pubkey, TEST_FINAL_CLTV)
1070                         .with_bolt11_features($nodes[1].node.bolt11_invoice_features()).unwrap()
1071                         .with_route_hints(vec![RouteHint(vec![
1072                                         RouteHintHop {
1073                                                 src_node_id: $nodes[0].node.get_our_node_id(),
1074                                                 short_channel_id: $channel.0.contents.short_channel_id,
1075                                                 fees: RoutingFees {
1076                                                         base_msat: $channel.0.contents.fee_base_msat,
1077                                                         proportional_millionths: $channel.0.contents.fee_proportional_millionths,
1078                                                 },
1079                                                 cltv_expiry_delta: $channel.0.contents.cltv_expiry_delta,
1080                                                 htlc_minimum_msat: None,
1081                                                 htlc_maximum_msat: None,
1082                                         },
1083                                         RouteHintHop {
1084                                                 src_node_id: phantom_route_hint.real_node_pubkey,
1085                                                 short_channel_id: phantom_route_hint.phantom_scid,
1086                                                 fees: RoutingFees {
1087                                                         base_msat: 0,
1088                                                         proportional_millionths: 0,
1089                                                 },
1090                                                 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1091                                                 htlc_minimum_msat: None,
1092                                                 htlc_maximum_msat: None,
1093                                         }
1094                 ])]).unwrap();
1095                 let scorer = test_utils::TestScorer::new();
1096                 let network_graph = $nodes[0].network_graph.read_only();
1097                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, $amt);
1098                 (get_route(
1099                         &$nodes[0].node.get_our_node_id(), &route_params, &network_graph,
1100                         Some(&$nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
1101                         $nodes[0].logger, &scorer, &Default::default(), &[0u8; 32]
1102                 ).unwrap(), phantom_route_hint.phantom_scid)
1103         }
1104 }}
1105
1106 #[test]
1107 fn test_phantom_onion_hmac_failure() {
1108         let chanmon_cfgs = create_chanmon_cfgs(2);
1109         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1110         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1111         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1112
1113         let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1114
1115         // Get the route.
1116         let recv_value_msat = 10_000;
1117         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
1118         let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
1119
1120         // Route the HTLC through to the destination.
1121         nodes[0].node.send_payment_with_route(&route, payment_hash,
1122                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1123         check_added_monitors!(nodes[0], 1);
1124         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1125         let mut update_add = update_0.update_add_htlcs[0].clone();
1126
1127         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1128         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1129
1130         // Modify the payload so the phantom hop's HMAC is bogus.
1131         let sha256_of_onion = {
1132                 let mut forward_htlcs = nodes[1].node.forward_htlcs.lock().unwrap();
1133                 let mut pending_forward = forward_htlcs.get_mut(&phantom_scid).unwrap();
1134                 match pending_forward[0] {
1135                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
1136                                 forward_info: PendingHTLCInfo {
1137                                         routing: PendingHTLCRouting::Forward { ref mut onion_packet, .. },
1138                                         ..
1139                                 }, ..
1140                         }) => {
1141                                 onion_packet.hmac[onion_packet.hmac.len() - 1] ^= 1;
1142                                 Sha256::hash(&onion_packet.hop_data).to_byte_array().to_vec()
1143                         },
1144                         _ => panic!("Unexpected forward"),
1145                 }
1146         };
1147         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1148         nodes[1].node.process_pending_htlc_forwards();
1149         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1150         nodes[1].node.process_pending_htlc_forwards();
1151         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1152         check_added_monitors!(&nodes[1], 1);
1153         assert!(update_1.update_fail_htlcs.len() == 1);
1154         let fail_msg = update_1.update_fail_htlcs[0].clone();
1155         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1156         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1157
1158         // Ensure the payment fails with the expected error.
1159         let mut fail_conditions = PaymentFailedConditions::new()
1160                 .blamed_scid(phantom_scid)
1161                 .blamed_chan_closed(true)
1162                 .expected_htlc_error_data(0x8000 | 0x4000 | 5, &sha256_of_onion);
1163         expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1164 }
1165
1166 #[test]
1167 fn test_phantom_invalid_onion_payload() {
1168         let chanmon_cfgs = create_chanmon_cfgs(2);
1169         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1170         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1171         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1172
1173         let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1174
1175         // Get the route.
1176         let recv_value_msat = 10_000;
1177         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
1178         let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
1179
1180         // We'll use the session priv later when constructing an invalid onion packet.
1181         let session_priv = [3; 32];
1182         *nodes[0].keys_manager.override_random_bytes.lock().unwrap() = Some(session_priv);
1183         nodes[0].node.send_payment_with_route(&route, payment_hash,
1184                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1185         check_added_monitors!(nodes[0], 1);
1186         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1187         let mut update_add = update_0.update_add_htlcs[0].clone();
1188
1189         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1190         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1191
1192         // Modify the onion packet to have an invalid payment amount.
1193         for (_, pending_forwards) in nodes[1].node.forward_htlcs.lock().unwrap().iter_mut() {
1194                 for f in pending_forwards.iter_mut() {
1195                         match f {
1196                                 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
1197                                         forward_info: PendingHTLCInfo {
1198                                                 routing: PendingHTLCRouting::Forward { ref mut onion_packet, .. },
1199                                                 ..
1200                                         }, ..
1201                                 }) => {
1202                                         // Construct the onion payloads for the entire route and an invalid amount.
1203                                         let height = nodes[0].best_block_info().1;
1204                                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
1205                                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
1206                                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(
1207                                                 &route.paths[0], msgs::MAX_VALUE_MSAT + 1,
1208                                                 RecipientOnionFields::secret_only(payment_secret), height + 1, &None).unwrap();
1209                                         // We only want to construct the onion packet for the last hop, not the entire route, so
1210                                         // remove the first hop's payload and its keys.
1211                                         onion_keys.remove(0);
1212                                         onion_payloads.remove(0);
1213
1214                                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1215                                         onion_packet.hop_data = new_onion_packet.hop_data;
1216                                         onion_packet.hmac = new_onion_packet.hmac;
1217                                 },
1218                                 _ => panic!("Unexpected forward"),
1219                         }
1220                 }
1221         }
1222         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1223         nodes[1].node.process_pending_htlc_forwards();
1224         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1225         nodes[1].node.process_pending_htlc_forwards();
1226         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1227         check_added_monitors!(&nodes[1], 1);
1228         assert!(update_1.update_fail_htlcs.len() == 1);
1229         let fail_msg = update_1.update_fail_htlcs[0].clone();
1230         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1231         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1232
1233         // Ensure the payment fails with the expected error.
1234         let error_data = Vec::new();
1235         let mut fail_conditions = PaymentFailedConditions::new()
1236                 .blamed_scid(phantom_scid)
1237                 .blamed_chan_closed(true)
1238                 .expected_htlc_error_data(0x4000 | 22, &error_data);
1239         expect_payment_failed_conditions(&nodes[0], payment_hash, true, fail_conditions);
1240 }
1241
1242 #[test]
1243 fn test_phantom_final_incorrect_cltv_expiry() {
1244         let chanmon_cfgs = create_chanmon_cfgs(2);
1245         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1246         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1247         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1248
1249         let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1250
1251         // Get the route.
1252         let recv_value_msat = 10_000;
1253         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
1254         let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
1255
1256         // Route the HTLC through to the destination.
1257         nodes[0].node.send_payment_with_route(&route, payment_hash,
1258                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1259         check_added_monitors!(nodes[0], 1);
1260         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1261         let mut update_add = update_0.update_add_htlcs[0].clone();
1262
1263         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1264         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1265
1266         // Modify the payload so the phantom hop's HMAC is bogus.
1267         for (_, pending_forwards) in nodes[1].node.forward_htlcs.lock().unwrap().iter_mut() {
1268                 for f in pending_forwards.iter_mut() {
1269                         match f {
1270                                 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
1271                                         forward_info: PendingHTLCInfo { ref mut outgoing_cltv_value, .. }, ..
1272                                 }) => {
1273                                         *outgoing_cltv_value -= 1;
1274                                 },
1275                                 _ => panic!("Unexpected forward"),
1276                         }
1277                 }
1278         }
1279         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1280         nodes[1].node.process_pending_htlc_forwards();
1281         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1282         nodes[1].node.process_pending_htlc_forwards();
1283         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1284         check_added_monitors!(&nodes[1], 1);
1285         assert!(update_1.update_fail_htlcs.len() == 1);
1286         let fail_msg = update_1.update_fail_htlcs[0].clone();
1287         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1288         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1289
1290         // Ensure the payment fails with the expected error.
1291         let expected_cltv: u32 = 80;
1292         let error_data = expected_cltv.to_be_bytes().to_vec();
1293         let mut fail_conditions = PaymentFailedConditions::new()
1294                 .blamed_scid(phantom_scid)
1295                 .expected_htlc_error_data(18, &error_data);
1296         expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1297 }
1298
1299 #[test]
1300 fn test_phantom_failure_too_low_cltv() {
1301         let chanmon_cfgs = create_chanmon_cfgs(2);
1302         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1303         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1304         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1305
1306         let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1307
1308         // Get the route.
1309         let recv_value_msat = 10_000;
1310         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
1311         let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
1312
1313         // Modify the route to have a too-low cltv.
1314         route.paths[0].hops[1].cltv_expiry_delta = 5;
1315
1316         // Route the HTLC through to the destination.
1317         nodes[0].node.send_payment_with_route(&route, payment_hash,
1318                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1319         check_added_monitors!(nodes[0], 1);
1320         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1321         let mut update_add = update_0.update_add_htlcs[0].clone();
1322
1323         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1324         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1325
1326         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1327         nodes[1].node.process_pending_htlc_forwards();
1328         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1329         nodes[1].node.process_pending_htlc_forwards();
1330         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1331         check_added_monitors!(&nodes[1], 1);
1332         assert!(update_1.update_fail_htlcs.len() == 1);
1333         let fail_msg = update_1.update_fail_htlcs[0].clone();
1334         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1335         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1336
1337         // Ensure the payment fails with the expected error.
1338         let mut error_data = recv_value_msat.to_be_bytes().to_vec();
1339         error_data.extend_from_slice(
1340                 &nodes[0].node.best_block.read().unwrap().height.to_be_bytes(),
1341         );
1342         let mut fail_conditions = PaymentFailedConditions::new()
1343                 .blamed_scid(phantom_scid)
1344                 .expected_htlc_error_data(0x4000 | 15, &error_data);
1345         expect_payment_failed_conditions(&nodes[0], payment_hash, true, fail_conditions);
1346 }
1347
1348 #[test]
1349 fn test_phantom_failure_modified_cltv() {
1350         // Test that we fail back phantoms if the upstream node fiddled with the CLTV too much with the
1351         // correct error code.
1352         let chanmon_cfgs = create_chanmon_cfgs(2);
1353         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1354         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1355         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1356
1357         let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1358
1359         // Get the route.
1360         let recv_value_msat = 10_000;
1361         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
1362         let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
1363
1364         // Route the HTLC through to the destination.
1365         nodes[0].node.send_payment_with_route(&route, payment_hash,
1366                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1367         check_added_monitors!(nodes[0], 1);
1368         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1369         let mut update_add = update_0.update_add_htlcs[0].clone();
1370
1371         // Modify the route to have a too-low cltv.
1372         update_add.cltv_expiry -= 10;
1373
1374         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1375         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1376
1377         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1378         assert!(update_1.update_fail_htlcs.len() == 1);
1379         let fail_msg = update_1.update_fail_htlcs[0].clone();
1380         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1381         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1382
1383         // Ensure the payment fails with the expected error.
1384         let mut fail_conditions = PaymentFailedConditions::new()
1385                 .blamed_scid(phantom_scid)
1386                 .expected_htlc_error_data(0x2000 | 2, &[]);
1387         expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1388 }
1389
1390 #[test]
1391 fn test_phantom_failure_expires_too_soon() {
1392         // Test that we fail back phantoms if the HTLC got delayed and we got blocks in between with
1393         // the correct error code.
1394         let chanmon_cfgs = create_chanmon_cfgs(2);
1395         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1396         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1397         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1398
1399         let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1400
1401         // Get the route.
1402         let recv_value_msat = 10_000;
1403         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
1404         let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
1405
1406         // Route the HTLC through to the destination.
1407         nodes[0].node.send_payment_with_route(&route, payment_hash,
1408                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1409         check_added_monitors!(nodes[0], 1);
1410         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1411         let mut update_add = update_0.update_add_htlcs[0].clone();
1412
1413         connect_blocks(&nodes[1], CLTV_FAR_FAR_AWAY);
1414         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1415         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1416
1417         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1418         assert!(update_1.update_fail_htlcs.len() == 1);
1419         let fail_msg = update_1.update_fail_htlcs[0].clone();
1420         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1421         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1422
1423         // Ensure the payment fails with the expected error.
1424         let mut fail_conditions = PaymentFailedConditions::new()
1425                 .blamed_scid(phantom_scid)
1426                 .expected_htlc_error_data(0x2000 | 2, &[]);
1427         expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1428 }
1429
1430 #[test]
1431 fn test_phantom_failure_too_low_recv_amt() {
1432         let chanmon_cfgs = create_chanmon_cfgs(2);
1433         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1434         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1435         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1436
1437         let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1438
1439         // Get the route with a too-low amount.
1440         let recv_amt_msat = 10_000;
1441         let bad_recv_amt_msat = recv_amt_msat - 10;
1442         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_amt_msat));
1443         let (mut route, phantom_scid) = get_phantom_route!(nodes, bad_recv_amt_msat, channel);
1444
1445         // Route the HTLC through to the destination.
1446         nodes[0].node.send_payment_with_route(&route, payment_hash,
1447                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1448         check_added_monitors!(nodes[0], 1);
1449         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1450         let mut update_add = update_0.update_add_htlcs[0].clone();
1451
1452         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1453         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1454
1455         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1456         nodes[1].node.process_pending_htlc_forwards();
1457         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1458         nodes[1].node.process_pending_htlc_forwards();
1459         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
1460         nodes[1].node.process_pending_htlc_forwards();
1461         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1462         check_added_monitors!(&nodes[1], 1);
1463         assert!(update_1.update_fail_htlcs.len() == 1);
1464         let fail_msg = update_1.update_fail_htlcs[0].clone();
1465         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1466         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1467
1468         // Ensure the payment fails with the expected error.
1469         let mut error_data = bad_recv_amt_msat.to_be_bytes().to_vec();
1470         error_data.extend_from_slice(&nodes[1].node.best_block.read().unwrap().height.to_be_bytes());
1471         let mut fail_conditions = PaymentFailedConditions::new()
1472                 .blamed_scid(phantom_scid)
1473                 .expected_htlc_error_data(0x4000 | 15, &error_data);
1474         expect_payment_failed_conditions(&nodes[0], payment_hash, true, fail_conditions);
1475 }
1476
1477 #[test]
1478 fn test_phantom_dust_exposure_failure() {
1479         do_test_phantom_dust_exposure_failure(false);
1480         do_test_phantom_dust_exposure_failure(true);
1481 }
1482
1483 fn do_test_phantom_dust_exposure_failure(multiplier_dust_limit: bool) {
1484         // Set the max dust exposure to the dust limit.
1485         let max_dust_exposure = 546;
1486         let mut receiver_config = UserConfig::default();
1487         // Default test fee estimator rate is 253, so to set the max dust exposure to the dust limit,
1488         // we need to set the multiplier to 2.
1489         receiver_config.channel_config.max_dust_htlc_exposure =
1490                 if multiplier_dust_limit { MaxDustHTLCExposure::FeeRateMultiplier(2) }
1491                 else { MaxDustHTLCExposure::FixedLimitMsat(max_dust_exposure) };
1492         receiver_config.channel_handshake_config.announced_channel = true;
1493
1494         let chanmon_cfgs = create_chanmon_cfgs(2);
1495         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1496         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(receiver_config)]);
1497         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1498
1499         let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1500
1501         // Get the route with an amount exceeding the dust exposure threshold of nodes[1].
1502         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(max_dust_exposure + 1));
1503         let (mut route, _) = get_phantom_route!(nodes, max_dust_exposure + 1, channel);
1504
1505         // Route the HTLC through to the destination.
1506         nodes[0].node.send_payment_with_route(&route, payment_hash,
1507                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1508         check_added_monitors!(nodes[0], 1);
1509         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1510         let mut update_add = update_0.update_add_htlcs[0].clone();
1511
1512         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1513         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1514
1515         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1516         assert!(update_1.update_fail_htlcs.len() == 1);
1517         let fail_msg = update_1.update_fail_htlcs[0].clone();
1518         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1519         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1520
1521         // Ensure the payment fails with the expected error.
1522         let mut err_data = Vec::new();
1523         err_data.extend_from_slice(&(channel.1.serialized_length() as u16 + 2).to_be_bytes());
1524         err_data.extend_from_slice(&ChannelUpdate::TYPE.to_be_bytes());
1525         err_data.extend_from_slice(&channel.1.encode());
1526
1527         let mut fail_conditions = PaymentFailedConditions::new()
1528                 .blamed_scid(channel.0.contents.short_channel_id)
1529                 .blamed_chan_closed(false)
1530                 .expected_htlc_error_data(0x1000 | 7, &err_data);
1531                 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1532 }
1533
1534 #[test]
1535 fn test_phantom_failure_reject_payment() {
1536         // Test that the user can successfully fail back a phantom node payment.
1537         let chanmon_cfgs = create_chanmon_cfgs(2);
1538         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1539         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1540         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1541
1542         let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1543
1544         // Get the route with a too-low amount.
1545         let recv_amt_msat = 10_000;
1546         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_amt_msat));
1547         let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_amt_msat, channel);
1548
1549         // Route the HTLC through to the destination.
1550         nodes[0].node.send_payment_with_route(&route, payment_hash,
1551                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1552         check_added_monitors!(nodes[0], 1);
1553         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1554         let mut update_add = update_0.update_add_htlcs[0].clone();
1555
1556         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1557         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1558
1559         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1560         nodes[1].node.process_pending_htlc_forwards();
1561         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1562         nodes[1].node.process_pending_htlc_forwards();
1563         expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_amt_msat, None, route.paths[0].hops.last().unwrap().pubkey);
1564         nodes[1].node.fail_htlc_backwards(&payment_hash);
1565         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1566         nodes[1].node.process_pending_htlc_forwards();
1567
1568         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1569         check_added_monitors!(&nodes[1], 1);
1570         assert!(update_1.update_fail_htlcs.len() == 1);
1571         let fail_msg = update_1.update_fail_htlcs[0].clone();
1572         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1573         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1574
1575         // Ensure the payment fails with the expected error.
1576         let mut error_data = recv_amt_msat.to_be_bytes().to_vec();
1577         error_data.extend_from_slice(&nodes[1].node.best_block.read().unwrap().height.to_be_bytes());
1578         let mut fail_conditions = PaymentFailedConditions::new()
1579                 .blamed_scid(phantom_scid)
1580                 .expected_htlc_error_data(0x4000 | 15, &error_data);
1581         expect_payment_failed_conditions(&nodes[0], payment_hash, true, fail_conditions);
1582 }