Drop the amount parameter to claim_funds
[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, PaymentSecret};
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, payment_secret: &PaymentSecret, 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, payment_secret, 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, 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<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(), &Some(*payment_secret)).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[2]);
271         let logger = test_utils::TestLogger::new();
272         let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].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();
273         // positve case
274         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000);
275
276         // intermediate node failure
277         run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
278                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
279                 let cur_height = nodes[0].best_block_info().1 + 1;
280                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
281                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
282                 let mut new_payloads = Vec::new();
283                 for payload in onion_payloads.drain(..) {
284                         new_payloads.push(BogusOnionHopData::new(payload));
285                 }
286                 // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
287                 // describing a length-1 TLV payload, which is obviously bogus.
288                 new_payloads[0].data[0] = 1;
289                 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
290         }, ||{}, 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
291
292         // final node failure
293         run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, &payment_secret, |msg| {
294                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
295                 let cur_height = nodes[0].best_block_info().1 + 1;
296                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
297                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
298                 let mut new_payloads = Vec::new();
299                 for payload in onion_payloads.drain(..) {
300                         new_payloads.push(BogusOnionHopData::new(payload));
301                 }
302                 // break the last-hop payload by swapping the realm (0) byte for a byte describing a
303                 // length-1 TLV payload, which is obviously bogus.
304                 new_payloads[1].data[0] = 1;
305                 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
306         }, ||{}, false, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
307
308         // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
309         // receiving simulated fail messages
310         // intermediate node failure
311         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
312                 // trigger error
313                 msg.amount_msat -= 1;
314         }, |msg| {
315                 // and tamper returning error message
316                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
317                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
318                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
319         }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: false}));
320
321         // final node failure
322         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
323                 // and tamper returning error message
324                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
325                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
326                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
327         }, ||{
328                 nodes[2].node.fail_htlc_backwards(&payment_hash);
329         }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: false}));
330         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
331
332         // intermediate node failure
333         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |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, &payment_secret, |_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);
348         }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
349         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
350
351         // intermediate node failure
352         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
353                 msg.amount_msat -= 1;
354         }, |msg| {
355                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
356                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
357                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
358         }, ||{
359                 nodes[2].node.fail_htlc_backwards(&payment_hash);
360         }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
361
362         // final node failure
363         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, &payment_secret, |_msg| {}, |msg| {
364                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
365                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
366                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
367         }, ||{
368                 nodes[2].node.fail_htlc_backwards(&payment_hash);
369         }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
370         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
371
372         run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
373                 Some(BADONION|PERM|4), None);
374
375         run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
376                 Some(BADONION|PERM|5), None);
377
378         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,
379                 Some(BADONION|PERM|6), None);
380
381         run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
382                 msg.amount_msat -= 1;
383         }, |msg| {
384                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
385                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
386                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
387         }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
388
389         run_onion_failure_test_with_fail_intercept("permanent_channel_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|8, &[0;0]);
395                 // short_channel_id from the processing node
396         }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
397
398         run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
399                 msg.amount_msat -= 1;
400         }, |msg| {
401                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
402                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
403                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
404                 // short_channel_id from the processing node
405         }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
406
407         let mut bogus_route = route.clone();
408         bogus_route.paths[0][1].short_channel_id -= 1;
409         run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, &payment_secret, |_| {}, ||{}, true, Some(PERM|10),
410           Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.paths[0][1].short_channel_id, is_permanent:true}));
411
412         let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_counterparty_htlc_minimum_msat() - 1;
413         let mut bogus_route = route.clone();
414         let route_len = bogus_route.paths[0].len();
415         bogus_route.paths[0][route_len-1].fee_msat = amt_to_forward;
416         run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, &payment_secret, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
417
418         // Test a positive test-case with one extra msat, meeting the minimum.
419         bogus_route.paths[0][route_len-1].fee_msat = amt_to_forward + 1;
420         let (preimage, _, _) = send_along_route(&nodes[0], bogus_route, &[&nodes[1], &nodes[2]], amt_to_forward+1);
421         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], preimage);
422
423         //TODO: with new config API, we will be able to generate both valid and
424         //invalid channel_update cases.
425         run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
426                 msg.amount_msat -= 1;
427         }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
428
429         run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
430                 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
431                 msg.cltv_expiry -= 1;
432         }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
433
434         run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
435                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
436                 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
437                 connect_blocks(&nodes[1], height - nodes[1].best_block_info().1);
438                 connect_blocks(&nodes[2], height - nodes[2].best_block_info().1);
439         }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
440
441         run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
442                 nodes[2].node.fail_htlc_backwards(&payment_hash);
443         }, false, Some(PERM|15), None);
444         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
445
446         run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, &payment_secret, |msg| {
447                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
448                 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
449                 connect_blocks(&nodes[1], height - nodes[1].best_block_info().1);
450                 connect_blocks(&nodes[2], height - nodes[2].best_block_info().1);
451         }, || {}, true, Some(17), None);
452
453         run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
454                 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
455                         for f in pending_forwards.iter_mut() {
456                                 match f {
457                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
458                                                 forward_info.outgoing_cltv_value += 1,
459                                         _ => {},
460                                 }
461                         }
462                 }
463         }, true, Some(18), None);
464
465         run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
466                 // violate amt_to_forward > msg.amount_msat
467                 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
468                         for f in pending_forwards.iter_mut() {
469                                 match f {
470                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
471                                                 forward_info.amt_to_forward -= 1,
472                                         _ => {},
473                                 }
474                         }
475                 }
476         }, true, Some(19), None);
477
478         run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
479                 // disconnect event to the channel between nodes[1] ~ nodes[2]
480                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
481                 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
482         }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
483         reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
484
485         run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, &payment_secret, |msg| {
486                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
487                 let mut route = route.clone();
488                 let height = nodes[2].best_block_info().1;
489                 route.paths[0][1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.paths[0][0].cltv_expiry_delta + 1;
490                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
491                 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, height).unwrap();
492                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
493                 msg.cltv_expiry = htlc_cltv;
494                 msg.onion_routing_packet = onion_packet;
495         }, ||{}, true, Some(21), None);
496 }
497
498