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 chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
15 use chain::keysinterface::{KeysInterface, Recipient};
16 use ln::{PaymentHash, PaymentSecret};
17 use ln::channelmanager::{HTLCForwardInfo, CLTV_FAR_FAR_AWAY, MIN_CLTV_EXPIRY_DELTA, PendingHTLCInfo, PendingHTLCRouting};
19 use routing::network_graph::{NetworkUpdate, RoutingFees};
20 use routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintHop};
21 use ln::features::{InitFeatures, InvoiceFeatures};
23 use ln::msgs::{ChannelMessageHandler, ChannelUpdate, OptionalField};
24 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider};
25 use util::ser::{Writeable, Writer};
26 use util::{byte_utils, test_utils};
27 use util::config::UserConfig;
29 use bitcoin::hash_types::BlockHash;
31 use bitcoin::hashes::Hash;
32 use bitcoin::hashes::sha256::Hash as Sha256;
34 use bitcoin::secp256k1;
35 use bitcoin::secp256k1::Secp256k1;
36 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
40 use core::default::Default;
42 use ln::functional_test_utils::*;
44 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>)
45 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
48 run_onion_failure_test_with_fail_intercept(_name, test_case, nodes, route, payment_hash, payment_secret, callback_msg, |_|{}, callback_node, expected_retryable, expected_error_code, expected_channel_update, expected_short_channel_id);
52 // 0: node1 fails backward
53 // 1: final node fails backward
54 // 2: payment completed but the user rejects the payment
55 // 3: final node fails backward (but tamper onion payloads from node0)
56 // 100: trigger error in the intermediate node and tamper returning fail_htlc
57 // 200: trigger error in the final node and tamper returning fail_htlc
58 fn run_onion_failure_test_with_fail_intercept<F1,F2,F3>(_name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash, payment_secret: &PaymentSecret, mut callback_msg: F1, mut callback_fail: F2, mut callback_node: F3, expected_retryable: bool, expected_error_code: Option<u16>, expected_channel_update: Option<NetworkUpdate>, expected_short_channel_id: Option<u64>)
59 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
60 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
63 macro_rules! expect_event {
64 ($node: expr, $event_type: path) => {{
65 let events = $node.node.get_and_clear_pending_events();
66 assert_eq!(events.len(), 1);
68 $event_type { .. } => {},
69 _ => panic!("Unexpected event"),
74 macro_rules! expect_htlc_forward {
76 expect_event!($node, Event::PendingHTLCsForwardable);
77 $node.node.process_pending_htlc_forwards();
81 // 0 ~~> 2 send payment
82 nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(*payment_secret)).unwrap();
83 check_added_monitors!(nodes[0], 1);
84 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
85 // temper update_add (0 => 1)
86 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
87 if test_case == 0 || test_case == 3 || test_case == 100 {
88 callback_msg(&mut update_add_0);
91 // 0 => 1 update_add & CS
92 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
93 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
95 let update_1_0 = match test_case {
96 0|100 => { // intermediate node failure; fail backward to 0
97 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
98 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));
101 1|2|3|200 => { // final node failure; forwarding to 2
102 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
104 if test_case != 200 {
107 expect_htlc_forward!(&nodes[1]);
109 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
110 check_added_monitors!(&nodes[1], 1);
111 assert_eq!(update_1.update_add_htlcs.len(), 1);
112 // tamper update_add (1 => 2)
113 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
114 if test_case != 3 && test_case != 200 {
115 callback_msg(&mut update_add_1);
119 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
120 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
122 if test_case == 2 || test_case == 200 {
123 expect_htlc_forward!(&nodes[2]);
124 expect_event!(&nodes[2], Event::PaymentReceived);
126 expect_pending_htlcs_forwardable!(nodes[2]);
129 let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
130 if test_case == 2 || test_case == 200 {
131 check_added_monitors!(&nodes[2], 1);
133 assert!(update_2_1.update_fail_htlcs.len() == 1);
135 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
136 if test_case == 200 {
137 callback_fail(&mut fail_msg);
141 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg);
142 commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
144 // backward fail on 1
145 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
146 assert!(update_1_0.update_fail_htlcs.len() == 1);
152 // 1 => 0 commitment_signed_dance
153 if update_1_0.update_fail_htlcs.len() > 0 {
154 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
155 if test_case == 100 {
156 callback_fail(&mut fail_msg);
158 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
160 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]);
163 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
165 let events = nodes[0].node.get_and_clear_pending_events();
166 assert_eq!(events.len(), 1);
167 if let &Event::PaymentPathFailed { ref rejected_by_dest, ref network_update, ref all_paths_failed, ref short_channel_id, ref error_code, .. } = &events[0] {
168 assert_eq!(*rejected_by_dest, !expected_retryable);
169 assert_eq!(*all_paths_failed, true);
170 assert_eq!(*error_code, expected_error_code);
171 if expected_channel_update.is_some() {
172 match network_update {
173 Some(update) => match update {
174 &NetworkUpdate::ChannelUpdateMessage { .. } => {
175 if let NetworkUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
176 panic!("channel_update not found!");
179 &NetworkUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
180 if let NetworkUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
181 assert!(*short_channel_id == *expected_short_channel_id);
182 assert!(*is_permanent == *expected_is_permanent);
184 panic!("Unexpected message event");
187 &NetworkUpdate::NodeFailure { ref node_id, ref is_permanent } => {
188 if let NetworkUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
189 assert!(*node_id == *expected_node_id);
190 assert!(*is_permanent == *expected_is_permanent);
192 panic!("Unexpected message event");
196 None => panic!("Expected channel update"),
199 assert!(network_update.is_none());
201 if let Some(expected_short_channel_id) = expected_short_channel_id {
202 match short_channel_id {
203 Some(short_channel_id) => assert_eq!(*short_channel_id, expected_short_channel_id),
204 None => panic!("Expected short channel id"),
207 assert!(short_channel_id.is_none());
210 panic!("Unexpected event");
214 impl msgs::ChannelUpdate {
215 fn dummy(short_channel_id: u64) -> msgs::ChannelUpdate {
216 use bitcoin::secp256k1::ffi::Signature as FFISignature;
217 use bitcoin::secp256k1::Signature;
218 msgs::ChannelUpdate {
219 signature: Signature::from(unsafe { FFISignature::new() }),
220 contents: msgs::UnsignedChannelUpdate {
221 chain_hash: BlockHash::hash(&vec![0u8][..]),
225 cltv_expiry_delta: 0,
226 htlc_minimum_msat: 0,
227 htlc_maximum_msat: OptionalField::Absent,
229 fee_proportional_millionths: 0,
236 struct BogusOnionHopData {
239 impl BogusOnionHopData {
240 fn new(orig: msgs::OnionHopData) -> Self {
241 Self { data: orig.encode() }
244 impl Writeable for BogusOnionHopData {
245 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
246 writer.write_all(&self.data[..])
250 const BADONION: u16 = 0x8000;
251 const PERM: u16 = 0x4000;
252 const NODE: u16 = 0x2000;
253 const UPDATE: u16 = 0x1000;
256 fn test_fee_failures() {
257 // Tests that the fee required when forwarding remains consistent over time. This was
258 // previously broken, with forwarding fees floating based on the fee estimator at the time of
261 // When this test was written, the default base fee floated based on the HTLC count.
262 // It is now fixed, so we simply set the fee to the expected value here.
263 let mut config = test_default_channel_config();
264 config.channel_options.forwarding_fee_base_msat = 196;
266 let chanmon_cfgs = create_chanmon_cfgs(3);
267 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
268 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config), Some(config), Some(config)]);
269 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
270 let channels = [create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()), create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known())];
273 let (route, payment_hash_success, payment_preimage_success, payment_secret_success) = get_route_and_payment_hash!(nodes[0], nodes[2], 40_000);
274 nodes[0].node.send_payment(&route, payment_hash_success, &Some(payment_secret_success)).unwrap();
275 check_added_monitors!(nodes[0], 1);
276 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 40_000, payment_hash_success, payment_secret_success);
277 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_success);
279 // If the hop gives fee_insufficient but enough fees were provided, then the previous hop
280 // malleated the payment before forwarding, taking funds when they shouldn't have.
281 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
282 let short_channel_id = channels[0].0.contents.short_channel_id;
283 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
284 msg.amount_msat -= 1;
285 }, || {}, true, Some(UPDATE|12), Some(NetworkUpdate::ChannelClosed { short_channel_id, is_permanent: true}), Some(short_channel_id));
287 // In an earlier version, we spuriously failed to forward payments if the expected feerate
288 // changed between the channel open and the payment.
290 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
294 let (payment_preimage_success, payment_hash_success, payment_secret_success) = get_payment_preimage_hash!(nodes[2]);
295 nodes[0].node.send_payment(&route, payment_hash_success, &Some(payment_secret_success)).unwrap();
296 check_added_monitors!(nodes[0], 1);
297 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 40_000, payment_hash_success, payment_secret_success);
298 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_success);
302 fn test_onion_failure() {
303 // When we check for amount_below_minimum below, we want to test that we're using the *right*
304 // amount, thus we need different htlc_minimum_msat values. We set node[2]'s htlc_minimum_msat
305 // to 2000, which is above the default value of 1000 set in create_node_chanmgrs.
306 // This exposed a previous bug because we were using the wrong value all the way down in
307 // Channel::get_counterparty_htlc_minimum_msat().
308 let mut node_2_cfg: UserConfig = Default::default();
309 node_2_cfg.own_channel_config.our_htlc_minimum_msat = 2000;
310 node_2_cfg.channel_options.announced_channel = true;
311 node_2_cfg.peer_channel_config_limits.force_announced_channel_preference = false;
313 // When this test was written, the default base fee floated based on the HTLC count.
314 // It is now fixed, so we simply set the fee to the expected value here.
315 let mut config = test_default_channel_config();
316 config.channel_options.forwarding_fee_base_msat = 196;
318 let chanmon_cfgs = create_chanmon_cfgs(3);
319 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
320 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config), Some(config), Some(node_2_cfg)]);
321 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
322 let channels = [create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()), create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known())];
323 for node in nodes.iter() {
324 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([3; 32]);
326 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 40000);
328 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000);
330 // intermediate node failure
331 let short_channel_id = channels[1].0.contents.short_channel_id;
332 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
333 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
334 let cur_height = nodes[0].best_block_info().1 + 1;
335 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
336 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height, &None).unwrap();
337 let mut new_payloads = Vec::new();
338 for payload in onion_payloads.drain(..) {
339 new_payloads.push(BogusOnionHopData::new(payload));
341 // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
342 // describing a length-1 TLV payload, which is obviously bogus.
343 new_payloads[0].data[0] = 1;
344 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
345 }, ||{}, true, Some(PERM|22), Some(NetworkUpdate::ChannelClosed{short_channel_id, is_permanent: true}), Some(short_channel_id));
347 // final node failure
348 let short_channel_id = channels[1].0.contents.short_channel_id;
349 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, &payment_secret, |msg| {
350 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
351 let cur_height = nodes[0].best_block_info().1 + 1;
352 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
353 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height, &None).unwrap();
354 let mut new_payloads = Vec::new();
355 for payload in onion_payloads.drain(..) {
356 new_payloads.push(BogusOnionHopData::new(payload));
358 // break the last-hop payload by swapping the realm (0) byte for a byte describing a
359 // length-1 TLV payload, which is obviously bogus.
360 new_payloads[1].data[0] = 1;
361 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
362 }, ||{}, false, Some(PERM|22), Some(NetworkUpdate::ChannelClosed{short_channel_id, is_permanent: true}), Some(short_channel_id));
364 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
365 // receiving simulated fail messages
366 // intermediate node failure
367 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
369 msg.amount_msat -= 1;
371 // and tamper returning error message
372 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
373 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
374 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
375 }, ||{}, true, Some(NODE|2), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: false}), Some(route.paths[0][0].short_channel_id));
377 // final node failure
378 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
379 // and tamper returning error message
380 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
381 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
382 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
384 nodes[2].node.fail_htlc_backwards(&payment_hash);
385 }, true, Some(NODE|2), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: false}), Some(route.paths[0][1].short_channel_id));
386 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
388 // intermediate node failure
389 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
390 msg.amount_msat -= 1;
392 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
393 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
394 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
395 }, ||{}, true, Some(PERM|NODE|2), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}), Some(route.paths[0][0].short_channel_id));
397 // final node failure
398 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
399 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
400 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
401 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
403 nodes[2].node.fail_htlc_backwards(&payment_hash);
404 }, false, Some(PERM|NODE|2), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}), Some(route.paths[0][1].short_channel_id));
405 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
407 // intermediate node failure
408 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
409 msg.amount_msat -= 1;
411 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
412 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
413 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
415 nodes[2].node.fail_htlc_backwards(&payment_hash);
416 }, true, Some(PERM|NODE|3), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}), Some(route.paths[0][0].short_channel_id));
418 // final node failure
419 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
420 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
421 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
422 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
424 nodes[2].node.fail_htlc_backwards(&payment_hash);
425 }, false, Some(PERM|NODE|3), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}), Some(route.paths[0][1].short_channel_id));
426 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
428 // Our immediate peer sent UpdateFailMalformedHTLC because it couldn't understand the onion in
429 // the UpdateAddHTLC that we sent.
430 let short_channel_id = channels[0].0.contents.short_channel_id;
431 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
432 Some(BADONION|PERM|4), None, Some(short_channel_id));
434 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
435 Some(BADONION|PERM|5), None, Some(short_channel_id));
437 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,
438 Some(BADONION|PERM|6), None, Some(short_channel_id));
440 let short_channel_id = channels[1].0.contents.short_channel_id;
441 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
442 msg.amount_msat -= 1;
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[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy(short_channel_id).encode_with_len()[..]);
447 }, ||{}, true, Some(UPDATE|7), Some(NetworkUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy(short_channel_id)}), Some(short_channel_id));
449 let short_channel_id = channels[1].0.contents.short_channel_id;
450 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
451 msg.amount_msat -= 1;
453 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
454 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
455 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
456 // short_channel_id from the processing node
457 }, ||{}, true, Some(PERM|8), Some(NetworkUpdate::ChannelClosed{short_channel_id, is_permanent: true}), Some(short_channel_id));
459 let short_channel_id = channels[1].0.contents.short_channel_id;
460 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
461 msg.amount_msat -= 1;
463 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
464 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
465 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
466 // short_channel_id from the processing node
467 }, ||{}, true, Some(PERM|9), Some(NetworkUpdate::ChannelClosed{short_channel_id, is_permanent: true}), Some(short_channel_id));
469 let mut bogus_route = route.clone();
470 bogus_route.paths[0][1].short_channel_id -= 1;
471 let short_channel_id = bogus_route.paths[0][1].short_channel_id;
472 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, &payment_secret, |_| {}, ||{}, true, Some(PERM|10),
473 Some(NetworkUpdate::ChannelClosed{short_channel_id, is_permanent:true}), Some(short_channel_id));
475 let short_channel_id = channels[1].0.contents.short_channel_id;
476 let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_counterparty_htlc_minimum_msat() - 1;
477 let mut bogus_route = route.clone();
478 let route_len = bogus_route.paths[0].len();
479 bogus_route.paths[0][route_len-1].fee_msat = amt_to_forward;
480 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, &payment_secret, |_| {}, ||{}, true, Some(UPDATE|11), Some(NetworkUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy(short_channel_id)}), Some(short_channel_id));
482 // Clear pending payments so that the following positive test has the correct payment hash.
483 for node in nodes.iter() {
484 node.node.clear_pending_payments();
487 // Test a positive test-case with one extra msat, meeting the minimum.
488 bogus_route.paths[0][route_len-1].fee_msat = amt_to_forward + 1;
489 let preimage = send_along_route(&nodes[0], bogus_route, &[&nodes[1], &nodes[2]], amt_to_forward+1).0;
490 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], preimage);
492 //TODO: with new config API, we will be able to generate both valid and
493 //invalid channel_update cases.
494 let short_channel_id = channels[0].0.contents.short_channel_id;
495 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
496 msg.amount_msat -= 1;
497 }, || {}, true, Some(UPDATE|12), Some(NetworkUpdate::ChannelClosed { short_channel_id, is_permanent: true}), Some(short_channel_id));
499 let short_channel_id = channels[0].0.contents.short_channel_id;
500 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
501 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
502 msg.cltv_expiry -= 1;
503 }, || {}, true, Some(UPDATE|13), Some(NetworkUpdate::ChannelClosed { short_channel_id, is_permanent: true}), Some(short_channel_id));
505 let short_channel_id = channels[1].0.contents.short_channel_id;
506 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
507 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
508 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
509 connect_blocks(&nodes[1], height - nodes[1].best_block_info().1);
510 connect_blocks(&nodes[2], height - nodes[2].best_block_info().1);
511 }, ||{}, true, Some(UPDATE|14), Some(NetworkUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy(short_channel_id)}), Some(short_channel_id));
513 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
514 nodes[2].node.fail_htlc_backwards(&payment_hash);
515 }, false, Some(PERM|15), None, None);
516 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
518 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, &payment_secret, |msg| {
519 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
520 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
521 connect_blocks(&nodes[1], height - nodes[1].best_block_info().1);
522 connect_blocks(&nodes[2], height - nodes[2].best_block_info().1);
523 }, || {}, true, Some(17), None, None);
525 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
526 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
527 for f in pending_forwards.iter_mut() {
529 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
530 forward_info.outgoing_cltv_value += 1,
535 }, true, Some(18), None, Some(channels[1].0.contents.short_channel_id));
537 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
538 // violate amt_to_forward > msg.amount_msat
539 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
540 for f in pending_forwards.iter_mut() {
542 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
543 forward_info.amt_to_forward -= 1,
548 }, true, Some(19), None, Some(channels[1].0.contents.short_channel_id));
550 let short_channel_id = channels[1].0.contents.short_channel_id;
551 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
552 // disconnect event to the channel between nodes[1] ~ nodes[2]
553 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
554 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
555 }, true, Some(UPDATE|20), Some(NetworkUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy(short_channel_id)}), Some(short_channel_id));
556 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
558 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
559 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
560 let mut route = route.clone();
561 let height = nodes[2].best_block_info().1;
562 route.paths[0][1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.paths[0][0].cltv_expiry_delta + 1;
563 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
564 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, height, &None).unwrap();
565 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
566 msg.cltv_expiry = htlc_cltv;
567 msg.onion_routing_packet = onion_packet;
568 }, ||{}, true, Some(21), Some(NetworkUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}), Some(route.paths[0][0].short_channel_id));
570 run_onion_failure_test_with_fail_intercept("mpp_timeout", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
571 // Tamper returning error message
572 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
573 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
574 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], 23, &[0;0]);
576 nodes[2].node.fail_htlc_backwards(&payment_hash);
577 }, true, Some(23), None, None);
580 macro_rules! get_phantom_route {
581 ($nodes: expr, $amt: expr, $channel: expr) => {{
582 let secp_ctx = Secp256k1::new();
583 let phantom_secret = $nodes[1].keys_manager.get_node_secret(Recipient::PhantomNode).unwrap();
584 let phantom_pubkey = PublicKey::from_secret_key(&secp_ctx, &phantom_secret);
585 let phantom_route_hint = $nodes[1].node.get_phantom_route_hints();
586 let payment_params = PaymentParameters::from_node_id(phantom_pubkey)
587 .with_features(InvoiceFeatures::known())
588 .with_route_hints(vec![RouteHint(vec![
590 src_node_id: $nodes[0].node.get_our_node_id(),
591 short_channel_id: $channel.0.contents.short_channel_id,
593 base_msat: $channel.0.contents.fee_base_msat,
594 proportional_millionths: $channel.0.contents.fee_proportional_millionths,
596 cltv_expiry_delta: $channel.0.contents.cltv_expiry_delta,
597 htlc_minimum_msat: None,
598 htlc_maximum_msat: None,
601 src_node_id: phantom_route_hint.real_node_pubkey,
602 short_channel_id: phantom_route_hint.phantom_scid,
605 proportional_millionths: 0,
607 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
608 htlc_minimum_msat: None,
609 htlc_maximum_msat: None,
612 let scorer = test_utils::TestScorer::with_penalty(0);
613 let network_graph = $nodes[0].network_graph.read_only();
615 &$nodes[0].node.get_our_node_id(), &payment_params, &network_graph,
616 Some(&$nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
617 $amt, TEST_FINAL_CLTV, $nodes[0].logger, &scorer, &[0u8; 32]
618 ).unwrap(), phantom_route_hint.phantom_scid)
623 fn test_phantom_onion_hmac_failure() {
624 let chanmon_cfgs = create_chanmon_cfgs(2);
625 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
626 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
627 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
629 let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
632 let recv_value_msat = 10_000;
633 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
634 let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
636 // Route the HTLC through to the destination.
637 nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
638 check_added_monitors!(nodes[0], 1);
639 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
640 let mut update_add = update_0.update_add_htlcs[0].clone();
642 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
643 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
645 // Modify the payload so the phantom hop's HMAC is bogus.
646 let sha256_of_onion = {
647 let mut channel_state = nodes[1].node.channel_state.lock().unwrap();
648 let mut pending_forward = channel_state.forward_htlcs.get_mut(&phantom_scid).unwrap();
649 match pending_forward[0] {
650 HTLCForwardInfo::AddHTLC {
651 forward_info: PendingHTLCInfo {
652 routing: PendingHTLCRouting::Forward { ref mut onion_packet, .. },
656 onion_packet.hmac[onion_packet.hmac.len() - 1] ^= 1;
657 Sha256::hash(&onion_packet.hop_data).into_inner().to_vec()
659 _ => panic!("Unexpected forward"),
662 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
663 nodes[1].node.process_pending_htlc_forwards();
664 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
665 nodes[1].node.process_pending_htlc_forwards();
666 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
667 check_added_monitors!(&nodes[1], 1);
668 assert!(update_1.update_fail_htlcs.len() == 1);
669 let fail_msg = update_1.update_fail_htlcs[0].clone();
670 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
671 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
673 // Ensure the payment fails with the expected error.
674 let mut fail_conditions = PaymentFailedConditions::new()
675 .blamed_scid(phantom_scid)
676 .blamed_chan_closed(true)
677 .expected_htlc_error_data(0x8000 | 0x4000 | 5, &sha256_of_onion);
678 expect_payment_failed_conditions!(nodes[0], payment_hash, false, fail_conditions);
682 fn test_phantom_invalid_onion_payload() {
683 let chanmon_cfgs = create_chanmon_cfgs(2);
684 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
685 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
686 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
688 let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
691 let recv_value_msat = 10_000;
692 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
693 let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
695 // We'll use the session priv later when constructing an invalid onion packet.
696 let session_priv = [3; 32];
697 *nodes[0].keys_manager.override_random_bytes.lock().unwrap() = Some(session_priv);
698 nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
699 check_added_monitors!(nodes[0], 1);
700 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
701 let mut update_add = update_0.update_add_htlcs[0].clone();
703 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
704 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
706 // Modify the onion packet to have an invalid payment amount.
707 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
708 for f in pending_forwards.iter_mut() {
710 &mut HTLCForwardInfo::AddHTLC {
711 forward_info: PendingHTLCInfo {
712 routing: PendingHTLCRouting::Forward { ref mut onion_packet, .. },
716 // Construct the onion payloads for the entire route and an invalid amount.
717 let height = nodes[0].best_block_info().1;
718 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
719 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
720 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], msgs::MAX_VALUE_MSAT + 1, &Some(payment_secret), height + 1, &None).unwrap();
721 // We only want to construct the onion packet for the last hop, not the entire route, so
722 // remove the first hop's payload and its keys.
723 onion_keys.remove(0);
724 onion_payloads.remove(0);
726 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
727 onion_packet.hop_data = new_onion_packet.hop_data;
728 onion_packet.hmac = new_onion_packet.hmac;
730 _ => panic!("Unexpected forward"),
734 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
735 nodes[1].node.process_pending_htlc_forwards();
736 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
737 nodes[1].node.process_pending_htlc_forwards();
738 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
739 check_added_monitors!(&nodes[1], 1);
740 assert!(update_1.update_fail_htlcs.len() == 1);
741 let fail_msg = update_1.update_fail_htlcs[0].clone();
742 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
743 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
745 // Ensure the payment fails with the expected error.
746 let error_data = Vec::new();
747 let mut fail_conditions = PaymentFailedConditions::new()
748 .blamed_scid(phantom_scid)
749 .blamed_chan_closed(true)
750 .expected_htlc_error_data(0x4000 | 22, &error_data);
751 expect_payment_failed_conditions!(nodes[0], payment_hash, true, fail_conditions);
755 fn test_phantom_final_incorrect_cltv_expiry() {
756 let chanmon_cfgs = create_chanmon_cfgs(2);
757 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
758 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
759 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
761 let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
764 let recv_value_msat = 10_000;
765 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
766 let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
768 // Route the HTLC through to the destination.
769 nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
770 check_added_monitors!(nodes[0], 1);
771 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
772 let mut update_add = update_0.update_add_htlcs[0].clone();
774 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
775 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
777 // Modify the payload so the phantom hop's HMAC is bogus.
778 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
779 for f in pending_forwards.iter_mut() {
781 &mut HTLCForwardInfo::AddHTLC {
782 forward_info: PendingHTLCInfo { ref mut outgoing_cltv_value, .. }, ..
784 *outgoing_cltv_value += 1;
786 _ => panic!("Unexpected forward"),
790 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
791 nodes[1].node.process_pending_htlc_forwards();
792 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
793 nodes[1].node.process_pending_htlc_forwards();
794 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
795 check_added_monitors!(&nodes[1], 1);
796 assert!(update_1.update_fail_htlcs.len() == 1);
797 let fail_msg = update_1.update_fail_htlcs[0].clone();
798 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
799 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
801 // Ensure the payment fails with the expected error.
802 let expected_cltv = 82;
803 let error_data = byte_utils::be32_to_array(expected_cltv).to_vec();
804 let mut fail_conditions = PaymentFailedConditions::new()
805 .blamed_scid(phantom_scid)
806 .expected_htlc_error_data(18, &error_data);
807 expect_payment_failed_conditions!(nodes[0], payment_hash, false, fail_conditions);
811 fn test_phantom_failure_too_low_cltv() {
812 let chanmon_cfgs = create_chanmon_cfgs(2);
813 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
814 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
815 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
817 let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
820 let recv_value_msat = 10_000;
821 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
822 let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
824 // Modify the route to have a too-low cltv.
825 route.paths[0][1].cltv_expiry_delta = 5;
827 // Route the HTLC through to the destination.
828 nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
829 check_added_monitors!(nodes[0], 1);
830 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
831 let mut update_add = update_0.update_add_htlcs[0].clone();
833 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
834 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
836 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
837 nodes[1].node.process_pending_htlc_forwards();
838 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
839 nodes[1].node.process_pending_htlc_forwards();
840 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
841 check_added_monitors!(&nodes[1], 1);
842 assert!(update_1.update_fail_htlcs.len() == 1);
843 let fail_msg = update_1.update_fail_htlcs[0].clone();
844 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
845 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
847 // Ensure the payment fails with the expected error.
848 let error_data = Vec::new();
849 let mut fail_conditions = PaymentFailedConditions::new()
850 .blamed_scid(phantom_scid)
851 .expected_htlc_error_data(17, &error_data);
852 expect_payment_failed_conditions!(nodes[0], payment_hash, false, fail_conditions);
856 fn test_phantom_failure_too_low_recv_amt() {
857 let chanmon_cfgs = create_chanmon_cfgs(2);
858 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
859 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
860 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
862 let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
864 // Get the route with a too-low amount.
865 let recv_amt_msat = 10_000;
866 let bad_recv_amt_msat = recv_amt_msat - 10;
867 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_amt_msat));
868 let (mut route, phantom_scid) = get_phantom_route!(nodes, bad_recv_amt_msat, channel);
870 // Route the HTLC through to the destination.
871 nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
872 check_added_monitors!(nodes[0], 1);
873 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
874 let mut update_add = update_0.update_add_htlcs[0].clone();
876 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
877 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
879 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
880 nodes[1].node.process_pending_htlc_forwards();
881 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
882 nodes[1].node.process_pending_htlc_forwards();
883 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
884 nodes[1].node.process_pending_htlc_forwards();
885 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
886 check_added_monitors!(&nodes[1], 1);
887 assert!(update_1.update_fail_htlcs.len() == 1);
888 let fail_msg = update_1.update_fail_htlcs[0].clone();
889 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
890 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
892 // Ensure the payment fails with the expected error.
893 let mut error_data = byte_utils::be64_to_array(bad_recv_amt_msat).to_vec();
894 error_data.extend_from_slice(
895 &byte_utils::be32_to_array(nodes[1].node.best_block.read().unwrap().height()),
897 let mut fail_conditions = PaymentFailedConditions::new()
898 .blamed_scid(phantom_scid)
899 .expected_htlc_error_data(0x4000 | 15, &error_data);
900 expect_payment_failed_conditions!(nodes[0], payment_hash, true, fail_conditions);
904 fn test_phantom_dust_exposure_failure() {
905 // Set the max dust exposure to the dust limit.
906 let max_dust_exposure = 546;
907 let mut receiver_config = UserConfig::default();
908 receiver_config.channel_options.max_dust_htlc_exposure_msat = max_dust_exposure;
909 receiver_config.channel_options.announced_channel = true;
911 let chanmon_cfgs = create_chanmon_cfgs(2);
912 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
913 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(receiver_config)]);
914 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
916 let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
918 // Get the route with an amount exceeding the dust exposure threshold of nodes[1].
919 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(max_dust_exposure + 1));
920 let (mut route, _) = get_phantom_route!(nodes, max_dust_exposure + 1, channel);
922 // Route the HTLC through to the destination.
923 nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
924 check_added_monitors!(nodes[0], 1);
925 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
926 let mut update_add = update_0.update_add_htlcs[0].clone();
928 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
929 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
931 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
932 assert!(update_1.update_fail_htlcs.len() == 1);
933 let fail_msg = update_1.update_fail_htlcs[0].clone();
934 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
935 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
937 // Ensure the payment fails with the expected error.
938 let mut error_data = channel.1.encode_with_len();
939 let mut fail_conditions = PaymentFailedConditions::new()
940 .blamed_scid(channel.0.contents.short_channel_id)
941 .blamed_chan_closed(false)
942 .expected_htlc_error_data(0x1000 | 7, &error_data);
943 expect_payment_failed_conditions!(nodes[0], payment_hash, false, fail_conditions);
947 fn test_phantom_failure_reject_payment() {
948 // Test that the user can successfully fail back a phantom node payment.
949 let chanmon_cfgs = create_chanmon_cfgs(2);
950 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
951 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
952 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
954 let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
956 // Get the route with a too-low amount.
957 let recv_amt_msat = 10_000;
958 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_amt_msat));
959 let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_amt_msat, channel);
961 // Route the HTLC through to the destination.
962 nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
963 check_added_monitors!(nodes[0], 1);
964 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
965 let mut update_add = update_0.update_add_htlcs[0].clone();
967 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
968 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
970 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
971 nodes[1].node.process_pending_htlc_forwards();
972 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
973 nodes[1].node.process_pending_htlc_forwards();
974 expect_payment_received!(nodes[1], payment_hash, payment_secret, recv_amt_msat);
975 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash));
976 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
977 nodes[1].node.process_pending_htlc_forwards();
979 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
980 check_added_monitors!(&nodes[1], 1);
981 assert!(update_1.update_fail_htlcs.len() == 1);
982 let fail_msg = update_1.update_fail_htlcs[0].clone();
983 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
984 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
986 // Ensure the payment fails with the expected error.
987 let mut error_data = byte_utils::be64_to_array(recv_amt_msat).to_vec();
988 error_data.extend_from_slice(
989 &byte_utils::be32_to_array(nodes[1].node.best_block.read().unwrap().height()),
991 let mut fail_conditions = PaymentFailedConditions::new()
992 .blamed_scid(phantom_scid)
993 .expected_htlc_error_data(0x4000 | 15, &error_data);
994 expect_payment_failed_conditions!(nodes[0], payment_hash, true, fail_conditions);