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::ChannelUpdateMessage { .. } => {
184 if let NetworkUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
185 panic!("channel_update not found!");
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);
193 panic!("Unexpected message event");
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);
201 panic!("Unexpected message event");
205 None => panic!("Expected channel update"),
208 assert!(network_update.is_none());
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"),
216 assert!(short_channel_id.is_none());
219 panic!("Unexpected event");
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
228 PaymentFailureReason::RecipientRejected
229 }, ev_reason.unwrap());
231 _ => panic!("Unexpected second event"),
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()),
247 cltv_expiry_delta: 0,
248 htlc_minimum_msat: 0,
249 htlc_maximum_msat: msgs::MAX_VALUE_MSAT,
251 fee_proportional_millionths: 0,
258 struct BogusOnionHopData {
261 impl BogusOnionHopData {
262 fn new(orig: msgs::OutboundOnionPayload) -> Self {
263 Self { data: orig.encode() }
266 impl Writeable for BogusOnionHopData {
267 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
268 writer.write_all(&self.data[..])
272 const BADONION: u16 = 0x8000;
273 const PERM: u16 = 0x4000;
274 const NODE: u16 = 0x2000;
275 const UPDATE: u16 = 0x1000;
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
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;
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)];
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);
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. However,
304 // because we ignore channel update contents, we will still blame the 2nd channel.
305 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
306 let short_channel_id = channels[1].0.contents.short_channel_id;
307 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
308 msg.amount_msat -= 1;
309 }, || {}, true, Some(UPDATE|12), Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: false}), Some(short_channel_id));
311 // In an earlier version, we spuriously failed to forward payments if the expected feerate
312 // changed between the channel open and the payment.
314 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
318 let (payment_preimage_success, payment_hash_success, payment_secret_success) = get_payment_preimage_hash!(nodes[2]);
319 nodes[0].node.send_payment_with_route(&route, payment_hash_success,
320 RecipientOnionFields::secret_only(payment_secret_success), PaymentId(payment_hash_success.0)).unwrap();
321 check_added_monitors!(nodes[0], 1);
322 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 40_000, payment_hash_success, payment_secret_success);
323 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_success);
327 fn test_onion_failure() {
328 // When we check for amount_below_minimum below, we want to test that we're using the *right*
329 // amount, thus we need different htlc_minimum_msat values. We set node[2]'s htlc_minimum_msat
330 // to 2000, which is above the default value of 1000 set in create_node_chanmgrs.
331 // This exposed a previous bug because we were using the wrong value all the way down in
332 // Channel::get_counterparty_htlc_minimum_msat().
333 let mut node_2_cfg: UserConfig = test_default_channel_config();
334 node_2_cfg.channel_handshake_config.our_htlc_minimum_msat = 2000;
335 node_2_cfg.channel_handshake_config.announced_channel = true;
336 node_2_cfg.channel_handshake_limits.force_announced_channel_preference = false;
338 // When this test was written, the default base fee floated based on the HTLC count.
339 // It is now fixed, so we simply set the fee to the expected value here.
340 let mut config = test_default_channel_config();
341 config.channel_config.forwarding_fee_base_msat = 196;
343 let chanmon_cfgs = create_chanmon_cfgs(3);
344 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
345 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config), Some(config), Some(node_2_cfg)]);
346 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
347 let channels = [create_announced_chan_between_nodes(&nodes, 0, 1), create_announced_chan_between_nodes(&nodes, 1, 2)];
348 for node in nodes.iter() {
349 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([3; 32]);
351 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 40000);
353 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000);
355 // intermediate node failure
356 let short_channel_id = channels[1].0.contents.short_channel_id;
357 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
358 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
359 let cur_height = nodes[0].best_block_info().1 + 1;
360 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
361 let recipient_onion_fields = RecipientOnionFields::spontaneous_empty();
362 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(
363 &route.paths[0], 40000, &recipient_onion_fields, cur_height, &None).unwrap();
364 let mut new_payloads = Vec::new();
365 for payload in onion_payloads.drain(..) {
366 new_payloads.push(BogusOnionHopData::new(payload));
368 // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
369 // describing a length-1 TLV payload, which is obviously bogus.
370 new_payloads[0].data[0] = 1;
371 msg.onion_routing_packet = onion_utils::construct_onion_packet_with_writable_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
372 }, ||{}, true, Some(PERM|22), Some(NetworkUpdate::ChannelFailure{short_channel_id, is_permanent: true}), Some(short_channel_id));
374 // final node failure
375 let short_channel_id = channels[1].0.contents.short_channel_id;
376 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, &payment_secret, |msg| {
377 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
378 let cur_height = nodes[0].best_block_info().1 + 1;
379 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
380 let recipient_onion_fields = RecipientOnionFields::spontaneous_empty();
381 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(
382 &route.paths[0], 40000, &recipient_onion_fields, cur_height, &None).unwrap();
383 let mut new_payloads = Vec::new();
384 for payload in onion_payloads.drain(..) {
385 new_payloads.push(BogusOnionHopData::new(payload));
387 // break the last-hop payload by swapping the realm (0) byte for a byte describing a
388 // length-1 TLV payload, which is obviously bogus.
389 new_payloads[1].data[0] = 1;
390 msg.onion_routing_packet = onion_utils::construct_onion_packet_with_writable_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
391 }, ||{}, false, Some(PERM|22), Some(NetworkUpdate::ChannelFailure{short_channel_id, is_permanent: true}), Some(short_channel_id));
393 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
394 // receiving simulated fail messages
395 // intermediate node failure
396 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
398 msg.amount_msat -= 1;
400 // and tamper returning error message
401 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
402 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
403 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), NODE|2, &[0;0]);
404 }, ||{}, 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));
406 // final node failure
407 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
408 // and tamper returning error message
409 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
410 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
411 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[1].shared_secret.as_ref(), NODE|2, &[0;0]);
413 nodes[2].node.fail_htlc_backwards(&payment_hash);
414 }, 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));
415 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
417 // intermediate node failure
418 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
419 msg.amount_msat -= 1;
421 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
422 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
423 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), PERM|NODE|2, &[0;0]);
424 }, ||{}, 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));
426 // final node failure
427 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
428 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
429 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
430 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[1].shared_secret.as_ref(), PERM|NODE|2, &[0;0]);
432 nodes[2].node.fail_htlc_backwards(&payment_hash);
433 }, 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));
434 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
436 // intermediate node failure
437 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
438 msg.amount_msat -= 1;
440 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
441 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
442 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), PERM|NODE|3, &[0;0]);
444 nodes[2].node.fail_htlc_backwards(&payment_hash);
445 }, 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));
447 // final node failure
448 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
449 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
450 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
451 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[1].shared_secret.as_ref(), PERM|NODE|3, &[0;0]);
453 nodes[2].node.fail_htlc_backwards(&payment_hash);
454 }, 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));
455 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
457 // Our immediate peer sent UpdateFailMalformedHTLC because it couldn't understand the onion in
458 // the UpdateAddHTLC that we sent.
459 let short_channel_id = channels[0].0.contents.short_channel_id;
460 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
461 Some(BADONION|PERM|4), None, Some(short_channel_id));
463 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
464 Some(BADONION|PERM|5), None, Some(short_channel_id));
466 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,
467 Some(BADONION|PERM|6), None, Some(short_channel_id));
469 let short_channel_id = channels[1].0.contents.short_channel_id;
470 let chan_update = ChannelUpdate::dummy(short_channel_id);
472 let mut err_data = Vec::new();
473 err_data.extend_from_slice(&(chan_update.serialized_length() as u16 + 2).to_be_bytes());
474 err_data.extend_from_slice(&ChannelUpdate::TYPE.to_be_bytes());
475 err_data.extend_from_slice(&chan_update.encode());
476 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
477 msg.amount_msat -= 1;
479 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
480 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
481 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), UPDATE|7, &err_data);
482 }, ||{}, true, Some(UPDATE|7),
483 Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: false }),
484 Some(short_channel_id));
486 // Check we can still handle onion failures that include channel updates without a type prefix
487 let err_data_without_type = chan_update.encode_with_len();
488 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
489 msg.amount_msat -= 1;
491 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
492 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
493 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), UPDATE|7, &err_data_without_type);
494 }, ||{}, true, Some(UPDATE|7),
495 Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: false }),
496 Some(short_channel_id));
498 let short_channel_id = channels[1].0.contents.short_channel_id;
499 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
500 msg.amount_msat -= 1;
502 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
503 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
504 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), PERM|8, &[0;0]);
505 // short_channel_id from the processing node
506 }, ||{}, true, Some(PERM|8), Some(NetworkUpdate::ChannelFailure{short_channel_id, is_permanent: true}), Some(short_channel_id));
508 let short_channel_id = channels[1].0.contents.short_channel_id;
509 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
510 msg.amount_msat -= 1;
512 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
513 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
514 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), PERM|9, &[0;0]);
515 // short_channel_id from the processing node
516 }, ||{}, true, Some(PERM|9), Some(NetworkUpdate::ChannelFailure{short_channel_id, is_permanent: true}), Some(short_channel_id));
518 let mut bogus_route = route.clone();
519 bogus_route.paths[0].hops[1].short_channel_id -= 1;
520 let short_channel_id = bogus_route.paths[0].hops[1].short_channel_id;
521 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, &payment_secret, |_| {}, ||{}, true, Some(PERM|10),
522 Some(NetworkUpdate::ChannelFailure{short_channel_id, is_permanent:true}), Some(short_channel_id));
524 let short_channel_id = channels[1].0.contents.short_channel_id;
525 let amt_to_forward = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
526 .unwrap().lock().unwrap().channel_by_id.get(&channels[1].2).unwrap()
527 .context().get_counterparty_htlc_minimum_msat() - 1;
528 let mut bogus_route = route.clone();
529 let route_len = bogus_route.paths[0].hops.len();
530 bogus_route.paths[0].hops[route_len-1].fee_msat = amt_to_forward;
531 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, &payment_secret, |_| {}, ||{}, true, Some(UPDATE|11),
532 Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: false }),
533 Some(short_channel_id));
535 // Clear pending payments so that the following positive test has the correct payment hash.
536 for node in nodes.iter() {
537 node.node.clear_pending_payments();
540 // Test a positive test-case with one extra msat, meeting the minimum.
541 bogus_route.paths[0].hops[route_len-1].fee_msat = amt_to_forward + 1;
542 let preimage = send_along_route(&nodes[0], bogus_route, &[&nodes[1], &nodes[2]], amt_to_forward+1).0;
543 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], preimage);
545 // We ignore channel update contents in onion errors, so will blame the 2nd channel even though
546 // the first node is the one that messed up.
547 let short_channel_id = channels[1].0.contents.short_channel_id;
548 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
549 msg.amount_msat -= 1;
550 }, || {}, true, Some(UPDATE|12), Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: false}), Some(short_channel_id));
552 let short_channel_id = channels[1].0.contents.short_channel_id;
553 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
554 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
555 msg.cltv_expiry -= 1;
556 }, || {}, true, Some(UPDATE|13), Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: false}), Some(short_channel_id));
558 let short_channel_id = channels[1].0.contents.short_channel_id;
559 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
560 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
561 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
562 connect_blocks(&nodes[1], height - nodes[1].best_block_info().1);
563 connect_blocks(&nodes[2], height - nodes[2].best_block_info().1);
564 }, ||{}, true, Some(UPDATE|14),
565 Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: false }),
566 Some(short_channel_id));
568 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
569 nodes[2].node.fail_htlc_backwards(&payment_hash);
570 }, false, Some(PERM|15), None, None);
571 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
573 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, &payment_secret, |msg| {
574 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
575 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
576 connect_blocks(&nodes[1], height - nodes[1].best_block_info().1);
577 connect_blocks(&nodes[2], height - nodes[2].best_block_info().1);
578 }, || {}, false, Some(0x4000 | 15), None, None);
580 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
581 for (_, pending_forwards) in nodes[1].node.forward_htlcs.lock().unwrap().iter_mut() {
582 for f in pending_forwards.iter_mut() {
584 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) =>
585 forward_info.outgoing_cltv_value -= 1,
590 }, true, Some(18), None, Some(channels[1].0.contents.short_channel_id));
592 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
593 // violate amt_to_forward > msg.amount_msat
594 for (_, pending_forwards) in nodes[1].node.forward_htlcs.lock().unwrap().iter_mut() {
595 for f in pending_forwards.iter_mut() {
597 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) =>
598 forward_info.outgoing_amt_msat -= 1,
603 }, true, Some(19), None, Some(channels[1].0.contents.short_channel_id));
605 let short_channel_id = channels[1].0.contents.short_channel_id;
606 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
607 // disconnect event to the channel between nodes[1] ~ nodes[2]
608 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
609 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
610 }, true, Some(UPDATE|7),
611 Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: false }),
612 Some(short_channel_id));
613 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
614 // disconnect event to the channel between nodes[1] ~ nodes[2]
615 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
616 nodes[1].node.timer_tick_occurred();
617 nodes[2].node.timer_tick_occurred();
619 nodes[1].node.get_and_clear_pending_msg_events();
620 nodes[2].node.get_and_clear_pending_msg_events();
621 }, true, Some(UPDATE|20),
622 Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: false }),
623 Some(short_channel_id));
624 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[2]));
626 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
627 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
628 let mut route = route.clone();
629 let height = nodes[2].best_block_info().1;
630 route.paths[0].hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.paths[0].hops[0].cltv_expiry_delta + 1;
631 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
632 let recipient_onion_fields = RecipientOnionFields::spontaneous_empty();
633 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(
634 &route.paths[0], 40000, &recipient_onion_fields, height, &None).unwrap();
635 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
636 msg.cltv_expiry = htlc_cltv;
637 msg.onion_routing_packet = onion_packet;
638 }, ||{}, 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));
640 run_onion_failure_test_with_fail_intercept("mpp_timeout", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
641 // Tamper returning error message
642 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
643 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
644 msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[1].shared_secret.as_ref(), 23, &[0;0]);
646 nodes[2].node.fail_htlc_backwards(&payment_hash);
647 }, true, Some(23), None, None);
649 run_onion_failure_test_with_fail_intercept("bogus err packet with valid hmac", 200, &nodes,
650 &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
651 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
652 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
653 let mut decoded_err_packet = msgs::DecodedOnionErrorPacket {
658 let um = onion_utils::gen_um_from_shared_secret(&onion_keys[1].shared_secret.as_ref());
659 let mut hmac = HmacEngine::<Sha256>::new(&um);
660 hmac.input(&decoded_err_packet.encode()[32..]);
661 decoded_err_packet.hmac = Hmac::from_engine(hmac).to_byte_array();
662 msg.reason = onion_utils::encrypt_failure_packet(
663 &onion_keys[1].shared_secret.as_ref(), &decoded_err_packet.encode()[..])
664 }, || nodes[2].node.fail_htlc_backwards(&payment_hash), false, None,
665 Some(NetworkUpdate::NodeFailure { node_id: route.paths[0].hops[1].pubkey, is_permanent: true }),
666 Some(channels[1].0.contents.short_channel_id));
667 run_onion_failure_test_with_fail_intercept("0-length channel update in intermediate node UPDATE onion failure",
668 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
669 msg.amount_msat -= 1;
671 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
672 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
673 let mut decoded_err_packet = msgs::DecodedOnionErrorPacket {
675 0x10, 0x7, // UPDATE|7
676 0x0, 0x0 // 0-len channel update
678 pad: vec![0; 255 - 4 /* 4-byte error message */],
681 let um = onion_utils::gen_um_from_shared_secret(&onion_keys[0].shared_secret.as_ref());
682 let mut hmac = HmacEngine::<Sha256>::new(&um);
683 hmac.input(&decoded_err_packet.encode()[32..]);
684 decoded_err_packet.hmac = Hmac::from_engine(hmac).to_byte_array();
685 msg.reason = onion_utils::encrypt_failure_packet(
686 &onion_keys[0].shared_secret.as_ref(), &decoded_err_packet.encode()[..])
687 }, || {}, true, Some(0x1000|7),
688 Some(NetworkUpdate::ChannelFailure {
689 short_channel_id: channels[1].0.contents.short_channel_id,
692 Some(channels[1].0.contents.short_channel_id));
693 run_onion_failure_test_with_fail_intercept("0-length channel update in final node UPDATE onion failure",
694 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
695 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
696 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
697 let mut decoded_err_packet = msgs::DecodedOnionErrorPacket {
699 0x10, 0x7, // UPDATE|7
700 0x0, 0x0 // 0-len channel update
702 pad: vec![0; 255 - 4 /* 4-byte error message */],
705 let um = onion_utils::gen_um_from_shared_secret(&onion_keys[1].shared_secret.as_ref());
706 let mut hmac = HmacEngine::<Sha256>::new(&um);
707 hmac.input(&decoded_err_packet.encode()[32..]);
708 decoded_err_packet.hmac = Hmac::from_engine(hmac).to_byte_array();
709 msg.reason = onion_utils::encrypt_failure_packet(
710 &onion_keys[1].shared_secret.as_ref(), &decoded_err_packet.encode()[..])
711 }, || nodes[2].node.fail_htlc_backwards(&payment_hash), true, Some(0x1000|7),
712 Some(NetworkUpdate::ChannelFailure {
713 short_channel_id: channels[1].0.contents.short_channel_id,
716 Some(channels[1].0.contents.short_channel_id));
720 fn test_overshoot_final_cltv() {
721 let chanmon_cfgs = create_chanmon_cfgs(3);
722 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
723 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None; 3]);
724 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
725 create_announced_chan_between_nodes(&nodes, 0, 1);
726 create_announced_chan_between_nodes(&nodes, 1, 2);
727 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 40000);
729 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
730 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id).unwrap();
732 check_added_monitors!(nodes[0], 1);
733 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
734 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
735 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
736 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
738 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
739 for (_, pending_forwards) in nodes[1].node.forward_htlcs.lock().unwrap().iter_mut() {
740 for f in pending_forwards.iter_mut() {
742 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) =>
743 forward_info.outgoing_cltv_value += 1,
748 expect_pending_htlcs_forwardable!(nodes[1]);
750 check_added_monitors!(&nodes[1], 1);
751 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
752 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
753 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
754 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
756 expect_pending_htlcs_forwardable!(nodes[2]);
757 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, 40_000);
758 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
761 fn do_test_onion_failure_stale_channel_update(announced_channel: bool) {
762 // Create a network of three nodes and two channels connecting them. We'll be updating the
763 // HTLC relay policy of the second channel, causing forwarding failures at the first hop.
764 let mut config = UserConfig::default();
765 config.channel_handshake_config.announced_channel = announced_channel;
766 config.channel_handshake_limits.force_announced_channel_preference = false;
767 config.accept_forwards_to_priv_channels = !announced_channel;
768 config.channel_config.max_dust_htlc_exposure = MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253);
769 let chanmon_cfgs = create_chanmon_cfgs(3);
770 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
773 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(config), None]);
774 let channel_manager_1_deserialized;
775 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
777 let other_channel = create_chan_between_nodes(
778 &nodes[0], &nodes[1],
780 let channel_to_update = if announced_channel {
781 let channel = create_announced_chan_between_nodes(
784 (channel.2, channel.0.contents.short_channel_id)
786 let channel = create_unannounced_chan_between_nodes_with_value(
787 &nodes, 1, 2, 100000, 10001,
789 (channel.0.channel_id, channel.0.short_channel_id_alias.unwrap())
791 let channel_to_update_counterparty = &nodes[2].node.get_our_node_id();
793 let default_config = ChannelConfig::default();
795 // A test payment should succeed as the ChannelConfig has not been changed yet.
796 const PAYMENT_AMT: u64 = 40000;
797 let (route, payment_hash, payment_preimage, payment_secret) = if announced_channel {
798 get_route_and_payment_hash!(nodes[0], nodes[2], PAYMENT_AMT)
800 let hop_hints = vec![RouteHint(vec![RouteHintHop {
801 src_node_id: nodes[1].node.get_our_node_id(),
802 short_channel_id: channel_to_update.1,
804 base_msat: default_config.forwarding_fee_base_msat,
805 proportional_millionths: default_config.forwarding_fee_proportional_millionths,
807 cltv_expiry_delta: default_config.cltv_expiry_delta,
808 htlc_maximum_msat: None,
809 htlc_minimum_msat: None,
811 let payment_params = PaymentParameters::from_node_id(*channel_to_update_counterparty, TEST_FINAL_CLTV)
812 .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap()
813 .with_route_hints(hop_hints).unwrap();
814 get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, PAYMENT_AMT)
816 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[2]]], PAYMENT_AMT,
817 payment_hash, payment_secret);
818 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
820 // Closure to force expiry of a channel's previous config.
821 let expire_prev_config = || {
822 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
823 nodes[1].node.timer_tick_occurred();
827 // Closure to update and retrieve the latest ChannelUpdate.
828 let update_and_get_channel_update = |config: &ChannelConfig, expect_new_update: bool,
829 prev_update: Option<&msgs::ChannelUpdate>, should_expire_prev_config: bool| -> Option<msgs::ChannelUpdate> {
830 nodes[1].node.update_channel_config(
831 channel_to_update_counterparty, &[channel_to_update.0], config,
833 let events = nodes[1].node.get_and_clear_pending_msg_events();
834 assert_eq!(events.len(), expect_new_update as usize);
835 if !expect_new_update {
838 let new_update = match &events[0] {
839 MessageSendEvent::BroadcastChannelUpdate { msg } => {
840 assert!(announced_channel);
843 MessageSendEvent::SendChannelUpdate { node_id, msg } => {
844 assert_eq!(node_id, channel_to_update_counterparty);
845 assert!(!announced_channel);
848 _ => panic!("expected Broadcast/SendChannelUpdate event"),
850 if prev_update.is_some() {
851 assert!(new_update.contents.timestamp > prev_update.unwrap().contents.timestamp)
853 if should_expire_prev_config {
854 expire_prev_config();
859 // We'll be attempting to route payments using the default ChannelUpdate for channels. This will
860 // lead to onion failures at the first hop once we update the ChannelConfig for the
862 let expect_onion_failure = |name: &str, error_code: u16| {
863 let short_channel_id = channel_to_update.1;
864 let network_update = NetworkUpdate::ChannelFailure { short_channel_id, is_permanent: false };
865 run_onion_failure_test(
866 name, 0, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {}, true,
867 Some(error_code), Some(network_update), Some(short_channel_id),
871 // Updates to cltv_expiry_delta below MIN_CLTV_EXPIRY_DELTA should fail with APIMisuseError.
872 let mut invalid_config = default_config.clone();
873 invalid_config.cltv_expiry_delta = 0;
874 match nodes[1].node.update_channel_config(
875 channel_to_update_counterparty, &[channel_to_update.0], &invalid_config,
877 Err(APIError::APIMisuseError{ .. }) => {},
878 _ => panic!("unexpected result applying invalid cltv_expiry_delta"),
881 // Increase the base fee which should trigger a new ChannelUpdate.
882 let mut config = nodes[1].node.list_usable_channels().iter()
883 .find(|channel| channel.channel_id == channel_to_update.0).unwrap()
885 config.forwarding_fee_base_msat = u32::max_value();
886 let msg = update_and_get_channel_update(&config, true, None, false).unwrap();
888 // The old policy should still be in effect until a new block is connected.
889 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[2]]], PAYMENT_AMT,
890 payment_hash, payment_secret);
891 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
893 // Connect a block, which should expire the previous config, leading to a failure when
894 // forwarding the HTLC.
895 expire_prev_config();
896 expect_onion_failure("fee_insufficient", UPDATE|12);
898 // Redundant updates should not trigger a new ChannelUpdate.
899 assert!(update_and_get_channel_update(&config, false, None, false).is_none());
901 // Similarly, updates that do not have an affect on ChannelUpdate should not trigger a new one.
902 config.force_close_avoidance_max_fee_satoshis *= 2;
903 assert!(update_and_get_channel_update(&config, false, None, false).is_none());
905 // Reset the base fee to the default and increase the proportional fee which should trigger a
906 // new ChannelUpdate.
907 config.forwarding_fee_base_msat = default_config.forwarding_fee_base_msat;
908 config.cltv_expiry_delta = u16::max_value();
909 assert!(update_and_get_channel_update(&config, true, Some(&msg), true).is_some());
910 expect_onion_failure("incorrect_cltv_expiry", UPDATE|13);
912 // Reset the proportional fee and increase the CLTV expiry delta which should trigger a new
914 config.cltv_expiry_delta = default_config.cltv_expiry_delta;
915 config.forwarding_fee_proportional_millionths = u32::max_value();
916 assert!(update_and_get_channel_update(&config, true, Some(&msg), true).is_some());
917 expect_onion_failure("fee_insufficient", UPDATE|12);
919 // To test persistence of the updated config, we'll re-initialize the ChannelManager.
920 let config_after_restart = {
921 let chan_1_monitor_serialized = get_monitor!(nodes[1], other_channel.3).encode();
922 let chan_2_monitor_serialized = get_monitor!(nodes[1], channel_to_update.0).encode();
923 reload_node!(nodes[1], *nodes[1].node.get_current_default_configuration(), &nodes[1].node.encode(),
924 &[&chan_1_monitor_serialized, &chan_2_monitor_serialized], persister, chain_monitor, channel_manager_1_deserialized);
925 nodes[1].node.list_channels().iter()
926 .find(|channel| channel.channel_id == channel_to_update.0).unwrap()
929 assert_eq!(config, config_after_restart);
933 fn test_onion_failure_stale_channel_update() {
934 do_test_onion_failure_stale_channel_update(false);
935 do_test_onion_failure_stale_channel_update(true);
939 fn test_always_create_tlv_format_onion_payloads() {
940 // Verify that we always generate tlv onion format payloads, even if the features specifically
941 // specifies no support for variable length onions, as the legacy payload format has been
942 // deprecated in BOLT4.
943 let chanmon_cfgs = create_chanmon_cfgs(3);
944 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
946 // Set `node[1]`'s init features to features which return `false` for
947 // `supports_variable_length_onion()`
948 let mut no_variable_length_onion_features = InitFeatures::empty();
949 no_variable_length_onion_features.set_static_remote_key_required();
950 *node_cfgs[1].override_init_features.borrow_mut() = Some(no_variable_length_onion_features);
952 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
953 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
955 create_announced_chan_between_nodes(&nodes, 0, 1);
956 create_announced_chan_between_nodes(&nodes, 1, 2);
958 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
959 .with_bolt11_features(Bolt11InvoiceFeatures::empty()).unwrap();
960 let (route, _payment_hash, _payment_preimage, _payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, 40000);
962 let hops = &route.paths[0].hops;
963 // Asserts that the first hop to `node[1]` signals no support for variable length onions.
964 assert!(!hops[0].node_features.supports_variable_length_onion());
965 // Asserts that the first hop to `node[1]` signals no support for variable length onions.
966 assert!(!hops[1].node_features.supports_variable_length_onion());
968 let cur_height = nodes[0].best_block_info().1 + 1;
969 let recipient_onion_fields = RecipientOnionFields::spontaneous_empty();
970 let (onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(
971 &route.paths[0], 40000, &recipient_onion_fields, cur_height, &None).unwrap();
973 match onion_payloads[0] {
974 msgs::OutboundOnionPayload::Forward {..} => {},
976 "Should have generated a `msgs::OnionHopDataFormat::NonFinalNode` payload for `hops[0]`,
977 despite that the features signals no support for variable length onions"
980 match onion_payloads[1] {
981 msgs::OutboundOnionPayload::Receive {..} => {},
983 "Should have generated a `msgs::OnionHopDataFormat::FinalNode` payload for `hops[1]`,
984 despite that the features signals no support for variable length onions"
990 fn test_trampoline_onion_payload_serialization() {
991 // As per https://github.com/lightning/bolts/blob/c01d2e6267d4a8d1095f0f1188970055a9a22d29/bolt04/trampoline-payment-onion-test.json#L3
992 let trampoline_payload = OutboundTrampolinePayload::Forward {
993 amt_to_forward: 100000000,
994 outgoing_cltv_value: 800000,
995 outgoing_node_id: PublicKey::from_slice(&<Vec<u8>>::from_hex("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()).unwrap(),
998 let slice_to_hex = |slice: &[u8]| {
1000 .map(|b| format!("{:02x}", b).to_string())
1001 .collect::<String>()
1004 let carol_payload_hex = slice_to_hex(&trampoline_payload.encode());
1005 assert_eq!(carol_payload_hex, "2e020405f5e10004030c35000e2102edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145");
1008 fn do_test_fail_htlc_backwards_with_reason(failure_code: FailureCode) {
1010 let chanmon_cfgs = create_chanmon_cfgs(2);
1011 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1012 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1013 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1015 create_announced_chan_between_nodes(&nodes, 0, 1);
1017 let payment_amount = 100_000;
1018 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_amount);
1019 nodes[0].node.send_payment_with_route(&route, payment_hash,
1020 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1021 check_added_monitors!(nodes[0], 1);
1023 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1024 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
1025 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1026 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1028 expect_pending_htlcs_forwardable!(nodes[1]);
1029 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, payment_amount);
1030 nodes[1].node.fail_htlc_backwards_with_reason(&payment_hash, failure_code);
1032 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash }]);
1033 check_added_monitors!(nodes[1], 1);
1035 let events = nodes[1].node.get_and_clear_pending_msg_events();
1036 assert_eq!(events.len(), 1);
1037 let (update_fail_htlc, commitment_signed) = match events[0] {
1038 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 } } => {
1039 assert!(update_add_htlcs.is_empty());
1040 assert!(update_fulfill_htlcs.is_empty());
1041 assert_eq!(update_fail_htlcs.len(), 1);
1042 assert!(update_fail_malformed_htlcs.is_empty());
1043 assert!(update_fee.is_none());
1044 (update_fail_htlcs[0].clone(), commitment_signed)
1046 _ => panic!("Unexpected event"),
1049 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
1050 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
1052 let failure_data = match failure_code {
1053 FailureCode::TemporaryNodeFailure => vec![],
1054 FailureCode::RequiredNodeFeatureMissing => vec![],
1055 FailureCode::IncorrectOrUnknownPaymentDetails => {
1056 let mut htlc_msat_height_data = (payment_amount as u64).to_be_bytes().to_vec();
1057 htlc_msat_height_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
1058 htlc_msat_height_data
1060 FailureCode::InvalidOnionPayload(data) => {
1062 Some((typ, offset)) => [BigSize(typ).encode(), offset.encode()].concat(),
1068 let failure_code = failure_code.into();
1069 let permanent_flag = 0x4000;
1070 let permanent_fail = (failure_code & permanent_flag) != 0;
1071 expect_payment_failed!(nodes[0], payment_hash, permanent_fail, failure_code, failure_data);
1076 fn test_fail_htlc_backwards_with_reason() {
1077 do_test_fail_htlc_backwards_with_reason(FailureCode::TemporaryNodeFailure);
1078 do_test_fail_htlc_backwards_with_reason(FailureCode::RequiredNodeFeatureMissing);
1079 do_test_fail_htlc_backwards_with_reason(FailureCode::IncorrectOrUnknownPaymentDetails);
1080 do_test_fail_htlc_backwards_with_reason(FailureCode::InvalidOnionPayload(Some((1 << 16, 42))));
1081 do_test_fail_htlc_backwards_with_reason(FailureCode::InvalidOnionPayload(None));
1084 macro_rules! get_phantom_route {
1085 ($nodes: expr, $amt: expr, $channel: expr) => {{
1086 let phantom_pubkey = $nodes[1].keys_manager.get_node_id(Recipient::PhantomNode).unwrap();
1087 let phantom_route_hint = $nodes[1].node.get_phantom_route_hints();
1088 let payment_params = PaymentParameters::from_node_id(phantom_pubkey, TEST_FINAL_CLTV)
1089 .with_bolt11_features($nodes[1].node.bolt11_invoice_features()).unwrap()
1090 .with_route_hints(vec![RouteHint(vec![
1092 src_node_id: $nodes[0].node.get_our_node_id(),
1093 short_channel_id: $channel.0.contents.short_channel_id,
1095 base_msat: $channel.0.contents.fee_base_msat,
1096 proportional_millionths: $channel.0.contents.fee_proportional_millionths,
1098 cltv_expiry_delta: $channel.0.contents.cltv_expiry_delta,
1099 htlc_minimum_msat: None,
1100 htlc_maximum_msat: None,
1103 src_node_id: phantom_route_hint.real_node_pubkey,
1104 short_channel_id: phantom_route_hint.phantom_scid,
1107 proportional_millionths: 0,
1109 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1110 htlc_minimum_msat: None,
1111 htlc_maximum_msat: None,
1114 let scorer = test_utils::TestScorer::new();
1115 let network_graph = $nodes[0].network_graph.read_only();
1116 let route_params = RouteParameters::from_payment_params_and_value(payment_params, $amt);
1118 &$nodes[0].node.get_our_node_id(), &route_params, &network_graph,
1119 Some(&$nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
1120 $nodes[0].logger, &scorer, &Default::default(), &[0u8; 32]
1121 ).unwrap(), phantom_route_hint.phantom_scid)
1126 fn test_phantom_onion_hmac_failure() {
1127 let chanmon_cfgs = create_chanmon_cfgs(2);
1128 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1129 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1130 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1132 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1135 let recv_value_msat = 10_000;
1136 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
1137 let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
1139 // Route the HTLC through to the destination.
1140 nodes[0].node.send_payment_with_route(&route, payment_hash,
1141 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1142 check_added_monitors!(nodes[0], 1);
1143 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1144 let mut update_add = update_0.update_add_htlcs[0].clone();
1146 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1147 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1149 // Modify the payload so the phantom hop's HMAC is bogus.
1150 let sha256_of_onion = {
1151 let mut forward_htlcs = nodes[1].node.forward_htlcs.lock().unwrap();
1152 let mut pending_forward = forward_htlcs.get_mut(&phantom_scid).unwrap();
1153 match pending_forward[0] {
1154 HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
1155 forward_info: PendingHTLCInfo {
1156 routing: PendingHTLCRouting::Forward { ref mut onion_packet, .. },
1160 onion_packet.hmac[onion_packet.hmac.len() - 1] ^= 1;
1161 Sha256::hash(&onion_packet.hop_data).to_byte_array().to_vec()
1163 _ => panic!("Unexpected forward"),
1166 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1167 nodes[1].node.process_pending_htlc_forwards();
1168 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1169 nodes[1].node.process_pending_htlc_forwards();
1170 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1171 check_added_monitors!(&nodes[1], 1);
1172 assert!(update_1.update_fail_htlcs.len() == 1);
1173 let fail_msg = update_1.update_fail_htlcs[0].clone();
1174 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1175 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1177 // Ensure the payment fails with the expected error.
1178 let mut fail_conditions = PaymentFailedConditions::new()
1179 .blamed_scid(phantom_scid)
1180 .blamed_chan_closed(true)
1181 .expected_htlc_error_data(0x8000 | 0x4000 | 5, &sha256_of_onion);
1182 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1186 fn test_phantom_invalid_onion_payload() {
1187 let chanmon_cfgs = create_chanmon_cfgs(2);
1188 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1189 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1190 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1192 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1195 let recv_value_msat = 10_000;
1196 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
1197 let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
1199 // We'll use the session priv later when constructing an invalid onion packet.
1200 let session_priv = [3; 32];
1201 *nodes[0].keys_manager.override_random_bytes.lock().unwrap() = Some(session_priv);
1202 nodes[0].node.send_payment_with_route(&route, payment_hash,
1203 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1204 check_added_monitors!(nodes[0], 1);
1205 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1206 let mut update_add = update_0.update_add_htlcs[0].clone();
1208 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1209 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1211 // Modify the onion packet to have an invalid payment amount.
1212 for (_, pending_forwards) in nodes[1].node.forward_htlcs.lock().unwrap().iter_mut() {
1213 for f in pending_forwards.iter_mut() {
1215 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
1216 forward_info: PendingHTLCInfo {
1217 routing: PendingHTLCRouting::Forward { ref mut onion_packet, .. },
1221 // Construct the onion payloads for the entire route and an invalid amount.
1222 let height = nodes[0].best_block_info().1;
1223 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
1224 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
1225 let recipient_onion_fields = RecipientOnionFields::secret_only(payment_secret);
1226 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(
1227 &route.paths[0], msgs::MAX_VALUE_MSAT + 1,
1228 &recipient_onion_fields, height + 1, &None).unwrap();
1229 // We only want to construct the onion packet for the last hop, not the entire route, so
1230 // remove the first hop's payload and its keys.
1231 onion_keys.remove(0);
1232 onion_payloads.remove(0);
1234 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1235 onion_packet.hop_data = new_onion_packet.hop_data;
1236 onion_packet.hmac = new_onion_packet.hmac;
1238 _ => panic!("Unexpected forward"),
1242 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1243 nodes[1].node.process_pending_htlc_forwards();
1244 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1245 nodes[1].node.process_pending_htlc_forwards();
1246 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1247 check_added_monitors!(&nodes[1], 1);
1248 assert!(update_1.update_fail_htlcs.len() == 1);
1249 let fail_msg = update_1.update_fail_htlcs[0].clone();
1250 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1251 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1253 // Ensure the payment fails with the expected error.
1254 let error_data = Vec::new();
1255 let mut fail_conditions = PaymentFailedConditions::new()
1256 .blamed_scid(phantom_scid)
1257 .blamed_chan_closed(true)
1258 .expected_htlc_error_data(0x4000 | 22, &error_data);
1259 expect_payment_failed_conditions(&nodes[0], payment_hash, true, fail_conditions);
1263 fn test_phantom_final_incorrect_cltv_expiry() {
1264 let chanmon_cfgs = create_chanmon_cfgs(2);
1265 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1266 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1267 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1269 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1272 let recv_value_msat = 10_000;
1273 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
1274 let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
1276 // Route the HTLC through to the destination.
1277 nodes[0].node.send_payment_with_route(&route, payment_hash,
1278 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1279 check_added_monitors!(nodes[0], 1);
1280 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1281 let mut update_add = update_0.update_add_htlcs[0].clone();
1283 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1284 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1286 // Modify the payload so the phantom hop's HMAC is bogus.
1287 for (_, pending_forwards) in nodes[1].node.forward_htlcs.lock().unwrap().iter_mut() {
1288 for f in pending_forwards.iter_mut() {
1290 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
1291 forward_info: PendingHTLCInfo { ref mut outgoing_cltv_value, .. }, ..
1293 *outgoing_cltv_value -= 1;
1295 _ => panic!("Unexpected forward"),
1299 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1300 nodes[1].node.process_pending_htlc_forwards();
1301 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1302 nodes[1].node.process_pending_htlc_forwards();
1303 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1304 check_added_monitors!(&nodes[1], 1);
1305 assert!(update_1.update_fail_htlcs.len() == 1);
1306 let fail_msg = update_1.update_fail_htlcs[0].clone();
1307 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1308 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1310 // Ensure the payment fails with the expected error.
1311 let expected_cltv: u32 = 80;
1312 let error_data = expected_cltv.to_be_bytes().to_vec();
1313 let mut fail_conditions = PaymentFailedConditions::new()
1314 .blamed_scid(phantom_scid)
1315 .expected_htlc_error_data(18, &error_data);
1316 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1320 fn test_phantom_failure_too_low_cltv() {
1321 let chanmon_cfgs = create_chanmon_cfgs(2);
1322 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1323 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1324 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1326 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1329 let recv_value_msat = 10_000;
1330 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
1331 let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
1333 // Modify the route to have a too-low cltv.
1334 route.paths[0].hops[1].cltv_expiry_delta = 5;
1336 // Route the HTLC through to the destination.
1337 nodes[0].node.send_payment_with_route(&route, payment_hash,
1338 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1339 check_added_monitors!(nodes[0], 1);
1340 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1341 let mut update_add = update_0.update_add_htlcs[0].clone();
1343 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1344 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1346 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1347 nodes[1].node.process_pending_htlc_forwards();
1348 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1349 nodes[1].node.process_pending_htlc_forwards();
1350 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1351 check_added_monitors!(&nodes[1], 1);
1352 assert!(update_1.update_fail_htlcs.len() == 1);
1353 let fail_msg = update_1.update_fail_htlcs[0].clone();
1354 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1355 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1357 // Ensure the payment fails with the expected error.
1358 let mut error_data = recv_value_msat.to_be_bytes().to_vec();
1359 error_data.extend_from_slice(
1360 &nodes[0].node.best_block.read().unwrap().height.to_be_bytes(),
1362 let mut fail_conditions = PaymentFailedConditions::new()
1363 .blamed_scid(phantom_scid)
1364 .expected_htlc_error_data(0x4000 | 15, &error_data);
1365 expect_payment_failed_conditions(&nodes[0], payment_hash, true, fail_conditions);
1369 fn test_phantom_failure_modified_cltv() {
1370 // Test that we fail back phantoms if the upstream node fiddled with the CLTV too much with the
1371 // correct error code.
1372 let chanmon_cfgs = create_chanmon_cfgs(2);
1373 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1374 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1375 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1377 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1380 let recv_value_msat = 10_000;
1381 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
1382 let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
1384 // Route the HTLC through to the destination.
1385 nodes[0].node.send_payment_with_route(&route, payment_hash,
1386 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1387 check_added_monitors!(nodes[0], 1);
1388 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1389 let mut update_add = update_0.update_add_htlcs[0].clone();
1391 // Modify the route to have a too-low cltv.
1392 update_add.cltv_expiry -= 10;
1394 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1395 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1397 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1398 assert!(update_1.update_fail_htlcs.len() == 1);
1399 let fail_msg = update_1.update_fail_htlcs[0].clone();
1400 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1401 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1403 // Ensure the payment fails with the expected error.
1404 let mut fail_conditions = PaymentFailedConditions::new()
1405 .blamed_scid(phantom_scid)
1406 .expected_htlc_error_data(0x2000 | 2, &[]);
1407 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1411 fn test_phantom_failure_expires_too_soon() {
1412 // Test that we fail back phantoms if the HTLC got delayed and we got blocks in between with
1413 // the correct error code.
1414 let chanmon_cfgs = create_chanmon_cfgs(2);
1415 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1416 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1417 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1419 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1422 let recv_value_msat = 10_000;
1423 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
1424 let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
1426 // Route the HTLC through to the destination.
1427 nodes[0].node.send_payment_with_route(&route, payment_hash,
1428 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1429 check_added_monitors!(nodes[0], 1);
1430 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1431 let mut update_add = update_0.update_add_htlcs[0].clone();
1433 connect_blocks(&nodes[1], CLTV_FAR_FAR_AWAY);
1434 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1435 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1437 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1438 assert!(update_1.update_fail_htlcs.len() == 1);
1439 let fail_msg = update_1.update_fail_htlcs[0].clone();
1440 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1441 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1443 // Ensure the payment fails with the expected error.
1444 let mut fail_conditions = PaymentFailedConditions::new()
1445 .blamed_scid(phantom_scid)
1446 .expected_htlc_error_data(0x2000 | 2, &[]);
1447 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1451 fn test_phantom_failure_too_low_recv_amt() {
1452 let chanmon_cfgs = create_chanmon_cfgs(2);
1453 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1454 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1455 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1457 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1459 // Get the route with a too-low amount.
1460 let recv_amt_msat = 10_000;
1461 let bad_recv_amt_msat = recv_amt_msat - 10;
1462 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_amt_msat));
1463 let (mut route, phantom_scid) = get_phantom_route!(nodes, bad_recv_amt_msat, channel);
1465 // Route the HTLC through to the destination.
1466 nodes[0].node.send_payment_with_route(&route, payment_hash,
1467 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1468 check_added_monitors!(nodes[0], 1);
1469 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1470 let mut update_add = update_0.update_add_htlcs[0].clone();
1472 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1473 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1475 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1476 nodes[1].node.process_pending_htlc_forwards();
1477 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1478 nodes[1].node.process_pending_htlc_forwards();
1479 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
1480 nodes[1].node.process_pending_htlc_forwards();
1481 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1482 check_added_monitors!(&nodes[1], 1);
1483 assert!(update_1.update_fail_htlcs.len() == 1);
1484 let fail_msg = update_1.update_fail_htlcs[0].clone();
1485 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1486 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1488 // Ensure the payment fails with the expected error.
1489 let mut error_data = bad_recv_amt_msat.to_be_bytes().to_vec();
1490 error_data.extend_from_slice(&nodes[1].node.best_block.read().unwrap().height.to_be_bytes());
1491 let mut fail_conditions = PaymentFailedConditions::new()
1492 .blamed_scid(phantom_scid)
1493 .expected_htlc_error_data(0x4000 | 15, &error_data);
1494 expect_payment_failed_conditions(&nodes[0], payment_hash, true, fail_conditions);
1498 fn test_phantom_dust_exposure_failure() {
1499 do_test_phantom_dust_exposure_failure(false);
1500 do_test_phantom_dust_exposure_failure(true);
1503 fn do_test_phantom_dust_exposure_failure(multiplier_dust_limit: bool) {
1504 // Set the max dust exposure to the dust limit.
1505 let max_dust_exposure = 546;
1506 let mut receiver_config = UserConfig::default();
1507 // Default test fee estimator rate is 253, so to set the max dust exposure to the dust limit,
1508 // we need to set the multiplier to 2.
1509 receiver_config.channel_config.max_dust_htlc_exposure =
1510 if multiplier_dust_limit { MaxDustHTLCExposure::FeeRateMultiplier(2) }
1511 else { MaxDustHTLCExposure::FixedLimitMsat(max_dust_exposure) };
1512 receiver_config.channel_handshake_config.announced_channel = true;
1514 let chanmon_cfgs = create_chanmon_cfgs(2);
1515 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1516 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(receiver_config)]);
1517 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1519 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1521 // Get the route with an amount exceeding the dust exposure threshold of nodes[1].
1522 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(max_dust_exposure + 1));
1523 let (mut route, _) = get_phantom_route!(nodes, max_dust_exposure + 1, channel);
1525 // Route the HTLC through to the destination.
1526 nodes[0].node.send_payment_with_route(&route, payment_hash,
1527 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1528 check_added_monitors!(nodes[0], 1);
1529 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1530 let mut update_add = update_0.update_add_htlcs[0].clone();
1532 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1533 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1535 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1536 assert!(update_1.update_fail_htlcs.len() == 1);
1537 let fail_msg = update_1.update_fail_htlcs[0].clone();
1538 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1539 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1541 // Ensure the payment fails with the expected error.
1542 let mut err_data = Vec::new();
1543 err_data.extend_from_slice(&(channel.1.serialized_length() as u16 + 2).to_be_bytes());
1544 err_data.extend_from_slice(&ChannelUpdate::TYPE.to_be_bytes());
1545 err_data.extend_from_slice(&channel.1.encode());
1547 let mut fail_conditions = PaymentFailedConditions::new()
1548 .blamed_scid(route.paths[0].hops.last().as_ref().unwrap().short_channel_id)
1549 .blamed_chan_closed(false)
1550 .expected_htlc_error_data(0x1000 | 7, &err_data);
1551 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1555 fn test_phantom_failure_reject_payment() {
1556 // Test that the user can successfully fail back a phantom node payment.
1557 let chanmon_cfgs = create_chanmon_cfgs(2);
1558 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1559 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1560 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1562 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
1564 // Get the route with a too-low amount.
1565 let recv_amt_msat = 10_000;
1566 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_amt_msat));
1567 let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_amt_msat, channel);
1569 // Route the HTLC through to the destination.
1570 nodes[0].node.send_payment_with_route(&route, payment_hash,
1571 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1572 check_added_monitors!(nodes[0], 1);
1573 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1574 let mut update_add = update_0.update_add_htlcs[0].clone();
1576 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1577 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1579 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1580 nodes[1].node.process_pending_htlc_forwards();
1581 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1582 nodes[1].node.process_pending_htlc_forwards();
1583 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_amt_msat, None, route.paths[0].hops.last().unwrap().pubkey);
1584 nodes[1].node.fail_htlc_backwards(&payment_hash);
1585 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1586 nodes[1].node.process_pending_htlc_forwards();
1588 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1589 check_added_monitors!(&nodes[1], 1);
1590 assert!(update_1.update_fail_htlcs.len() == 1);
1591 let fail_msg = update_1.update_fail_htlcs[0].clone();
1592 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1593 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1595 // Ensure the payment fails with the expected error.
1596 let mut error_data = recv_amt_msat.to_be_bytes().to_vec();
1597 error_data.extend_from_slice(&nodes[1].node.best_block.read().unwrap().height.to_be_bytes());
1598 let mut fail_conditions = PaymentFailedConditions::new()
1599 .blamed_scid(phantom_scid)
1600 .expected_htlc_error_data(0x4000 | 15, &error_data);
1601 expect_payment_failed_conditions(&nodes[0], payment_hash, true, fail_conditions);