Add tests for defaulting to creating tlv onions
[rust-lightning] / lightning / src / ln / onion_route_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests of the onion error messages/codes which are returned when routing a payment fails.
11 //! These tests work by standing up full nodes and route payments across the network, checking the
12 //! returned errors decode to the correct thing.
13
14 use chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
15 use chain::keysinterface::{KeysInterface, Recipient};
16 use ln::{PaymentHash, PaymentSecret};
17 use ln::channelmanager::{HTLCForwardInfo, CLTV_FAR_FAR_AWAY, MIN_CLTV_EXPIRY_DELTA, PendingHTLCInfo, PendingHTLCRouting};
18 use ln::onion_utils;
19 use routing::network_graph::{NetworkUpdate, RoutingFees, NodeId};
20 use routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintHop};
21 use ln::features::{InitFeatures, InvoiceFeatures, NodeFeatures};
22 use ln::msgs;
23 use ln::msgs::{ChannelMessageHandler, ChannelUpdate, OptionalField};
24 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider};
25 use util::ser::{Writeable, Writer};
26 use util::{byte_utils, test_utils};
27 use util::config::UserConfig;
28
29 use bitcoin::hash_types::BlockHash;
30
31 use bitcoin::hashes::Hash;
32 use bitcoin::hashes::sha256::Hash as Sha256;
33
34 use bitcoin::secp256k1;
35 use bitcoin::secp256k1::Secp256k1;
36 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
37
38 use io;
39 use prelude::*;
40 use core::default::Default;
41
42 use ln::functional_test_utils::*;
43
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),
46                                 F2: FnMut(),
47 {
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);
49 }
50
51 // test_case
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),
61                                 F3: FnMut(),
62 {
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);
67                         match events[0] {
68                                 $event_type { .. } => {},
69                                 _ => panic!("Unexpected event"),
70                         }
71                 }}
72         }
73
74         macro_rules! expect_htlc_forward {
75                 ($node: expr) => {{
76                         expect_event!($node, Event::PendingHTLCsForwardable);
77                         $node.node.process_pending_htlc_forwards();
78                 }}
79         }
80
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);
89                 callback_node();
90         }
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);
94
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));
99                         update_1_0
100                 },
101                 1|2|3|200 => { // final node failure; forwarding to 2
102                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
103                         // forwarding on 1
104                         if test_case != 200 {
105                                 callback_node();
106                         }
107                         expect_htlc_forward!(&nodes[1]);
108
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);
116                         }
117
118                         // 1 => 2
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);
121
122                         if test_case == 2 || test_case == 200 {
123                                 expect_htlc_forward!(&nodes[2]);
124                                 expect_event!(&nodes[2], Event::PaymentReceived);
125                                 callback_node();
126                                 expect_pending_htlcs_forwardable!(nodes[2]);
127                         }
128
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);
132                         }
133                         assert!(update_2_1.update_fail_htlcs.len() == 1);
134
135                         let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
136                         if test_case == 200 {
137                                 callback_fail(&mut fail_msg);
138                         }
139
140                         // 2 => 1
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);
143
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);
147                         update_1_0
148                 },
149                 _ => unreachable!(),
150         };
151
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);
157                 }
158                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
159         } else {
160                 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]);
161         };
162
163         commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
164
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!");
177                                                 }
178                                         },
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);
183                                                 } else {
184                                                         panic!("Unexpected message event");
185                                                 }
186                                         },
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);
191                                                 } else {
192                                                         panic!("Unexpected message event");
193                                                 }
194                                         },
195                                 }
196                                 None => panic!("Expected channel update"),
197                         }
198                 } else {
199                         assert!(network_update.is_none());
200                 }
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"),
205                         }
206                 } else {
207                         assert!(short_channel_id.is_none());
208                 }
209         } else {
210                 panic!("Unexpected event");
211         }
212 }
213
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][..]),
222                                 short_channel_id,
223                                 timestamp: 0,
224                                 flags: 0,
225                                 cltv_expiry_delta: 0,
226                                 htlc_minimum_msat: 0,
227                                 htlc_maximum_msat: OptionalField::Absent,
228                                 fee_base_msat: 0,
229                                 fee_proportional_millionths: 0,
230                                 excess_data: vec![],
231                         }
232                 }
233         }
234 }
235
236 struct BogusOnionHopData {
237         data: Vec<u8>
238 }
239 impl BogusOnionHopData {
240         fn new(orig: msgs::OnionHopData) -> Self {
241                 Self { data: orig.encode() }
242         }
243 }
244 impl Writeable for BogusOnionHopData {
245         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
246                 writer.write_all(&self.data[..])
247         }
248 }
249
250 const BADONION: u16 = 0x8000;
251 const PERM: u16 = 0x4000;
252 const NODE: u16 = 0x2000;
253 const UPDATE: u16 = 0x1000;
254
255 #[test]
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
259         // forwarding.
260         //
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;
265
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())];
271
272         // positive case
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);
278
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));
286
287         // In an earlier version, we spuriously failed to forward payments if the expected feerate
288         // changed between the channel open and the payment.
289         {
290                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
291                 *feerate_lock *= 2;
292         }
293
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);
299 }
300
301 #[test]
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;
312
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;
317
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]);
325         }
326         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 40000);
327         // positive case
328         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000);
329
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));
340                 }
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));
346
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));
357                 }
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));
363
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| {
368                 // trigger error
369                 msg.amount_msat -= 1;
370         }, |msg| {
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));
376
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]);
383         }, ||{
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]);
387
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;
391         }, |msg| {
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));
396
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]);
402         }, ||{
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]);
406
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;
410         }, |msg| {
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]);
414         }, ||{
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));
417
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]);
423         }, ||{
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]);
427
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));
433
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));
436
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));
439
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;
443         }, |msg| {
444                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
445                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
446                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[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));
448
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;
452         }, |msg| {
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));
458
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;
462         }, |msg| {
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));
468
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));
474
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));
481
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();
485         }
486
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);
491
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));
498
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));
504
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));
512
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]);
517
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);
524
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() {
528                                 match f {
529                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
530                                                 forward_info.outgoing_cltv_value += 1,
531                                         _ => {},
532                                 }
533                         }
534                 }
535         }, true, Some(18), None, Some(channels[1].0.contents.short_channel_id));
536
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() {
541                                 match f {
542                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
543                                                 forward_info.amt_to_forward -= 1,
544                                         _ => {},
545                                 }
546                         }
547                 }
548         }, true, Some(19), None, Some(channels[1].0.contents.short_channel_id));
549
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));
557
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));
569
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]);
575         }, ||{
576                 nodes[2].node.fail_htlc_backwards(&payment_hash);
577         }, true, Some(23), None, None);
578 }
579
580 #[test]
581 fn test_default_to_onion_payload_tlv_format() {
582         // Tests that we default to creating tlv format onion payloads when no `NodeAnnouncementInfo`
583         // `features` for a node in the `network_graph` exists, or when the node isn't in the
584         // `network_graph`, and no other known `features` for the node exists.
585         let mut priv_channels_conf = UserConfig::default();
586         priv_channels_conf.channel_options.announced_channel = false;
587         let chanmon_cfgs = create_chanmon_cfgs(5);
588         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
589         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, Some(priv_channels_conf)]);
590         let mut nodes = create_network(5, &node_cfgs, &node_chanmgrs);
591
592         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
593         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
594         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
595         create_unannounced_chan_between_nodes_with_value(&nodes, 3, 4, 100000, 10001, InitFeatures::known(), InitFeatures::known());
596
597         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id());
598         let origin_node = &nodes[0];
599         let network_graph = origin_node.network_graph;
600
601         // Clears all the `NodeAnnouncementInfo` for all nodes of `nodes[0]`'s `network_graph`, so that
602         // their `features` aren't used when creating the `route`.
603         network_graph.clear_nodes_announcement_info();
604
605         let (announced_route, _, _, _) = get_route_and_payment_hash!(
606                 origin_node, nodes[3], payment_params, 10_000, TEST_FINAL_CLTV);
607
608         let hops = &announced_route.paths[0];
609         // Assert that the hop between `nodes[1]` and `nodes[2]` defaults to supporting variable length
610         // onions, as `nodes[0]` has no `NodeAnnouncementInfo` `features` for `node[2]`
611         assert!(hops[1].node_features.supports_variable_length_onion());
612         // Assert that the hop between `nodes[2]` and `nodes[3]` defaults to supporting variable length
613         // onions, as `nodes[0]` has no `NodeAnnouncementInfo` `features` for `node[3]`, and no `InvoiceFeatures`
614         // for the `payment_params`, which would otherwise have been used.
615         assert!(hops[2].node_features.supports_variable_length_onion());
616         // Note that we do not assert that `hops[0]` (the channel between `nodes[0]` and `nodes[1]`)
617         // supports variable length onions, as the `InitFeatures` exchanged in the init message
618         // between the nodes will be used when creating the route. We therefore do not default to
619         // supporting variable length onions for that hop, as the `InitFeatures` in this case are
620         // `InitFeatures::known()`.
621
622         let unannounced_chan = &nodes[4].node.list_usable_channels()[0];
623
624         let last_hop = RouteHint(vec![RouteHintHop {
625                 src_node_id: nodes[3].node.get_our_node_id(),
626                 short_channel_id: unannounced_chan.short_channel_id.unwrap(),
627                 fees: RoutingFees {
628                         base_msat: 0,
629                         proportional_millionths: 0,
630                 },
631                 cltv_expiry_delta: 42,
632                 htlc_minimum_msat: None,
633                 htlc_maximum_msat: None,
634         }]);
635
636         let unannounced_chan_params = PaymentParameters::from_node_id(nodes[4].node.get_our_node_id()).with_route_hints(vec![last_hop]);
637         let (unannounced_route, _, _, _) = get_route_and_payment_hash!(
638                 origin_node, nodes[4], unannounced_chan_params, 10_000, TEST_FINAL_CLTV);
639
640         let unannounced_chan_hop = &unannounced_route.paths[0][3];
641         // Ensure that `nodes[4]` doesn't exist in `nodes[0]`'s `network_graph`, as it's not public.
642         assert!(&network_graph.read_only().nodes().get(&NodeId::from_pubkey(&nodes[4].node.get_our_node_id())).is_none());
643         // Assert that the hop between `nodes[3]` and `nodes[4]` defaults to supporting variable length
644         // onions, even though `nodes[4]` as `nodes[0]` doesn't exists in `nodes[0]`'s `network_graph`,
645         // and no `InvoiceFeatures` for the `payment_params` exists, which would otherwise have been
646         // used.
647         assert!(unannounced_chan_hop.node_features.supports_variable_length_onion());
648
649         let cur_height = nodes[0].best_block_info().1 + 1;
650         let (announced_route_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&announced_route.paths[0], 40000, &None, cur_height, &None).unwrap();
651         let (unannounced_route_paylods, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&unannounced_route.paths[0], 40000, &None, cur_height, &None).unwrap();
652
653         for onion_payloads in vec![announced_route_payloads, unannounced_route_paylods] {
654                 for onion_payload in onion_payloads.iter() {
655                         match onion_payload.format {
656                                 msgs::OnionHopDataFormat::Legacy {..} => {
657                                         panic!("Generated a `msgs::OnionHopDataFormat::Legacy` payload, even though that shouldn't have happend.");
658                                 }
659                                 _ => {}
660                         }
661                 }
662         }
663 }
664
665 #[test]
666 fn test_do_not_default_to_onion_payload_tlv_format_when_unsupported() {
667         // Tests that we do not default to creating tlv onions if either of these types features
668         // exists, which specifies no support for variable length onions for a specific hop, when
669         // creating a route:
670         // 1. `InitFeatures` to the counterparty node exchanged with the init message to the node.
671         // 2. `NodeFeatures` in the `NodeAnnouncementInfo` of a node in sender node's `network_graph`.
672         // 3. `InvoiceFeatures` specified by the receiving node, when no `NodeAnnouncementInfo`
673         // `features` exists for the receiver in the sender's `network_graph`.
674         let chanmon_cfgs = create_chanmon_cfgs(4);
675         let mut node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
676
677         // Set `node[1]` config to `InitFeatures::empty()` which return `false` for
678         // `supports_variable_length_onion()`
679         let mut node_1_cfg = &mut node_cfgs[1];
680         node_1_cfg.features = InitFeatures::empty();
681
682         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
683         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
684
685         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
686         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
687         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
688
689         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
690                 .with_features(InvoiceFeatures::empty());
691         let origin_node = &nodes[0];
692         let network_graph = origin_node.network_graph;
693         network_graph.clear_nodes_announcement_info();
694
695         // Set `NodeAnnouncementInfo` `features` which do not support variable length onions for
696         // `nodes[2]` in `nodes[0]`'s `network_graph`.
697         let nodes_2_unsigned_node_announcement = msgs::UnsignedNodeAnnouncement {
698                 features: NodeFeatures::empty(),
699                 timestamp: 0,
700                 node_id: nodes[2].node.get_our_node_id(),
701                 rgb: [32; 3],
702                 alias: [16;32],
703                 addresses: Vec::new(),
704                 excess_address_data: Vec::new(),
705                 excess_data: Vec::new(),
706         };
707         let _res = network_graph.update_node_from_unsigned_announcement(&nodes_2_unsigned_node_announcement);
708
709         let (route, _, _, _) = get_route_and_payment_hash!(
710                 origin_node, nodes[3], payment_params, 10_000, TEST_FINAL_CLTV);
711
712         let hops = &route.paths[0];
713
714         // Assert that the hop between `nodes[0]` and `nodes[1]` doesn't support variable length
715         // onions, as as the `InitFeatures` exchanged (`InitFeatures::empty()`) in the init message
716         // between the nodes when setting up the channel is used when creating the `route` and that we
717         // therefore do not default to supporting variable length onions. Despite `nodes[0]` having no
718         // `NodeAnnouncementInfo` `features` for `node[1]`.
719         assert!(!hops[0].node_features.supports_variable_length_onion());
720         // Assert that the hop between `nodes[1]` and `nodes[2]` uses the `features` from
721         // `nodes_2_unsigned_node_announcement` that doesn't support variable length onions.
722         assert!(!hops[1].node_features.supports_variable_length_onion());
723         // Assert that the hop between `nodes[2]` and `nodes[3]` uses the `InvoiceFeatures` set to the
724         // `payment_params`, that doesn't support variable length onions. We therefore do not end up
725         // defaulting to supporting variable length onions, despite `nodes[0]` having no
726         // `NodeAnnouncementInfo` `features` for `node[3]`.
727         assert!(!hops[2].node_features.supports_variable_length_onion());
728
729         let cur_height = nodes[0].best_block_info().1 + 1;
730         let (onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height, &None).unwrap();
731
732         for onion_payload in onion_payloads.iter() {
733                 match onion_payload.format {
734                         msgs::OnionHopDataFormat::Legacy {..} => {}
735                         _ => {
736                                 panic!("Should have only have generated `msgs::OnionHopDataFormat::Legacy` payloads");
737                         }
738                 }
739         }
740 }
741
742 macro_rules! get_phantom_route {
743         ($nodes: expr, $amt: expr, $channel: expr) => {{
744                 let secp_ctx = Secp256k1::new();
745                 let phantom_secret = $nodes[1].keys_manager.get_node_secret(Recipient::PhantomNode).unwrap();
746                 let phantom_pubkey = PublicKey::from_secret_key(&secp_ctx, &phantom_secret);
747                 let phantom_route_hint = $nodes[1].node.get_phantom_route_hints();
748                 let payment_params = PaymentParameters::from_node_id(phantom_pubkey)
749                         .with_features(InvoiceFeatures::known())
750                         .with_route_hints(vec![RouteHint(vec![
751                                         RouteHintHop {
752                                                 src_node_id: $nodes[0].node.get_our_node_id(),
753                                                 short_channel_id: $channel.0.contents.short_channel_id,
754                                                 fees: RoutingFees {
755                                                         base_msat: $channel.0.contents.fee_base_msat,
756                                                         proportional_millionths: $channel.0.contents.fee_proportional_millionths,
757                                                 },
758                                                 cltv_expiry_delta: $channel.0.contents.cltv_expiry_delta,
759                                                 htlc_minimum_msat: None,
760                                                 htlc_maximum_msat: None,
761                                         },
762                                         RouteHintHop {
763                                                 src_node_id: phantom_route_hint.real_node_pubkey,
764                                                 short_channel_id: phantom_route_hint.phantom_scid,
765                                                 fees: RoutingFees {
766                                                         base_msat: 0,
767                                                         proportional_millionths: 0,
768                                                 },
769                                                 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
770                                                 htlc_minimum_msat: None,
771                                                 htlc_maximum_msat: None,
772                                         }
773                 ])]);
774                 let scorer = test_utils::TestScorer::with_penalty(0);
775                 let network_graph = $nodes[0].network_graph.read_only();
776                 (get_route(
777                         &$nodes[0].node.get_our_node_id(), &payment_params, &network_graph,
778                         Some(&$nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
779                         $amt, TEST_FINAL_CLTV, $nodes[0].logger, &scorer, &[0u8; 32]
780                 ).unwrap(), phantom_route_hint.phantom_scid)
781         }
782 }}
783
784 #[test]
785 fn test_phantom_onion_hmac_failure() {
786         let chanmon_cfgs = create_chanmon_cfgs(2);
787         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
788         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
789         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
790
791         let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
792
793         // Get the route.
794         let recv_value_msat = 10_000;
795         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
796         let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
797
798         // Route the HTLC through to the destination.
799         nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
800         check_added_monitors!(nodes[0], 1);
801         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
802         let mut update_add = update_0.update_add_htlcs[0].clone();
803
804         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
805         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
806
807         // Modify the payload so the phantom hop's HMAC is bogus.
808         let sha256_of_onion = {
809                 let mut channel_state = nodes[1].node.channel_state.lock().unwrap();
810                 let mut pending_forward = channel_state.forward_htlcs.get_mut(&phantom_scid).unwrap();
811                 match pending_forward[0] {
812                         HTLCForwardInfo::AddHTLC {
813                                 forward_info: PendingHTLCInfo {
814                                         routing: PendingHTLCRouting::Forward { ref mut onion_packet, .. },
815                                         ..
816                                 }, ..
817                         } => {
818                                 onion_packet.hmac[onion_packet.hmac.len() - 1] ^= 1;
819                                 Sha256::hash(&onion_packet.hop_data).into_inner().to_vec()
820                         },
821                         _ => panic!("Unexpected forward"),
822                 }
823         };
824         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
825         nodes[1].node.process_pending_htlc_forwards();
826         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
827         nodes[1].node.process_pending_htlc_forwards();
828         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
829         check_added_monitors!(&nodes[1], 1);
830         assert!(update_1.update_fail_htlcs.len() == 1);
831         let fail_msg = update_1.update_fail_htlcs[0].clone();
832         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
833         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
834
835         // Ensure the payment fails with the expected error.
836         let mut fail_conditions = PaymentFailedConditions::new()
837                 .blamed_scid(phantom_scid)
838                 .blamed_chan_closed(true)
839                 .expected_htlc_error_data(0x8000 | 0x4000 | 5, &sha256_of_onion);
840         expect_payment_failed_conditions!(nodes[0], payment_hash, false, fail_conditions);
841 }
842
843 #[test]
844 fn test_phantom_invalid_onion_payload() {
845         let chanmon_cfgs = create_chanmon_cfgs(2);
846         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
847         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
848         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
849
850         let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
851
852         // Get the route.
853         let recv_value_msat = 10_000;
854         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
855         let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
856
857         // We'll use the session priv later when constructing an invalid onion packet.
858         let session_priv = [3; 32];
859         *nodes[0].keys_manager.override_random_bytes.lock().unwrap() = Some(session_priv);
860         nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
861         check_added_monitors!(nodes[0], 1);
862         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
863         let mut update_add = update_0.update_add_htlcs[0].clone();
864
865         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
866         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
867
868         // Modify the onion packet to have an invalid payment amount.
869         for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
870                 for f in pending_forwards.iter_mut() {
871                         match f {
872                                 &mut HTLCForwardInfo::AddHTLC {
873                                         forward_info: PendingHTLCInfo {
874                                                 routing: PendingHTLCRouting::Forward { ref mut onion_packet, .. },
875                                                 ..
876                                         }, ..
877                                 } => {
878                                         // Construct the onion payloads for the entire route and an invalid amount.
879                                         let height = nodes[0].best_block_info().1;
880                                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
881                                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
882                                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], msgs::MAX_VALUE_MSAT + 1, &Some(payment_secret), height + 1, &None).unwrap();
883                                         // We only want to construct the onion packet for the last hop, not the entire route, so
884                                         // remove the first hop's payload and its keys.
885                                         onion_keys.remove(0);
886                                         onion_payloads.remove(0);
887
888                                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
889                                         onion_packet.hop_data = new_onion_packet.hop_data;
890                                         onion_packet.hmac = new_onion_packet.hmac;
891                                 },
892                                 _ => panic!("Unexpected forward"),
893                         }
894                 }
895         }
896         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
897         nodes[1].node.process_pending_htlc_forwards();
898         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
899         nodes[1].node.process_pending_htlc_forwards();
900         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
901         check_added_monitors!(&nodes[1], 1);
902         assert!(update_1.update_fail_htlcs.len() == 1);
903         let fail_msg = update_1.update_fail_htlcs[0].clone();
904         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
905         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
906
907         // Ensure the payment fails with the expected error.
908         let error_data = Vec::new();
909         let mut fail_conditions = PaymentFailedConditions::new()
910                 .blamed_scid(phantom_scid)
911                 .blamed_chan_closed(true)
912                 .expected_htlc_error_data(0x4000 | 22, &error_data);
913         expect_payment_failed_conditions!(nodes[0], payment_hash, true, fail_conditions);
914 }
915
916 #[test]
917 fn test_phantom_final_incorrect_cltv_expiry() {
918         let chanmon_cfgs = create_chanmon_cfgs(2);
919         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
920         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
921         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
922
923         let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
924
925         // Get the route.
926         let recv_value_msat = 10_000;
927         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
928         let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
929
930         // Route the HTLC through to the destination.
931         nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
932         check_added_monitors!(nodes[0], 1);
933         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
934         let mut update_add = update_0.update_add_htlcs[0].clone();
935
936         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
937         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
938
939         // Modify the payload so the phantom hop's HMAC is bogus.
940         for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
941                 for f in pending_forwards.iter_mut() {
942                         match f {
943                                 &mut HTLCForwardInfo::AddHTLC {
944                                         forward_info: PendingHTLCInfo { ref mut outgoing_cltv_value, .. }, ..
945                                 } => {
946                                         *outgoing_cltv_value += 1;
947                                 },
948                                 _ => panic!("Unexpected forward"),
949                         }
950                 }
951         }
952         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
953         nodes[1].node.process_pending_htlc_forwards();
954         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
955         nodes[1].node.process_pending_htlc_forwards();
956         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
957         check_added_monitors!(&nodes[1], 1);
958         assert!(update_1.update_fail_htlcs.len() == 1);
959         let fail_msg = update_1.update_fail_htlcs[0].clone();
960         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
961         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
962
963         // Ensure the payment fails with the expected error.
964         let expected_cltv = 82;
965         let error_data = byte_utils::be32_to_array(expected_cltv).to_vec();
966         let mut fail_conditions = PaymentFailedConditions::new()
967                 .blamed_scid(phantom_scid)
968                 .expected_htlc_error_data(18, &error_data);
969         expect_payment_failed_conditions!(nodes[0], payment_hash, false, fail_conditions);
970 }
971
972 #[test]
973 fn test_phantom_failure_too_low_cltv() {
974         let chanmon_cfgs = create_chanmon_cfgs(2);
975         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
976         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
977         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
978
979         let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
980
981         // Get the route.
982         let recv_value_msat = 10_000;
983         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
984         let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
985
986         // Modify the route to have a too-low cltv.
987         route.paths[0][1].cltv_expiry_delta = 5;
988
989         // Route the HTLC through to the destination.
990         nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
991         check_added_monitors!(nodes[0], 1);
992         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
993         let mut update_add = update_0.update_add_htlcs[0].clone();
994
995         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
996         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
997
998         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
999         nodes[1].node.process_pending_htlc_forwards();
1000         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1001         nodes[1].node.process_pending_htlc_forwards();
1002         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1003         check_added_monitors!(&nodes[1], 1);
1004         assert!(update_1.update_fail_htlcs.len() == 1);
1005         let fail_msg = update_1.update_fail_htlcs[0].clone();
1006         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1007         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1008
1009         // Ensure the payment fails with the expected error.
1010         let error_data = Vec::new();
1011         let mut fail_conditions = PaymentFailedConditions::new()
1012                 .blamed_scid(phantom_scid)
1013                 .expected_htlc_error_data(17, &error_data);
1014         expect_payment_failed_conditions!(nodes[0], payment_hash, false, fail_conditions);
1015 }
1016
1017 #[test]
1018 fn test_phantom_failure_too_low_recv_amt() {
1019         let chanmon_cfgs = create_chanmon_cfgs(2);
1020         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1021         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1022         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1023
1024         let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1025
1026         // Get the route with a too-low amount.
1027         let recv_amt_msat = 10_000;
1028         let bad_recv_amt_msat = recv_amt_msat - 10;
1029         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_amt_msat));
1030         let (mut route, phantom_scid) = get_phantom_route!(nodes, bad_recv_amt_msat, channel);
1031
1032         // Route the HTLC through to the destination.
1033         nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
1034         check_added_monitors!(nodes[0], 1);
1035         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1036         let mut update_add = update_0.update_add_htlcs[0].clone();
1037
1038         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1039         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1040
1041         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1042         nodes[1].node.process_pending_htlc_forwards();
1043         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1044         nodes[1].node.process_pending_htlc_forwards();
1045         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1046         nodes[1].node.process_pending_htlc_forwards();
1047         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1048         check_added_monitors!(&nodes[1], 1);
1049         assert!(update_1.update_fail_htlcs.len() == 1);
1050         let fail_msg = update_1.update_fail_htlcs[0].clone();
1051         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1052         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1053
1054         // Ensure the payment fails with the expected error.
1055         let mut error_data = byte_utils::be64_to_array(bad_recv_amt_msat).to_vec();
1056         error_data.extend_from_slice(
1057                 &byte_utils::be32_to_array(nodes[1].node.best_block.read().unwrap().height()),
1058         );
1059         let mut fail_conditions = PaymentFailedConditions::new()
1060                 .blamed_scid(phantom_scid)
1061                 .expected_htlc_error_data(0x4000 | 15, &error_data);
1062         expect_payment_failed_conditions!(nodes[0], payment_hash, true, fail_conditions);
1063 }
1064
1065 #[test]
1066 fn test_phantom_dust_exposure_failure() {
1067         // Set the max dust exposure to the dust limit.
1068         let max_dust_exposure = 546;
1069         let mut receiver_config = UserConfig::default();
1070         receiver_config.channel_options.max_dust_htlc_exposure_msat = max_dust_exposure;
1071         receiver_config.channel_options.announced_channel = true;
1072
1073         let chanmon_cfgs = create_chanmon_cfgs(2);
1074         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1075         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(receiver_config)]);
1076         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1077
1078         let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1079
1080         // Get the route with an amount exceeding the dust exposure threshold of nodes[1].
1081         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(max_dust_exposure + 1));
1082         let (mut route, _) = get_phantom_route!(nodes, max_dust_exposure + 1, channel);
1083
1084         // Route the HTLC through to the destination.
1085         nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
1086         check_added_monitors!(nodes[0], 1);
1087         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1088         let mut update_add = update_0.update_add_htlcs[0].clone();
1089
1090         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1091         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1092
1093         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1094         assert!(update_1.update_fail_htlcs.len() == 1);
1095         let fail_msg = update_1.update_fail_htlcs[0].clone();
1096         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1097         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1098
1099         // Ensure the payment fails with the expected error.
1100         let mut error_data = channel.1.encode_with_len();
1101         let mut fail_conditions = PaymentFailedConditions::new()
1102                 .blamed_scid(channel.0.contents.short_channel_id)
1103                 .blamed_chan_closed(false)
1104                 .expected_htlc_error_data(0x1000 | 7, &error_data);
1105                 expect_payment_failed_conditions!(nodes[0], payment_hash, false, fail_conditions);
1106 }
1107
1108 #[test]
1109 fn test_phantom_failure_reject_payment() {
1110         // Test that the user can successfully fail back a phantom node payment.
1111         let chanmon_cfgs = create_chanmon_cfgs(2);
1112         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1113         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1114         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1115
1116         let channel = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1117
1118         // Get the route with a too-low amount.
1119         let recv_amt_msat = 10_000;
1120         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_amt_msat));
1121         let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_amt_msat, channel);
1122
1123         // Route the HTLC through to the destination.
1124         nodes[0].node.send_payment(&route, payment_hash.clone(), &Some(payment_secret)).unwrap();
1125         check_added_monitors!(nodes[0], 1);
1126         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1127         let mut update_add = update_0.update_add_htlcs[0].clone();
1128
1129         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1130         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1131
1132         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1133         nodes[1].node.process_pending_htlc_forwards();
1134         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1135         nodes[1].node.process_pending_htlc_forwards();
1136         expect_payment_received!(nodes[1], payment_hash, payment_secret, recv_amt_msat);
1137         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash));
1138         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1139         nodes[1].node.process_pending_htlc_forwards();
1140
1141         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1142         check_added_monitors!(&nodes[1], 1);
1143         assert!(update_1.update_fail_htlcs.len() == 1);
1144         let fail_msg = update_1.update_fail_htlcs[0].clone();
1145         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1146         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1147
1148         // Ensure the payment fails with the expected error.
1149         let mut error_data = byte_utils::be64_to_array(recv_amt_msat).to_vec();
1150         error_data.extend_from_slice(
1151                 &byte_utils::be32_to_array(nodes[1].node.best_block.read().unwrap().height()),
1152         );
1153         let mut fail_conditions = PaymentFailedConditions::new()
1154                 .blamed_scid(phantom_scid)
1155                 .expected_htlc_error_data(0x4000 | 15, &error_data);
1156         expect_payment_failed_conditions!(nodes[0], payment_hash, true, fail_conditions);
1157 }