1 // This file is Copyright its original authors, visible in version control
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
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.
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::types::{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::functional_test_utils::test_default_channel_config;
26 use crate::ln::msgs::{ChannelMessageHandler, ChannelUpdate, OutboundTrampolinePayload};
27 use crate::ln::wire::Encode;
28 use crate::util::ser::{Writeable, Writer, BigSize};
29 use crate::util::test_utils;
30 use crate::util::config::{UserConfig, ChannelConfig, MaxDustHTLCExposure};
31 use crate::util::errors::APIError;
33 use bitcoin::blockdata::constants::ChainHash;
34 use bitcoin::hashes::{Hash, HashEngine};
35 use bitcoin::hashes::hmac::{Hmac, HmacEngine};
36 use bitcoin::hashes::sha256::Hash as Sha256;
38 use bitcoin::secp256k1;
39 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
42 use crate::prelude::*;
43 use bitcoin::hashes::hex::FromHex;
45 use crate::ln::functional_test_utils::*;
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),
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);
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>
67 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
68 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
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);
76 $event_type { .. } => {},
77 _ => panic!("Unexpected event"),
82 macro_rules! expect_htlc_forward {
84 expect_event!($node, Event::PendingHTLCsForwardable);
85 $node.node.process_pending_htlc_forwards();
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);
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);
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));
111 1|2|3|200 => { // final node failure; forwarding to 2
112 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
114 if test_case != 200 {
117 expect_htlc_forward!(&nodes[1]);
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);
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);
132 if test_case == 2 || test_case == 200 {
133 expect_htlc_forward!(&nodes[2]);
134 expect_event!(&nodes[2], Event::PaymentClaimable);
136 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
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);
143 assert!(update_2_1.update_fail_htlcs.len() == 1);
145 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
146 if test_case == 200 {
147 callback_fail(&mut fail_msg);
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);
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);
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);
168 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
170 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]);
173 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
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::ChannelFailure { ref short_channel_id, ref is_permanent } => {
184 if let NetworkUpdate::ChannelFailure { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
185 assert!(*short_channel_id == *expected_short_channel_id);
186 assert!(*is_permanent == *expected_is_permanent);
188 panic!("Unexpected message event");
191 &NetworkUpdate::NodeFailure { ref node_id, ref is_permanent } => {
192 if let NetworkUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
193 assert!(*node_id == *expected_node_id);
194 assert!(*is_permanent == *expected_is_permanent);
196 panic!("Unexpected message event");
200 None => panic!("Expected channel update"),
203 assert!(network_update.is_none());
205 if let Some(expected_short_channel_id) = expected_short_channel_id {
206 match short_channel_id {
207 Some(short_channel_id) => assert_eq!(*short_channel_id, expected_short_channel_id),
208 None => panic!("Expected short channel id"),
211 assert!(short_channel_id.is_none());
214 panic!("Unexpected event");
217 Event::PaymentFailed { payment_hash: ev_payment_hash, payment_id: ev_payment_id, reason: ref ev_reason } => {
218 assert_eq!(*payment_hash, ev_payment_hash);
219 assert_eq!(payment_id, ev_payment_id);
220 assert_eq!(if expected_retryable {
221 PaymentFailureReason::RetriesExhausted
223 PaymentFailureReason::RecipientRejected
224 }, ev_reason.unwrap());
226 _ => panic!("Unexpected second event"),
230 impl msgs::ChannelUpdate {
231 fn dummy(short_channel_id: u64) -> msgs::ChannelUpdate {
232 use bitcoin::hash_types::BlockHash;
233 use bitcoin::secp256k1::ffi::Signature as FFISignature;
234 use bitcoin::secp256k1::ecdsa::Signature;
235 msgs::ChannelUpdate {
236 signature: Signature::from(unsafe { FFISignature::new() }),
237 contents: msgs::UnsignedChannelUpdate {
238 chain_hash: ChainHash::from(BlockHash::hash(&vec![0u8][..]).as_ref()),
242 cltv_expiry_delta: 0,
243 htlc_minimum_msat: 0,
244 htlc_maximum_msat: msgs::MAX_VALUE_MSAT,
246 fee_proportional_millionths: 0,
253 struct BogusOnionHopData {
256 impl BogusOnionHopData {
257 fn new(orig: msgs::OutboundOnionPayload) -> Self {
258 Self { data: orig.encode() }
261 impl Writeable for BogusOnionHopData {
262 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
263 writer.write_all(&self.data[..])
267 const BADONION: u16 = 0x8000;
268 const PERM: u16 = 0x4000;
269 const NODE: u16 = 0x2000;
270 const UPDATE: u16 = 0x1000;
273 fn test_fee_failures() {
274 // Tests that the fee required when forwarding remains consistent over time. This was
275 // previously broken, with forwarding fees floating based on the fee estimator at the time of
278 // When this test was written, the default base fee floated based on the HTLC count.
279 // It is now fixed, so we simply set the fee to the expected value here.
280 let mut config = test_default_channel_config();
281 config.channel_config.forwarding_fee_base_msat = 196;
283 let chanmon_cfgs = create_chanmon_cfgs(3);
284 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
285 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config), Some(config), Some(config)]);
286 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
287 let channels = [create_announced_chan_between_nodes(&nodes, 0, 1), create_announced_chan_between_nodes(&nodes, 1, 2)];
290 let (route, payment_hash_success, payment_preimage_success, payment_secret_success) = get_route_and_payment_hash!(nodes[0], nodes[2], 40_000);
291 nodes[0].node.send_payment_with_route(&route, payment_hash_success,
292 RecipientOnionFields::secret_only(payment_secret_success), PaymentId(payment_hash_success.0)).unwrap();
293 check_added_monitors!(nodes[0], 1);
294 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 40_000, payment_hash_success, payment_secret_success);
295 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_success);
297 // If the hop gives fee_insufficient but enough fees were provided, then the previous hop
298 // malleated the payment before forwarding, taking funds when they shouldn't have. However,
299 // because we ignore channel update contents, we will still blame the 2nd channel.
300 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
301 let short_channel_id = channels[1].0.contents.short_channel_id;
302 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
303 msg.amount_msat -= 1;
304 }, || {}, true, Some(UPDATE|12), Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: false}), Some(short_channel_id));
306 // In an earlier version, we spuriously failed to forward payments if the expected feerate
307 // changed between the channel open and the payment.
309 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
313 let (payment_preimage_success, payment_hash_success, payment_secret_success) = get_payment_preimage_hash!(nodes[2]);
314 nodes[0].node.send_payment_with_route(&route, payment_hash_success,
315 RecipientOnionFields::secret_only(payment_secret_success), PaymentId(payment_hash_success.0)).unwrap();
316 check_added_monitors!(nodes[0], 1);
317 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 40_000, payment_hash_success, payment_secret_success);
318 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_success);
322 fn test_onion_failure() {
323 // When we check for amount_below_minimum below, we want to test that we're using the *right*
324 // amount, thus we need different htlc_minimum_msat values. We set node[2]'s htlc_minimum_msat
325 // to 2000, which is above the default value of 1000 set in create_node_chanmgrs.
326 // This exposed a previous bug because we were using the wrong value all the way down in
327 // Channel::get_counterparty_htlc_minimum_msat().
328 let mut node_2_cfg: UserConfig = test_default_channel_config();
329 node_2_cfg.channel_handshake_config.our_htlc_minimum_msat = 2000;
330 node_2_cfg.channel_handshake_config.announced_channel = true;
331 node_2_cfg.channel_handshake_limits.force_announced_channel_preference = false;
333 // When this test was written, the default base fee floated based on the HTLC count.
334 // It is now fixed, so we simply set the fee to the expected value here.
335 let mut config = test_default_channel_config();
336 config.channel_config.forwarding_fee_base_msat = 196;
338 let chanmon_cfgs = create_chanmon_cfgs(3);
339 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
340 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config), Some(config), Some(node_2_cfg)]);
341 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
342 let channels = [create_announced_chan_between_nodes(&nodes, 0, 1), create_announced_chan_between_nodes(&nodes, 1, 2)];
343 for node in nodes.iter() {
344 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([3; 32]);
346 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 40000);
348 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000);
350 // intermediate node failure
351 let short_channel_id = channels[1].0.contents.short_channel_id;
352 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
353 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
354 let cur_height = nodes[0].best_block_info().1 + 1;
355 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
356 let recipient_onion_fields = RecipientOnionFields::spontaneous_empty();
357 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(
358 &route.paths[0], 40000, &recipient_onion_fields, cur_height, &None).unwrap();
359 let mut new_payloads = Vec::new();
360 for payload in onion_payloads.drain(..) {
361 new_payloads.push(BogusOnionHopData::new(payload));
363 // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
364 // describing a length-1 TLV payload, which is obviously bogus.
365 new_payloads[0].data[0] = 1;
366 msg.onion_routing_packet = onion_utils::construct_onion_packet_with_writable_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
367 }, ||{}, true, Some(PERM|22), Some(NetworkUpdate::ChannelFailure{short_channel_id, is_permanent: true}), Some(short_channel_id));
369 // final node failure
370 let short_channel_id = channels[1].0.contents.short_channel_id;
371 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, &payment_secret, |msg| {
372 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
373 let cur_height = nodes[0].best_block_info().1 + 1;
374 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
375 let recipient_onion_fields = RecipientOnionFields::spontaneous_empty();
376 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(
377 &route.paths[0], 40000, &recipient_onion_fields, cur_height, &None).unwrap();
378 let mut new_payloads = Vec::new();
379 for payload in onion_payloads.drain(..) {
380 new_payloads.push(BogusOnionHopData::new(payload));
382 // break the last-hop payload by swapping the realm (0) byte for a byte describing a
383 // length-1 TLV payload, which is obviously bogus.
384 new_payloads[1].data[0] = 1;
385 msg.onion_routing_packet = onion_utils::construct_onion_packet_with_writable_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
386 }, ||{}, false, Some(PERM|22), Some(NetworkUpdate::ChannelFailure{short_channel_id, is_permanent: true}), Some(short_channel_id));
388 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
389 // receiving simulated fail messages
390 // intermediate node failure
391 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
393 msg.amount_msat -= 1;
395 // and tamper returning error message
396 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
397 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
398 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), NODE|2, &[0;0]);
399 }, ||{}, 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));
401 // final node failure
402 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
403 // and tamper returning error message
404 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
405 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
406 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[1].shared_secret.as_ref(), NODE|2, &[0;0]);
408 nodes[2].node.fail_htlc_backwards(&payment_hash);
409 }, 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));
410 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
412 // intermediate node failure
413 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
414 msg.amount_msat -= 1;
416 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
417 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
418 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), PERM|NODE|2, &[0;0]);
419 }, ||{}, 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));
421 // final node failure
422 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
423 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
424 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
425 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[1].shared_secret.as_ref(), PERM|NODE|2, &[0;0]);
427 nodes[2].node.fail_htlc_backwards(&payment_hash);
428 }, 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));
429 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
431 // intermediate node failure
432 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
433 msg.amount_msat -= 1;
435 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
436 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
437 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), PERM|NODE|3, &[0;0]);
439 nodes[2].node.fail_htlc_backwards(&payment_hash);
440 }, 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));
442 // final node failure
443 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
444 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
445 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
446 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[1].shared_secret.as_ref(), PERM|NODE|3, &[0;0]);
448 nodes[2].node.fail_htlc_backwards(&payment_hash);
449 }, 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));
450 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
452 // Our immediate peer sent UpdateFailMalformedHTLC because it couldn't understand the onion in
453 // the UpdateAddHTLC that we sent.
454 let short_channel_id = channels[0].0.contents.short_channel_id;
455 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
456 Some(BADONION|PERM|4), None, Some(short_channel_id));
458 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
459 Some(BADONION|PERM|5), None, Some(short_channel_id));
461 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,
462 Some(BADONION|PERM|6), None, Some(short_channel_id));
464 let short_channel_id = channels[1].0.contents.short_channel_id;
465 let chan_update = ChannelUpdate::dummy(short_channel_id);
467 let mut err_data = Vec::new();
468 err_data.extend_from_slice(&(chan_update.serialized_length() as u16 + 2).to_be_bytes());
469 err_data.extend_from_slice(&ChannelUpdate::TYPE.to_be_bytes());
470 err_data.extend_from_slice(&chan_update.encode());
471 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
472 msg.amount_msat -= 1;
474 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
475 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
476 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), UPDATE|7, &err_data);
477 }, ||{}, true, Some(UPDATE|7),
478 Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: false }),
479 Some(short_channel_id));
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;
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),
490 Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: false }),
491 Some(short_channel_id));
493 let short_channel_id = channels[1].0.contents.short_channel_id;
494 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
495 msg.amount_msat -= 1;
497 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
498 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
499 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), PERM|8, &[0;0]);
500 // short_channel_id from the processing node
501 }, ||{}, true, Some(PERM|8), Some(NetworkUpdate::ChannelFailure{short_channel_id, is_permanent: true}), Some(short_channel_id));
503 let short_channel_id = channels[1].0.contents.short_channel_id;
504 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
505 msg.amount_msat -= 1;
507 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
508 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
509 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), PERM|9, &[0;0]);
510 // short_channel_id from the processing node
511 }, ||{}, true, Some(PERM|9), Some(NetworkUpdate::ChannelFailure{short_channel_id, is_permanent: true}), Some(short_channel_id));
513 let mut bogus_route = route.clone();
514 bogus_route.paths[0].hops[1].short_channel_id -= 1;
515 let short_channel_id = bogus_route.paths[0].hops[1].short_channel_id;
516 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, &payment_secret, |_| {}, ||{}, true, Some(PERM|10),
517 Some(NetworkUpdate::ChannelFailure{short_channel_id, is_permanent:true}), Some(short_channel_id));
519 let short_channel_id = channels[1].0.contents.short_channel_id;
520 let amt_to_forward = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
521 .unwrap().lock().unwrap().channel_by_id.get(&channels[1].2).unwrap()
522 .context().get_counterparty_htlc_minimum_msat() - 1;
523 let mut bogus_route = route.clone();
524 let route_len = bogus_route.paths[0].hops.len();
525 bogus_route.paths[0].hops[route_len-1].fee_msat = amt_to_forward;
526 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, &payment_secret, |_| {}, ||{}, true, Some(UPDATE|11),
527 Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: false }),
528 Some(short_channel_id));
530 // Clear pending payments so that the following positive test has the correct payment hash.
531 for node in nodes.iter() {
532 node.node.clear_pending_payments();
535 // Test a positive test-case with one extra msat, meeting the minimum.
536 bogus_route.paths[0].hops[route_len-1].fee_msat = amt_to_forward + 1;
537 let preimage = send_along_route(&nodes[0], bogus_route, &[&nodes[1], &nodes[2]], amt_to_forward+1).0;
538 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], preimage);
540 // We ignore channel update contents in onion errors, so will blame the 2nd channel even though
541 // the first node is the one that messed up.
542 let short_channel_id = channels[1].0.contents.short_channel_id;
543 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
544 msg.amount_msat -= 1;
545 }, || {}, true, Some(UPDATE|12), Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: false}), Some(short_channel_id));
547 let short_channel_id = channels[1].0.contents.short_channel_id;
548 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
549 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
550 msg.cltv_expiry -= 1;
551 }, || {}, true, Some(UPDATE|13), Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: false}), Some(short_channel_id));
553 let short_channel_id = channels[1].0.contents.short_channel_id;
554 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
555 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
556 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
557 connect_blocks(&nodes[1], height - nodes[1].best_block_info().1);
558 connect_blocks(&nodes[2], height - nodes[2].best_block_info().1);
559 }, ||{}, true, Some(UPDATE|14),
560 Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: false }),
561 Some(short_channel_id));
563 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
564 nodes[2].node.fail_htlc_backwards(&payment_hash);
565 }, false, Some(PERM|15), None, None);
566 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
568 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, &payment_secret, |msg| {
569 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
570 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
571 connect_blocks(&nodes[1], height - nodes[1].best_block_info().1);
572 connect_blocks(&nodes[2], height - nodes[2].best_block_info().1);
573 }, || {}, false, Some(0x4000 | 15), None, None);
575 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
576 for (_, pending_forwards) in nodes[1].node.forward_htlcs.lock().unwrap().iter_mut() {
577 for f in pending_forwards.iter_mut() {
579 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) =>
580 forward_info.outgoing_cltv_value -= 1,
585 }, true, Some(18), None, Some(channels[1].0.contents.short_channel_id));
587 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
588 // violate amt_to_forward > msg.amount_msat
589 for (_, pending_forwards) in nodes[1].node.forward_htlcs.lock().unwrap().iter_mut() {
590 for f in pending_forwards.iter_mut() {
592 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) =>
593 forward_info.outgoing_amt_msat -= 1,
598 }, true, Some(19), None, Some(channels[1].0.contents.short_channel_id));
600 let short_channel_id = channels[1].0.contents.short_channel_id;
601 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
602 // disconnect event to the channel between nodes[1] ~ nodes[2]
603 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
604 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
605 }, true, Some(UPDATE|7),
606 Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: false }),
607 Some(short_channel_id));
608 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
609 // disconnect event to the channel between nodes[1] ~ nodes[2]
610 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
611 nodes[1].node.timer_tick_occurred();
612 nodes[2].node.timer_tick_occurred();
614 nodes[1].node.get_and_clear_pending_msg_events();
615 nodes[2].node.get_and_clear_pending_msg_events();
616 }, true, Some(UPDATE|20),
617 Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: false }),
618 Some(short_channel_id));
619 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[2]));
621 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
622 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
623 let mut route = route.clone();
624 let height = nodes[2].best_block_info().1;
625 route.paths[0].hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.paths[0].hops[0].cltv_expiry_delta + 1;
626 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
627 let recipient_onion_fields = RecipientOnionFields::spontaneous_empty();
628 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(
629 &route.paths[0], 40000, &recipient_onion_fields, height, &None).unwrap();
630 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
631 msg.cltv_expiry = htlc_cltv;
632 msg.onion_routing_packet = onion_packet;
633 }, ||{}, 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));
635 run_onion_failure_test_with_fail_intercept("mpp_timeout", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
636 // Tamper returning error message
637 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
638 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
639 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[1].shared_secret.as_ref(), 23, &[0;0]);
641 nodes[2].node.fail_htlc_backwards(&payment_hash);
642 }, true, Some(23), None, None);
644 run_onion_failure_test_with_fail_intercept("bogus err packet with valid hmac", 200, &nodes,
645 &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
646 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
647 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
648 let mut decoded_err_packet = msgs::DecodedOnionErrorPacket {
653 let um = onion_utils::gen_um_from_shared_secret(&onion_keys[1].shared_secret.as_ref());
654 let mut hmac = HmacEngine::<Sha256>::new(&um);
655 hmac.input(&decoded_err_packet.encode()[32..]);
656 decoded_err_packet.hmac = Hmac::from_engine(hmac).to_byte_array();
657 msg.reason = onion_utils::encrypt_failure_packet(
658 &onion_keys[1].shared_secret.as_ref(), &decoded_err_packet.encode()[..])
659 }, || nodes[2].node.fail_htlc_backwards(&payment_hash), false, None,
660 Some(NetworkUpdate::NodeFailure { node_id: route.paths[0].hops[1].pubkey, is_permanent: true }),
661 Some(channels[1].0.contents.short_channel_id));
662 run_onion_failure_test_with_fail_intercept("0-length channel update in intermediate node UPDATE onion failure",
663 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
664 msg.amount_msat -= 1;
666 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
667 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
668 let mut decoded_err_packet = msgs::DecodedOnionErrorPacket {
670 0x10, 0x7, // UPDATE|7
671 0x0, 0x0 // 0-len channel update
673 pad: vec![0; 255 - 4 /* 4-byte error message */],
676 let um = onion_utils::gen_um_from_shared_secret(&onion_keys[0].shared_secret.as_ref());
677 let mut hmac = HmacEngine::<Sha256>::new(&um);
678 hmac.input(&decoded_err_packet.encode()[32..]);
679 decoded_err_packet.hmac = Hmac::from_engine(hmac).to_byte_array();
680 msg.reason = onion_utils::encrypt_failure_packet(
681 &onion_keys[0].shared_secret.as_ref(), &decoded_err_packet.encode()[..])
682 }, || {}, true, Some(0x1000|7),
683 Some(NetworkUpdate::ChannelFailure {
684 short_channel_id: channels[1].0.contents.short_channel_id,
687 Some(channels[1].0.contents.short_channel_id));
688 run_onion_failure_test_with_fail_intercept("0-length channel update in final node UPDATE onion failure",
689 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
690 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
691 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
692 let mut decoded_err_packet = msgs::DecodedOnionErrorPacket {
694 0x10, 0x7, // UPDATE|7
695 0x0, 0x0 // 0-len channel update
697 pad: vec![0; 255 - 4 /* 4-byte error message */],
700 let um = onion_utils::gen_um_from_shared_secret(&onion_keys[1].shared_secret.as_ref());
701 let mut hmac = HmacEngine::<Sha256>::new(&um);
702 hmac.input(&decoded_err_packet.encode()[32..]);
703 decoded_err_packet.hmac = Hmac::from_engine(hmac).to_byte_array();
704 msg.reason = onion_utils::encrypt_failure_packet(
705 &onion_keys[1].shared_secret.as_ref(), &decoded_err_packet.encode()[..])
706 }, || nodes[2].node.fail_htlc_backwards(&payment_hash), true, Some(0x1000|7),
707 Some(NetworkUpdate::ChannelFailure {
708 short_channel_id: channels[1].0.contents.short_channel_id,
711 Some(channels[1].0.contents.short_channel_id));
715 fn test_overshoot_final_cltv() {
716 let chanmon_cfgs = create_chanmon_cfgs(3);
717 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
718 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None; 3]);
719 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
720 create_announced_chan_between_nodes(&nodes, 0, 1);
721 create_announced_chan_between_nodes(&nodes, 1, 2);
722 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 40000);
724 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
725 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id).unwrap();
727 check_added_monitors!(nodes[0], 1);
728 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
729 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
730 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
731 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
733 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
734 for (_, pending_forwards) in nodes[1].node.forward_htlcs.lock().unwrap().iter_mut() {
735 for f in pending_forwards.iter_mut() {
737 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) =>
738 forward_info.outgoing_cltv_value += 1,
743 expect_pending_htlcs_forwardable!(nodes[1]);
745 check_added_monitors!(&nodes[1], 1);
746 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
747 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
748 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
749 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
751 expect_pending_htlcs_forwardable!(nodes[2]);
752 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, 40_000);
753 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
756 fn do_test_onion_failure_stale_channel_update(announced_channel: bool) {
757 // Create a network of three nodes and two channels connecting them. We'll be updating the
758 // HTLC relay policy of the second channel, causing forwarding failures at the first hop.
759 let mut config = UserConfig::default();
760 config.channel_handshake_config.announced_channel = announced_channel;
761 config.channel_handshake_limits.force_announced_channel_preference = false;
762 config.accept_forwards_to_priv_channels = !announced_channel;
763 config.channel_config.max_dust_htlc_exposure = MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253);
764 let chanmon_cfgs = create_chanmon_cfgs(3);
765 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
768 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(config), None]);
769 let channel_manager_1_deserialized;
770 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
772 let other_channel = create_chan_between_nodes(
773 &nodes[0], &nodes[1],
775 let channel_to_update = if announced_channel {
776 let channel = create_announced_chan_between_nodes(
779 (channel.2, channel.0.contents.short_channel_id)
781 let channel = create_unannounced_chan_between_nodes_with_value(
782 &nodes, 1, 2, 100000, 10001,
784 (channel.0.channel_id, channel.0.short_channel_id_alias.unwrap())
786 let channel_to_update_counterparty = &nodes[2].node.get_our_node_id();
788 let default_config = ChannelConfig::default();
790 // A test payment should succeed as the ChannelConfig has not been changed yet.
791 const PAYMENT_AMT: u64 = 40000;
792 let (route, payment_hash, payment_preimage, payment_secret) = if announced_channel {
793 get_route_and_payment_hash!(nodes[0], nodes[2], PAYMENT_AMT)
795 let hop_hints = vec![RouteHint(vec![RouteHintHop {
796 src_node_id: nodes[1].node.get_our_node_id(),
797 short_channel_id: channel_to_update.1,
799 base_msat: default_config.forwarding_fee_base_msat,
800 proportional_millionths: default_config.forwarding_fee_proportional_millionths,
802 cltv_expiry_delta: default_config.cltv_expiry_delta,
803 htlc_maximum_msat: None,
804 htlc_minimum_msat: None,
806 let payment_params = PaymentParameters::from_node_id(*channel_to_update_counterparty, TEST_FINAL_CLTV)
807 .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap()
808 .with_route_hints(hop_hints).unwrap();
809 get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, PAYMENT_AMT)
811 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[2]]], PAYMENT_AMT,
812 payment_hash, payment_secret);
813 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
815 // Closure to force expiry of a channel's previous config.
816 let expire_prev_config = || {
817 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
818 nodes[1].node.timer_tick_occurred();
822 // Closure to update and retrieve the latest ChannelUpdate.
823 let update_and_get_channel_update = |config: &ChannelConfig, expect_new_update: bool,
824 prev_update: Option<&msgs::ChannelUpdate>, should_expire_prev_config: bool| -> Option<msgs::ChannelUpdate> {
825 nodes[1].node.update_channel_config(
826 channel_to_update_counterparty, &[channel_to_update.0], config,
828 let events = nodes[1].node.get_and_clear_pending_msg_events();
829 assert_eq!(events.len(), expect_new_update as usize);
830 if !expect_new_update {
833 let new_update = match &events[0] {
834 MessageSendEvent::BroadcastChannelUpdate { msg } => {
835 assert!(announced_channel);
838 MessageSendEvent::SendChannelUpdate { node_id, msg } => {
839 assert_eq!(node_id, channel_to_update_counterparty);
840 assert!(!announced_channel);
843 _ => panic!("expected Broadcast/SendChannelUpdate event"),
845 if prev_update.is_some() {
846 assert!(new_update.contents.timestamp > prev_update.unwrap().contents.timestamp)
848 if should_expire_prev_config {
849 expire_prev_config();
854 // We'll be attempting to route payments using the default ChannelUpdate for channels. This will
855 // lead to onion failures at the first hop once we update the ChannelConfig for the
857 let expect_onion_failure = |name: &str, error_code: u16| {
858 let short_channel_id = channel_to_update.1;
859 let network_update = NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: false };
860 run_onion_failure_test(
861 name, 0, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {}, true,
862 Some(error_code), Some(network_update), Some(short_channel_id),
866 // Updates to cltv_expiry_delta below MIN_CLTV_EXPIRY_DELTA should fail with APIMisuseError.
867 let mut invalid_config = default_config.clone();
868 invalid_config.cltv_expiry_delta = 0;
869 match nodes[1].node.update_channel_config(
870 channel_to_update_counterparty, &[channel_to_update.0], &invalid_config,
872 Err(APIError::APIMisuseError{ .. }) => {},
873 _ => panic!("unexpected result applying invalid cltv_expiry_delta"),
876 // Increase the base fee which should trigger a new ChannelUpdate.
877 let mut config = nodes[1].node.list_usable_channels().iter()
878 .find(|channel| channel.channel_id == channel_to_update.0).unwrap()
880 config.forwarding_fee_base_msat = u32::max_value();
881 let msg = update_and_get_channel_update(&config, true, None, false).unwrap();
883 // The old policy should still be in effect until a new block is connected.
884 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[2]]], PAYMENT_AMT,
885 payment_hash, payment_secret);
886 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
888 // Connect a block, which should expire the previous config, leading to a failure when
889 // forwarding the HTLC.
890 expire_prev_config();
891 expect_onion_failure("fee_insufficient", UPDATE|12);
893 // Redundant updates should not trigger a new ChannelUpdate.
894 assert!(update_and_get_channel_update(&config, false, None, false).is_none());
896 // Similarly, updates that do not have an affect on ChannelUpdate should not trigger a new one.
897 config.force_close_avoidance_max_fee_satoshis *= 2;
898 assert!(update_and_get_channel_update(&config, false, None, false).is_none());
900 // Reset the base fee to the default and increase the proportional fee which should trigger a
901 // new ChannelUpdate.
902 config.forwarding_fee_base_msat = default_config.forwarding_fee_base_msat;
903 config.cltv_expiry_delta = u16::max_value();
904 assert!(update_and_get_channel_update(&config, true, Some(&msg), true).is_some());
905 expect_onion_failure("incorrect_cltv_expiry", UPDATE|13);
907 // Reset the proportional fee and increase the CLTV expiry delta which should trigger a new
909 config.cltv_expiry_delta = default_config.cltv_expiry_delta;
910 config.forwarding_fee_proportional_millionths = u32::max_value();
911 assert!(update_and_get_channel_update(&config, true, Some(&msg), true).is_some());
912 expect_onion_failure("fee_insufficient", UPDATE|12);
914 // To test persistence of the updated config, we'll re-initialize the ChannelManager.
915 let config_after_restart = {
916 let chan_1_monitor_serialized = get_monitor!(nodes[1], other_channel.3).encode();
917 let chan_2_monitor_serialized = get_monitor!(nodes[1], channel_to_update.0).encode();
918 reload_node!(nodes[1], *nodes[1].node.get_current_default_configuration(), &nodes[1].node.encode(),
919 &[&chan_1_monitor_serialized, &chan_2_monitor_serialized], persister, chain_monitor, channel_manager_1_deserialized);
920 nodes[1].node.list_channels().iter()
921 .find(|channel| channel.channel_id == channel_to_update.0).unwrap()
924 assert_eq!(config, config_after_restart);
928 fn test_onion_failure_stale_channel_update() {
929 do_test_onion_failure_stale_channel_update(false);
930 do_test_onion_failure_stale_channel_update(true);
934 fn test_always_create_tlv_format_onion_payloads() {
935 // Verify that we always generate tlv onion format payloads, even if the features specifically
936 // specifies no support for variable length onions, as the legacy payload format has been
937 // deprecated in BOLT4.
938 let chanmon_cfgs = create_chanmon_cfgs(3);
939 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
941 // Set `node[1]`'s init features to features which return `false` for
942 // `supports_variable_length_onion()`
943 let mut no_variable_length_onion_features = InitFeatures::empty();
944 no_variable_length_onion_features.set_static_remote_key_required();
945 *node_cfgs[1].override_init_features.borrow_mut() = Some(no_variable_length_onion_features);
947 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
948 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
950 create_announced_chan_between_nodes(&nodes, 0, 1);
951 create_announced_chan_between_nodes(&nodes, 1, 2);
953 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
954 .with_bolt11_features(Bolt11InvoiceFeatures::empty()).unwrap();
955 let (route, _payment_hash, _payment_preimage, _payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, 40000);
957 let hops = &route.paths[0].hops;
958 // Asserts that the first hop to `node[1]` signals no support for variable length onions.
959 assert!(!hops[0].node_features.supports_variable_length_onion());
960 // Asserts that the first hop to `node[1]` signals no support for variable length onions.
961 assert!(!hops[1].node_features.supports_variable_length_onion());
963 let cur_height = nodes[0].best_block_info().1 + 1;
964 let recipient_onion_fields = RecipientOnionFields::spontaneous_empty();
965 let (onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(
966 &route.paths[0], 40000, &recipient_onion_fields, cur_height, &None).unwrap();
968 match onion_payloads[0] {
969 msgs::OutboundOnionPayload::Forward {..} => {},
971 "Should have generated a `msgs::OnionHopDataFormat::NonFinalNode` payload for `hops[0]`,
972 despite that the features signals no support for variable length onions"
975 match onion_payloads[1] {
976 msgs::OutboundOnionPayload::Receive {..} => {},
978 "Should have generated a `msgs::OnionHopDataFormat::FinalNode` payload for `hops[1]`,
979 despite that the features signals no support for variable length onions"
985 fn test_trampoline_onion_payload_serialization() {
986 // As per https://github.com/lightning/bolts/blob/c01d2e6267d4a8d1095f0f1188970055a9a22d29/bolt04/trampoline-payment-onion-test.json#L3
987 let trampoline_payload = OutboundTrampolinePayload::Forward {
988 amt_to_forward: 100000000,
989 outgoing_cltv_value: 800000,
990 outgoing_node_id: PublicKey::from_slice(&<Vec<u8>>::from_hex("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()).unwrap(),
993 let slice_to_hex = |slice: &[u8]| {
995 .map(|b| format!("{:02x}", b).to_string())
999 let carol_payload_hex = slice_to_hex(&trampoline_payload.encode());
1000 assert_eq!(carol_payload_hex, "2e020405f5e10004030c35000e2102edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145");
1003 fn do_test_fail_htlc_backwards_with_reason(failure_code: FailureCode) {
1005 let chanmon_cfgs = create_chanmon_cfgs(2);
1006 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1007 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1008 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1010 create_announced_chan_between_nodes(&nodes, 0, 1);
1012 let payment_amount = 100_000;
1013 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_amount);
1014 nodes[0].node.send_payment_with_route(&route, payment_hash,
1015 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1016 check_added_monitors!(nodes[0], 1);
1018 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1019 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
1020 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1021 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1023 expect_pending_htlcs_forwardable!(nodes[1]);
1024 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, payment_amount);
1025 nodes[1].node.fail_htlc_backwards_with_reason(&payment_hash, failure_code);
1027 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash }]);
1028 check_added_monitors!(nodes[1], 1);
1030 let events = nodes[1].node.get_and_clear_pending_msg_events();
1031 assert_eq!(events.len(), 1);
1032 let (update_fail_htlc, commitment_signed) = match events[0] {
1033 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 } } => {
1034 assert!(update_add_htlcs.is_empty());
1035 assert!(update_fulfill_htlcs.is_empty());
1036 assert_eq!(update_fail_htlcs.len(), 1);
1037 assert!(update_fail_malformed_htlcs.is_empty());
1038 assert!(update_fee.is_none());
1039 (update_fail_htlcs[0].clone(), commitment_signed)
1041 _ => panic!("Unexpected event"),
1044 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
1045 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
1047 let failure_data = match failure_code {
1048 FailureCode::TemporaryNodeFailure => vec![],
1049 FailureCode::RequiredNodeFeatureMissing => vec![],
1050 FailureCode::IncorrectOrUnknownPaymentDetails => {
1051 let mut htlc_msat_height_data = (payment_amount as u64).to_be_bytes().to_vec();
1052 htlc_msat_height_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
1053 htlc_msat_height_data
1055 FailureCode::InvalidOnionPayload(data) => {
1057 Some((typ, offset)) => [BigSize(typ).encode(), offset.encode()].concat(),
1063 let failure_code = failure_code.into();
1064 let permanent_flag = 0x4000;
1065 let permanent_fail = (failure_code & permanent_flag) != 0;
1066 expect_payment_failed!(nodes[0], payment_hash, permanent_fail, failure_code, failure_data);
1071 fn test_fail_htlc_backwards_with_reason() {
1072 do_test_fail_htlc_backwards_with_reason(FailureCode::TemporaryNodeFailure);
1073 do_test_fail_htlc_backwards_with_reason(FailureCode::RequiredNodeFeatureMissing);
1074 do_test_fail_htlc_backwards_with_reason(FailureCode::IncorrectOrUnknownPaymentDetails);
1075 do_test_fail_htlc_backwards_with_reason(FailureCode::InvalidOnionPayload(Some((1 << 16, 42))));
1076 do_test_fail_htlc_backwards_with_reason(FailureCode::InvalidOnionPayload(None));
1079 macro_rules! get_phantom_route {
1080 ($nodes: expr, $amt: expr, $channel: expr) => {{
1081 let phantom_pubkey = $nodes[1].keys_manager.get_node_id(Recipient::PhantomNode).unwrap();
1082 let phantom_route_hint = $nodes[1].node.get_phantom_route_hints();
1083 let payment_params = PaymentParameters::from_node_id(phantom_pubkey, TEST_FINAL_CLTV)
1084 .with_bolt11_features($nodes[1].node.bolt11_invoice_features()).unwrap()
1085 .with_route_hints(vec![RouteHint(vec![
1087 src_node_id: $nodes[0].node.get_our_node_id(),
1088 short_channel_id: $channel.0.contents.short_channel_id,
1090 base_msat: $channel.0.contents.fee_base_msat,
1091 proportional_millionths: $channel.0.contents.fee_proportional_millionths,
1093 cltv_expiry_delta: $channel.0.contents.cltv_expiry_delta,
1094 htlc_minimum_msat: None,
1095 htlc_maximum_msat: None,
1098 src_node_id: phantom_route_hint.real_node_pubkey,
1099 short_channel_id: phantom_route_hint.phantom_scid,
1102 proportional_millionths: 0,
1104 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1105 htlc_minimum_msat: None,
1106 htlc_maximum_msat: None,
1109 let scorer = test_utils::TestScorer::new();
1110 let network_graph = $nodes[0].network_graph.read_only();
1111 let route_params = RouteParameters::from_payment_params_and_value(payment_params, $amt);
1113 &$nodes[0].node.get_our_node_id(), &route_params, &network_graph,
1114 Some(&$nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
1115 $nodes[0].logger, &scorer, &Default::default(), &[0u8; 32]
1116 ).unwrap(), phantom_route_hint.phantom_scid)
1121 fn test_phantom_onion_hmac_failure() {
1122 let chanmon_cfgs = create_chanmon_cfgs(2);
1123 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1124 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1125 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1127 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1130 let recv_value_msat = 10_000;
1131 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
1132 let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
1134 // Route the HTLC through to the destination.
1135 nodes[0].node.send_payment_with_route(&route, payment_hash,
1136 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1137 check_added_monitors!(nodes[0], 1);
1138 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1139 let mut update_add = update_0.update_add_htlcs[0].clone();
1141 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1142 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1144 // Modify the payload so the phantom hop's HMAC is bogus.
1145 let sha256_of_onion = {
1146 let mut forward_htlcs = nodes[1].node.forward_htlcs.lock().unwrap();
1147 let mut pending_forward = forward_htlcs.get_mut(&phantom_scid).unwrap();
1148 match pending_forward[0] {
1149 HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
1150 forward_info: PendingHTLCInfo {
1151 routing: PendingHTLCRouting::Forward { ref mut onion_packet, .. },
1155 onion_packet.hmac[onion_packet.hmac.len() - 1] ^= 1;
1156 Sha256::hash(&onion_packet.hop_data).to_byte_array().to_vec()
1158 _ => panic!("Unexpected forward"),
1161 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1162 nodes[1].node.process_pending_htlc_forwards();
1163 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1164 nodes[1].node.process_pending_htlc_forwards();
1165 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1166 check_added_monitors!(&nodes[1], 1);
1167 assert!(update_1.update_fail_htlcs.len() == 1);
1168 let fail_msg = update_1.update_fail_htlcs[0].clone();
1169 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1170 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1172 // Ensure the payment fails with the expected error.
1173 let mut fail_conditions = PaymentFailedConditions::new()
1174 .blamed_scid(phantom_scid)
1175 .blamed_chan_closed(true)
1176 .expected_htlc_error_data(0x8000 | 0x4000 | 5, &sha256_of_onion);
1177 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1181 fn test_phantom_invalid_onion_payload() {
1182 let chanmon_cfgs = create_chanmon_cfgs(2);
1183 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1184 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1185 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1187 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1190 let recv_value_msat = 10_000;
1191 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
1192 let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
1194 // We'll use the session priv later when constructing an invalid onion packet.
1195 let session_priv = [3; 32];
1196 *nodes[0].keys_manager.override_random_bytes.lock().unwrap() = Some(session_priv);
1197 nodes[0].node.send_payment_with_route(&route, payment_hash,
1198 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1199 check_added_monitors!(nodes[0], 1);
1200 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1201 let mut update_add = update_0.update_add_htlcs[0].clone();
1203 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1204 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1206 // Modify the onion packet to have an invalid payment amount.
1207 for (_, pending_forwards) in nodes[1].node.forward_htlcs.lock().unwrap().iter_mut() {
1208 for f in pending_forwards.iter_mut() {
1210 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
1211 forward_info: PendingHTLCInfo {
1212 routing: PendingHTLCRouting::Forward { ref mut onion_packet, .. },
1216 // Construct the onion payloads for the entire route and an invalid amount.
1217 let height = nodes[0].best_block_info().1;
1218 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
1219 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
1220 let recipient_onion_fields = RecipientOnionFields::secret_only(payment_secret);
1221 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(
1222 &route.paths[0], msgs::MAX_VALUE_MSAT + 1,
1223 &recipient_onion_fields, height + 1, &None).unwrap();
1224 // We only want to construct the onion packet for the last hop, not the entire route, so
1225 // remove the first hop's payload and its keys.
1226 onion_keys.remove(0);
1227 onion_payloads.remove(0);
1229 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1230 onion_packet.hop_data = new_onion_packet.hop_data;
1231 onion_packet.hmac = new_onion_packet.hmac;
1233 _ => panic!("Unexpected forward"),
1237 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1238 nodes[1].node.process_pending_htlc_forwards();
1239 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1240 nodes[1].node.process_pending_htlc_forwards();
1241 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1242 check_added_monitors!(&nodes[1], 1);
1243 assert!(update_1.update_fail_htlcs.len() == 1);
1244 let fail_msg = update_1.update_fail_htlcs[0].clone();
1245 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1246 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1248 // Ensure the payment fails with the expected error.
1249 let error_data = Vec::new();
1250 let mut fail_conditions = PaymentFailedConditions::new()
1251 .blamed_scid(phantom_scid)
1252 .blamed_chan_closed(true)
1253 .expected_htlc_error_data(0x4000 | 22, &error_data);
1254 expect_payment_failed_conditions(&nodes[0], payment_hash, true, fail_conditions);
1258 fn test_phantom_final_incorrect_cltv_expiry() {
1259 let chanmon_cfgs = create_chanmon_cfgs(2);
1260 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1261 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1262 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1264 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1267 let recv_value_msat = 10_000;
1268 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
1269 let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
1271 // Route the HTLC through to the destination.
1272 nodes[0].node.send_payment_with_route(&route, payment_hash,
1273 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1274 check_added_monitors!(nodes[0], 1);
1275 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1276 let mut update_add = update_0.update_add_htlcs[0].clone();
1278 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1279 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1281 // Modify the payload so the phantom hop's HMAC is bogus.
1282 for (_, pending_forwards) in nodes[1].node.forward_htlcs.lock().unwrap().iter_mut() {
1283 for f in pending_forwards.iter_mut() {
1285 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
1286 forward_info: PendingHTLCInfo { ref mut outgoing_cltv_value, .. }, ..
1288 *outgoing_cltv_value -= 1;
1290 _ => panic!("Unexpected forward"),
1294 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1295 nodes[1].node.process_pending_htlc_forwards();
1296 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1297 nodes[1].node.process_pending_htlc_forwards();
1298 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1299 check_added_monitors!(&nodes[1], 1);
1300 assert!(update_1.update_fail_htlcs.len() == 1);
1301 let fail_msg = update_1.update_fail_htlcs[0].clone();
1302 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1303 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1305 // Ensure the payment fails with the expected error.
1306 let expected_cltv: u32 = 80;
1307 let error_data = expected_cltv.to_be_bytes().to_vec();
1308 let mut fail_conditions = PaymentFailedConditions::new()
1309 .blamed_scid(phantom_scid)
1310 .expected_htlc_error_data(18, &error_data);
1311 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1315 fn test_phantom_failure_too_low_cltv() {
1316 let chanmon_cfgs = create_chanmon_cfgs(2);
1317 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1318 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1319 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1321 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1324 let recv_value_msat = 10_000;
1325 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
1326 let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
1328 // Modify the route to have a too-low cltv.
1329 route.paths[0].hops[1].cltv_expiry_delta = 5;
1331 // Route the HTLC through to the destination.
1332 nodes[0].node.send_payment_with_route(&route, payment_hash,
1333 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1334 check_added_monitors!(nodes[0], 1);
1335 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1336 let mut update_add = update_0.update_add_htlcs[0].clone();
1338 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1339 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1341 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1342 nodes[1].node.process_pending_htlc_forwards();
1343 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1344 nodes[1].node.process_pending_htlc_forwards();
1345 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1346 check_added_monitors!(&nodes[1], 1);
1347 assert!(update_1.update_fail_htlcs.len() == 1);
1348 let fail_msg = update_1.update_fail_htlcs[0].clone();
1349 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1350 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1352 // Ensure the payment fails with the expected error.
1353 let mut error_data = recv_value_msat.to_be_bytes().to_vec();
1354 error_data.extend_from_slice(
1355 &nodes[0].node.best_block.read().unwrap().height.to_be_bytes(),
1357 let mut fail_conditions = PaymentFailedConditions::new()
1358 .blamed_scid(phantom_scid)
1359 .expected_htlc_error_data(0x4000 | 15, &error_data);
1360 expect_payment_failed_conditions(&nodes[0], payment_hash, true, fail_conditions);
1364 fn test_phantom_failure_modified_cltv() {
1365 // Test that we fail back phantoms if the upstream node fiddled with the CLTV too much with the
1366 // correct error code.
1367 let chanmon_cfgs = create_chanmon_cfgs(2);
1368 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1369 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1370 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1372 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1375 let recv_value_msat = 10_000;
1376 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
1377 let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
1379 // Route the HTLC through to the destination.
1380 nodes[0].node.send_payment_with_route(&route, payment_hash,
1381 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1382 check_added_monitors!(nodes[0], 1);
1383 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1384 let mut update_add = update_0.update_add_htlcs[0].clone();
1386 // Modify the route to have a too-low cltv.
1387 update_add.cltv_expiry -= 10;
1389 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1390 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1392 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1393 assert!(update_1.update_fail_htlcs.len() == 1);
1394 let fail_msg = update_1.update_fail_htlcs[0].clone();
1395 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1396 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1398 // Ensure the payment fails with the expected error.
1399 let mut fail_conditions = PaymentFailedConditions::new()
1400 .blamed_scid(phantom_scid)
1401 .expected_htlc_error_data(0x2000 | 2, &[]);
1402 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1406 fn test_phantom_failure_expires_too_soon() {
1407 // Test that we fail back phantoms if the HTLC got delayed and we got blocks in between with
1408 // the correct error code.
1409 let chanmon_cfgs = create_chanmon_cfgs(2);
1410 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1411 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1412 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1414 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1417 let recv_value_msat = 10_000;
1418 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
1419 let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
1421 // Route the HTLC through to the destination.
1422 nodes[0].node.send_payment_with_route(&route, payment_hash,
1423 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1424 check_added_monitors!(nodes[0], 1);
1425 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1426 let mut update_add = update_0.update_add_htlcs[0].clone();
1428 connect_blocks(&nodes[1], CLTV_FAR_FAR_AWAY);
1429 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1430 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1432 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1433 assert!(update_1.update_fail_htlcs.len() == 1);
1434 let fail_msg = update_1.update_fail_htlcs[0].clone();
1435 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1436 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1438 // Ensure the payment fails with the expected error.
1439 let mut fail_conditions = PaymentFailedConditions::new()
1440 .blamed_scid(phantom_scid)
1441 .expected_htlc_error_data(0x2000 | 2, &[]);
1442 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1446 fn test_phantom_failure_too_low_recv_amt() {
1447 let chanmon_cfgs = create_chanmon_cfgs(2);
1448 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1449 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1450 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1452 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1454 // Get the route with a too-low amount.
1455 let recv_amt_msat = 10_000;
1456 let bad_recv_amt_msat = recv_amt_msat - 10;
1457 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_amt_msat));
1458 let (mut route, phantom_scid) = get_phantom_route!(nodes, bad_recv_amt_msat, channel);
1460 // Route the HTLC through to the destination.
1461 nodes[0].node.send_payment_with_route(&route, payment_hash,
1462 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1463 check_added_monitors!(nodes[0], 1);
1464 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1465 let mut update_add = update_0.update_add_htlcs[0].clone();
1467 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1468 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1470 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1471 nodes[1].node.process_pending_htlc_forwards();
1472 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1473 nodes[1].node.process_pending_htlc_forwards();
1474 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
1475 nodes[1].node.process_pending_htlc_forwards();
1476 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1477 check_added_monitors!(&nodes[1], 1);
1478 assert!(update_1.update_fail_htlcs.len() == 1);
1479 let fail_msg = update_1.update_fail_htlcs[0].clone();
1480 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1481 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1483 // Ensure the payment fails with the expected error.
1484 let mut error_data = bad_recv_amt_msat.to_be_bytes().to_vec();
1485 error_data.extend_from_slice(&nodes[1].node.best_block.read().unwrap().height.to_be_bytes());
1486 let mut fail_conditions = PaymentFailedConditions::new()
1487 .blamed_scid(phantom_scid)
1488 .expected_htlc_error_data(0x4000 | 15, &error_data);
1489 expect_payment_failed_conditions(&nodes[0], payment_hash, true, fail_conditions);
1493 fn test_phantom_dust_exposure_failure() {
1494 do_test_phantom_dust_exposure_failure(false);
1495 do_test_phantom_dust_exposure_failure(true);
1498 fn do_test_phantom_dust_exposure_failure(multiplier_dust_limit: bool) {
1499 // Set the max dust exposure to the dust limit.
1500 let max_dust_exposure = 546;
1501 let mut receiver_config = UserConfig::default();
1502 // Default test fee estimator rate is 253, so to set the max dust exposure to the dust limit,
1503 // we need to set the multiplier to 2.
1504 receiver_config.channel_config.max_dust_htlc_exposure =
1505 if multiplier_dust_limit { MaxDustHTLCExposure::FeeRateMultiplier(2) }
1506 else { MaxDustHTLCExposure::FixedLimitMsat(max_dust_exposure) };
1507 receiver_config.channel_handshake_config.announced_channel = true;
1509 let chanmon_cfgs = create_chanmon_cfgs(2);
1510 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1511 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(receiver_config)]);
1512 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1514 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1516 // Get the route with an amount exceeding the dust exposure threshold of nodes[1].
1517 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(max_dust_exposure + 1));
1518 let (mut route, _) = get_phantom_route!(nodes, max_dust_exposure + 1, channel);
1520 // Route the HTLC through to the destination.
1521 nodes[0].node.send_payment_with_route(&route, payment_hash,
1522 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1523 check_added_monitors!(nodes[0], 1);
1524 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1525 let mut update_add = update_0.update_add_htlcs[0].clone();
1527 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1528 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1530 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1531 assert!(update_1.update_fail_htlcs.len() == 1);
1532 let fail_msg = update_1.update_fail_htlcs[0].clone();
1533 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1534 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1536 // Ensure the payment fails with the expected error.
1537 let mut err_data = Vec::new();
1538 err_data.extend_from_slice(&(channel.1.serialized_length() as u16 + 2).to_be_bytes());
1539 err_data.extend_from_slice(&ChannelUpdate::TYPE.to_be_bytes());
1540 err_data.extend_from_slice(&channel.1.encode());
1542 let mut fail_conditions = PaymentFailedConditions::new()
1543 .blamed_scid(route.paths[0].hops.last().as_ref().unwrap().short_channel_id)
1544 .blamed_chan_closed(false)
1545 .expected_htlc_error_data(0x1000 | 7, &err_data);
1546 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1550 fn test_phantom_failure_reject_payment() {
1551 // Test that the user can successfully fail back a phantom node payment.
1552 let chanmon_cfgs = create_chanmon_cfgs(2);
1553 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1554 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1555 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1557 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1559 // Get the route with a too-low amount.
1560 let recv_amt_msat = 10_000;
1561 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_amt_msat));
1562 let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_amt_msat, channel);
1564 // Route the HTLC through to the destination.
1565 nodes[0].node.send_payment_with_route(&route, payment_hash,
1566 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1567 check_added_monitors!(nodes[0], 1);
1568 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1569 let mut update_add = update_0.update_add_htlcs[0].clone();
1571 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1572 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1574 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1575 nodes[1].node.process_pending_htlc_forwards();
1576 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1577 nodes[1].node.process_pending_htlc_forwards();
1578 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_amt_msat, None, route.paths[0].hops.last().unwrap().pubkey);
1579 nodes[1].node.fail_htlc_backwards(&payment_hash);
1580 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1581 nodes[1].node.process_pending_htlc_forwards();
1583 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1584 check_added_monitors!(&nodes[1], 1);
1585 assert!(update_1.update_fail_htlcs.len() == 1);
1586 let fail_msg = update_1.update_fail_htlcs[0].clone();
1587 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1588 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1590 // Ensure the payment fails with the expected error.
1591 let mut error_data = recv_amt_msat.to_be_bytes().to_vec();
1592 error_data.extend_from_slice(&nodes[1].node.best_block.read().unwrap().height.to_be_bytes());
1593 let mut fail_conditions = PaymentFailedConditions::new()
1594 .blamed_scid(phantom_scid)
1595 .expected_htlc_error_data(0x4000 | 15, &error_data);
1596 expect_payment_failed_conditions(&nodes[0], payment_hash, true, fail_conditions);