Use known InvoiceFeatures for routing in tests
[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 ln::channelmanager::{HTLCForwardInfo, PaymentPreimage, PaymentHash};
16 use ln::onion_utils;
17 use routing::router::{Route, get_route};
18 use ln::features::{InitFeatures, InvoiceFeatures};
19 use ln::msgs;
20 use ln::msgs::{ChannelMessageHandler, HTLCFailChannelUpdate, OptionalField};
21 use util::test_utils;
22 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
23 use util::ser::{Writeable, Writer};
24 use util::config::UserConfig;
25
26 use bitcoin::hash_types::BlockHash;
27
28 use bitcoin::hashes::sha256::Hash as Sha256;
29 use bitcoin::hashes::Hash;
30
31 use bitcoin::secp256k1::Secp256k1;
32 use bitcoin::secp256k1::key::SecretKey;
33
34 use std::default::Default;
35 use std::io;
36
37 use ln::functional_test_utils::*;
38
39 fn run_onion_failure_test<F1,F2>(_name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash, callback_msg: F1, callback_node: F2, expected_retryable: bool, expected_error_code: Option<u16>, expected_channel_update: Option<HTLCFailChannelUpdate>)
40         where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
41                                 F2: FnMut(),
42 {
43         run_onion_failure_test_with_fail_intercept(_name, test_case, nodes, route, payment_hash, callback_msg, |_|{}, callback_node, expected_retryable, expected_error_code, expected_channel_update);
44 }
45
46 // test_case
47 // 0: node1 fails backward
48 // 1: final node fails backward
49 // 2: payment completed but the user rejects the payment
50 // 3: final node fails backward (but tamper onion payloads from node0)
51 // 100: trigger error in the intermediate node and tamper returning fail_htlc
52 // 200: trigger error in the final node and tamper returning fail_htlc
53 fn run_onion_failure_test_with_fail_intercept<F1,F2,F3>(_name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash, mut callback_msg: F1, mut callback_fail: F2, mut callback_node: F3, expected_retryable: bool, expected_error_code: Option<u16>, expected_channel_update: Option<HTLCFailChannelUpdate>)
54         where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
55                                 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
56                                 F3: FnMut(),
57 {
58         macro_rules! expect_event {
59                 ($node: expr, $event_type: path) => {{
60                         let events = $node.node.get_and_clear_pending_events();
61                         assert_eq!(events.len(), 1);
62                         match events[0] {
63                                 $event_type { .. } => {},
64                                 _ => panic!("Unexpected event"),
65                         }
66                 }}
67         }
68
69         macro_rules! expect_htlc_forward {
70                 ($node: expr) => {{
71                         expect_event!($node, Event::PendingHTLCsForwardable);
72                         $node.node.process_pending_htlc_forwards();
73                 }}
74         }
75
76         // 0 ~~> 2 send payment
77         nodes[0].node.send_payment(&route, payment_hash.clone(), &None).unwrap();
78         check_added_monitors!(nodes[0], 1);
79         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
80         // temper update_add (0 => 1)
81         let mut update_add_0 = update_0.update_add_htlcs[0].clone();
82         if test_case == 0 || test_case == 3 || test_case == 100 {
83                 callback_msg(&mut update_add_0);
84                 callback_node();
85         }
86         // 0 => 1 update_add & CS
87         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
88         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
89
90         let update_1_0 = match test_case {
91                 0|100 => { // intermediate node failure; fail backward to 0
92                         let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
93                         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));
94                         update_1_0
95                 },
96                 1|2|3|200 => { // final node failure; forwarding to 2
97                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
98                         // forwarding on 1
99                         if test_case != 200 {
100                                 callback_node();
101                         }
102                         expect_htlc_forward!(&nodes[1]);
103
104                         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
105                         check_added_monitors!(&nodes[1], 1);
106                         assert_eq!(update_1.update_add_htlcs.len(), 1);
107                         // tamper update_add (1 => 2)
108                         let mut update_add_1 = update_1.update_add_htlcs[0].clone();
109                         if test_case != 3 && test_case != 200 {
110                                 callback_msg(&mut update_add_1);
111                         }
112
113                         // 1 => 2
114                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
115                         commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
116
117                         if test_case == 2 || test_case == 200 {
118                                 expect_htlc_forward!(&nodes[2]);
119                                 expect_event!(&nodes[2], Event::PaymentReceived);
120                                 callback_node();
121                                 expect_pending_htlcs_forwardable!(nodes[2]);
122                         }
123
124                         let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
125                         if test_case == 2 || test_case == 200 {
126                                 check_added_monitors!(&nodes[2], 1);
127                         }
128                         assert!(update_2_1.update_fail_htlcs.len() == 1);
129
130                         let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
131                         if test_case == 200 {
132                                 callback_fail(&mut fail_msg);
133                         }
134
135                         // 2 => 1
136                         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg);
137                         commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
138
139                         // backward fail on 1
140                         let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
141                         assert!(update_1_0.update_fail_htlcs.len() == 1);
142                         update_1_0
143                 },
144                 _ => unreachable!(),
145         };
146
147         // 1 => 0 commitment_signed_dance
148         if update_1_0.update_fail_htlcs.len() > 0 {
149                 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
150                 if test_case == 100 {
151                         callback_fail(&mut fail_msg);
152                 }
153                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
154         } else {
155                 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]);
156         };
157
158         commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
159
160         let events = nodes[0].node.get_and_clear_pending_events();
161         assert_eq!(events.len(), 1);
162         if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code, error_data: _ } = &events[0] {
163                 assert_eq!(*rejected_by_dest, !expected_retryable);
164                 assert_eq!(*error_code, expected_error_code);
165         } else {
166                 panic!("Uexpected event");
167         }
168
169         let events = nodes[0].node.get_and_clear_pending_msg_events();
170         if expected_channel_update.is_some() {
171                 assert_eq!(events.len(), 1);
172                 match events[0] {
173                         MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
174                                 match update {
175                                         &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
176                                                 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
177                                                         panic!("channel_update not found!");
178                                                 }
179                                         },
180                                         &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
181                                                 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
182                                                         assert!(*short_channel_id == *expected_short_channel_id);
183                                                         assert!(*is_permanent == *expected_is_permanent);
184                                                 } else {
185                                                         panic!("Unexpected message event");
186                                                 }
187                                         },
188                                         &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
189                                                 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
190                                                         assert!(*node_id == *expected_node_id);
191                                                         assert!(*is_permanent == *expected_is_permanent);
192                                                 } else {
193                                                         panic!("Unexpected message event");
194                                                 }
195                                         },
196                                 }
197                         },
198                         _ => panic!("Unexpected message event"),
199                 }
200         } else {
201                 assert_eq!(events.len(), 0);
202         }
203 }
204
205 impl msgs::ChannelUpdate {
206         fn dummy() -> msgs::ChannelUpdate {
207                 use bitcoin::secp256k1::ffi::Signature as FFISignature;
208                 use bitcoin::secp256k1::Signature;
209                 msgs::ChannelUpdate {
210                         signature: Signature::from(unsafe { FFISignature::new() }),
211                         contents: msgs::UnsignedChannelUpdate {
212                                 chain_hash: BlockHash::hash(&vec![0u8][..]),
213                                 short_channel_id: 0,
214                                 timestamp: 0,
215                                 flags: 0,
216                                 cltv_expiry_delta: 0,
217                                 htlc_minimum_msat: 0,
218                                 htlc_maximum_msat: OptionalField::Absent,
219                                 fee_base_msat: 0,
220                                 fee_proportional_millionths: 0,
221                                 excess_data: vec![],
222                         }
223                 }
224         }
225 }
226
227 struct BogusOnionHopData {
228         data: Vec<u8>
229 }
230 impl BogusOnionHopData {
231         fn new(orig: msgs::OnionHopData) -> Self {
232                 Self { data: orig.encode() }
233         }
234 }
235 impl Writeable for BogusOnionHopData {
236         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
237                 writer.write_all(&self.data[..])
238         }
239 }
240
241 #[test]
242 fn test_onion_failure() {
243         use ln::msgs::ChannelUpdate;
244         use ln::channelmanager::CLTV_FAR_FAR_AWAY;
245         use bitcoin::secp256k1;
246
247         const BADONION: u16 = 0x8000;
248         const PERM: u16 = 0x4000;
249         const NODE: u16 = 0x2000;
250         const UPDATE: u16 = 0x1000;
251
252         // When we check for amount_below_minimum below, we want to test that we're using the *right*
253         // amount, thus we need different htlc_minimum_msat values. We set node[2]'s htlc_minimum_msat
254         // to 2000, which is above the default value of 1000 set in create_node_chanmgrs.
255         // This exposed a previous bug because we were using the wrong value all the way down in
256         // Channel::get_counterparty_htlc_minimum_msat().
257         let mut node_2_cfg: UserConfig = Default::default();
258         node_2_cfg.own_channel_config.our_htlc_minimum_msat = 2000;
259         node_2_cfg.channel_options.announced_channel = true;
260         node_2_cfg.peer_channel_config_limits.force_announced_channel_preference = false;
261
262         let chanmon_cfgs = create_chanmon_cfgs(3);
263         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
264         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, Some(node_2_cfg)]);
265         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
266         for node in nodes.iter() {
267                 *node.keys_manager.override_session_priv.lock().unwrap() = Some([3; 32]);
268         }
269         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())];
270         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[0]);
271         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
272         let logger = test_utils::TestLogger::new();
273         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap();
274         // positve case
275         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000, 40_000);
276
277         // intermediate node failure
278         run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
279                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
280                 let cur_height = nodes[0].best_block_info().1 + 1;
281                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
282                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
283                 let mut new_payloads = Vec::new();
284                 for payload in onion_payloads.drain(..) {
285                         new_payloads.push(BogusOnionHopData::new(payload));
286                 }
287                 // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
288                 // describing a length-1 TLV payload, which is obviously bogus.
289                 new_payloads[0].data[0] = 1;
290                 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
291         }, ||{}, true, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));//XXX incremented channels idx here
292
293         // final node failure
294         run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
295                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
296                 let cur_height = nodes[0].best_block_info().1 + 1;
297                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
298                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
299                 let mut new_payloads = Vec::new();
300                 for payload in onion_payloads.drain(..) {
301                         new_payloads.push(BogusOnionHopData::new(payload));
302                 }
303                 // break the last-hop payload by swapping the realm (0) byte for a byte describing a
304                 // length-1 TLV payload, which is obviously bogus.
305                 new_payloads[1].data[0] = 1;
306                 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
307         }, ||{}, false, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
308
309         // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
310         // receiving simulated fail messages
311         // intermediate node failure
312         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
313                 // trigger error
314                 msg.amount_msat -= 1;
315         }, |msg| {
316                 // and tamper returning error message
317                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
318                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
319                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
320         }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: false}));
321
322         // final node failure
323         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
324                 // and tamper returning error message
325                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
326                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
327                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
328         }, ||{
329                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
330         }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: false}));
331
332         // intermediate node failure
333         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
334                 msg.amount_msat -= 1;
335         }, |msg| {
336                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
337                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
338                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
339         }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
340
341         // final node failure
342         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
343                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
344                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
345                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
346         }, ||{
347                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
348         }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
349
350         // intermediate node failure
351         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
352                 msg.amount_msat -= 1;
353         }, |msg| {
354                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
355                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
356                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
357         }, ||{
358                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
359         }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
360
361         // final node failure
362         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
363                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
364                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
365                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
366         }, ||{
367                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
368         }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
369
370         run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
371                 Some(BADONION|PERM|4), None);
372
373         run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
374                 Some(BADONION|PERM|5), None);
375
376         run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
377                 Some(BADONION|PERM|6), None);
378
379         run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
380                 msg.amount_msat -= 1;
381         }, |msg| {
382                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
383                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
384                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
385         }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
386
387         run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
388                 msg.amount_msat -= 1;
389         }, |msg| {
390                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
391                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
392                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
393                 // short_channel_id from the processing node
394         }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
395
396         run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
397                 msg.amount_msat -= 1;
398         }, |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[0].shared_secret[..], PERM|9, &[0;0]);
402                 // short_channel_id from the processing node
403         }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
404
405         let mut bogus_route = route.clone();
406         bogus_route.paths[0][1].short_channel_id -= 1;
407         run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
408           Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.paths[0][1].short_channel_id, is_permanent:true}));
409
410         let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_counterparty_htlc_minimum_msat() - 1;
411         let mut bogus_route = route.clone();
412         let route_len = bogus_route.paths[0].len();
413         bogus_route.paths[0][route_len-1].fee_msat = amt_to_forward;
414         run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
415
416         // Test a positive test-case with one extra msat, meeting the minimum.
417         bogus_route.paths[0][route_len-1].fee_msat = amt_to_forward + 1;
418         let (preimage, _, _) = send_along_route(&nodes[0], bogus_route, &[&nodes[1], &nodes[2]], amt_to_forward+1);
419         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], preimage, amt_to_forward+1);
420
421         //TODO: with new config API, we will be able to generate both valid and
422         //invalid channel_update cases.
423         run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
424                 msg.amount_msat -= 1;
425         }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
426
427         run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
428                 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
429                 msg.cltv_expiry -= 1;
430         }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
431
432         run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
433                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
434                 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
435                 connect_blocks(&nodes[1], height - nodes[1].best_block_info().1);
436                 connect_blocks(&nodes[2], height - nodes[2].best_block_info().1);
437         }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
438
439         run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
440                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
441         }, false, Some(PERM|15), None);
442
443         run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
444                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
445                 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
446                 connect_blocks(&nodes[1], height - nodes[1].best_block_info().1);
447                 connect_blocks(&nodes[2], height - nodes[2].best_block_info().1);
448         }, || {}, true, Some(17), None);
449
450         run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
451                 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
452                         for f in pending_forwards.iter_mut() {
453                                 match f {
454                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
455                                                 forward_info.outgoing_cltv_value += 1,
456                                         _ => {},
457                                 }
458                         }
459                 }
460         }, true, Some(18), None);
461
462         run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
463                 // violate amt_to_forward > msg.amount_msat
464                 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
465                         for f in pending_forwards.iter_mut() {
466                                 match f {
467                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
468                                                 forward_info.amt_to_forward -= 1,
469                                         _ => {},
470                                 }
471                         }
472                 }
473         }, true, Some(19), None);
474
475         run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
476                 // disconnect event to the channel between nodes[1] ~ nodes[2]
477                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
478                 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
479         }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
480         reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
481
482         run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
483                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
484                 let mut route = route.clone();
485                 let height = nodes[2].best_block_info().1;
486                 route.paths[0][1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.paths[0][0].cltv_expiry_delta + 1;
487                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
488                 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, height).unwrap();
489                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
490                 msg.cltv_expiry = htlc_cltv;
491                 msg.onion_routing_packet = onion_packet;
492         }, ||{}, true, Some(21), None);
493 }
494
495