More regularly send an Error message when we force-close a channel
[rust-lightning] / lightning / src / ln / functional_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 that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use chain;
15 use chain::Watch;
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::{Sign, KeysInterface};
20 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
21 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
22 use ln::channel::{Channel, ChannelError};
23 use ln::{chan_utils, onion_utils};
24 use routing::router::{Route, RouteHop, get_route};
25 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
26 use ln::msgs;
27 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
28 use util::enforcing_trait_impls::EnforcingSigner;
29 use util::{byte_utils, test_utils};
30 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
31 use util::errors::APIError;
32 use util::ser::{Writeable, ReadableArgs};
33 use util::config::UserConfig;
34
35 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
36 use bitcoin::hash_types::{Txid, BlockHash};
37 use bitcoin::blockdata::block::{Block, BlockHeader};
38 use bitcoin::blockdata::script::Builder;
39 use bitcoin::blockdata::opcodes;
40 use bitcoin::blockdata::constants::genesis_block;
41 use bitcoin::network::constants::Network;
42
43 use bitcoin::hashes::sha256::Hash as Sha256;
44 use bitcoin::hashes::Hash;
45
46 use bitcoin::secp256k1::{Secp256k1, Message};
47 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
48
49 use regex;
50
51 use std::collections::{BTreeSet, HashMap, HashSet};
52 use std::default::Default;
53 use std::sync::Mutex;
54 use std::sync::atomic::Ordering;
55
56 use ln::functional_test_utils::*;
57 use ln::chan_utils::CommitmentTransaction;
58 use ln::msgs::OptionalField::Present;
59
60 #[test]
61 fn test_insane_channel_opens() {
62         // Stand up a network of 2 nodes
63         let chanmon_cfgs = create_chanmon_cfgs(2);
64         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
65         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
66         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
67
68         // Instantiate channel parameters where we push the maximum msats given our
69         // funding satoshis
70         let channel_value_sat = 31337; // same as funding satoshis
71         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
72         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
73
74         // Have node0 initiate a channel to node1 with aforementioned parameters
75         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
76
77         // Extract the channel open message from node0 to node1
78         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
79
80         // Test helper that asserts we get the correct error string given a mutator
81         // that supposedly makes the channel open message insane
82         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
83                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
84                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
85                 assert_eq!(msg_events.len(), 1);
86                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
87                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
88                         match action {
89                                 &ErrorAction::SendErrorMessage { .. } => {
90                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
91                                 },
92                                 _ => panic!("unexpected event!"),
93                         }
94                 } else { assert!(false); }
95         };
96
97         use ln::channel::MAX_FUNDING_SATOSHIS;
98         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
99
100         // Test all mutations that would make the channel open message insane
101         insane_open_helper(format!("Funding must be smaller than {}. It was {}", MAX_FUNDING_SATOSHIS, MAX_FUNDING_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
102
103         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
104
105         insane_open_helper(r"push_msat \d+ was larger than funding value \d+", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
106
107         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
108
109         insane_open_helper(r"Bogus; channel reserve \(\d+\) is less than dust limit \(\d+\)", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
110
111         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
112
113         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
114
115         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
116
117         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
118 }
119
120 #[test]
121 fn test_async_inbound_update_fee() {
122         let chanmon_cfgs = create_chanmon_cfgs(2);
123         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
124         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
125         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
126         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
127         let logger = test_utils::TestLogger::new();
128         let channel_id = chan.2;
129
130         // balancing
131         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
132
133         // A                                        B
134         // update_fee                            ->
135         // send (1) commitment_signed            -.
136         //                                       <- update_add_htlc/commitment_signed
137         // send (2) RAA (awaiting remote revoke) -.
138         // (1) commitment_signed is delivered    ->
139         //                                       .- send (3) RAA (awaiting remote revoke)
140         // (2) RAA is delivered                  ->
141         //                                       .- send (4) commitment_signed
142         //                                       <- (3) RAA is delivered
143         // send (5) commitment_signed            -.
144         //                                       <- (4) commitment_signed is delivered
145         // send (6) RAA                          -.
146         // (5) commitment_signed is delivered    ->
147         //                                       <- RAA
148         // (6) RAA is delivered                  ->
149
150         // First nodes[0] generates an update_fee
151         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
152         check_added_monitors!(nodes[0], 1);
153
154         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
155         assert_eq!(events_0.len(), 1);
156         let (update_msg, commitment_signed) = match events_0[0] { // (1)
157                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
158                         (update_fee.as_ref(), commitment_signed)
159                 },
160                 _ => panic!("Unexpected event"),
161         };
162
163         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
164
165         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
166         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
167         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
168         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
169         check_added_monitors!(nodes[1], 1);
170
171         let payment_event = {
172                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
173                 assert_eq!(events_1.len(), 1);
174                 SendEvent::from_event(events_1.remove(0))
175         };
176         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
177         assert_eq!(payment_event.msgs.len(), 1);
178
179         // ...now when the messages get delivered everyone should be happy
180         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
181         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
182         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
183         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
184         check_added_monitors!(nodes[0], 1);
185
186         // deliver(1), generate (3):
187         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
188         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
189         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
190         check_added_monitors!(nodes[1], 1);
191
192         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
193         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
194         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
195         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
196         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
197         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
198         assert!(bs_update.update_fee.is_none()); // (4)
199         check_added_monitors!(nodes[1], 1);
200
201         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
202         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
203         assert!(as_update.update_add_htlcs.is_empty()); // (5)
204         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
205         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
206         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
207         assert!(as_update.update_fee.is_none()); // (5)
208         check_added_monitors!(nodes[0], 1);
209
210         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
211         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
212         // only (6) so get_event_msg's assert(len == 1) passes
213         check_added_monitors!(nodes[0], 1);
214
215         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
216         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
217         check_added_monitors!(nodes[1], 1);
218
219         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
220         check_added_monitors!(nodes[0], 1);
221
222         let events_2 = nodes[0].node.get_and_clear_pending_events();
223         assert_eq!(events_2.len(), 1);
224         match events_2[0] {
225                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
226                 _ => panic!("Unexpected event"),
227         }
228
229         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
230         check_added_monitors!(nodes[1], 1);
231 }
232
233 #[test]
234 fn test_update_fee_unordered_raa() {
235         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
236         // crash in an earlier version of the update_fee patch)
237         let chanmon_cfgs = create_chanmon_cfgs(2);
238         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
239         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
240         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
241         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
242         let channel_id = chan.2;
243         let logger = test_utils::TestLogger::new();
244
245         // balancing
246         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
247
248         // First nodes[0] generates an update_fee
249         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
250         check_added_monitors!(nodes[0], 1);
251
252         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
253         assert_eq!(events_0.len(), 1);
254         let update_msg = match events_0[0] { // (1)
255                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
256                         update_fee.as_ref()
257                 },
258                 _ => panic!("Unexpected event"),
259         };
260
261         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
262
263         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
264         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
265         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
266         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
267         check_added_monitors!(nodes[1], 1);
268
269         let payment_event = {
270                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
271                 assert_eq!(events_1.len(), 1);
272                 SendEvent::from_event(events_1.remove(0))
273         };
274         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
275         assert_eq!(payment_event.msgs.len(), 1);
276
277         // ...now when the messages get delivered everyone should be happy
278         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
279         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
280         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
281         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
282         check_added_monitors!(nodes[0], 1);
283
284         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
285         check_added_monitors!(nodes[1], 1);
286
287         // We can't continue, sadly, because our (1) now has a bogus signature
288 }
289
290 #[test]
291 fn test_multi_flight_update_fee() {
292         let chanmon_cfgs = create_chanmon_cfgs(2);
293         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
294         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
295         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
296         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
297         let channel_id = chan.2;
298
299         // A                                        B
300         // update_fee/commitment_signed          ->
301         //                                       .- send (1) RAA and (2) commitment_signed
302         // update_fee (never committed)          ->
303         // (3) update_fee                        ->
304         // We have to manually generate the above update_fee, it is allowed by the protocol but we
305         // don't track which updates correspond to which revoke_and_ack responses so we're in
306         // AwaitingRAA mode and will not generate the update_fee yet.
307         //                                       <- (1) RAA delivered
308         // (3) is generated and send (4) CS      -.
309         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
310         // know the per_commitment_point to use for it.
311         //                                       <- (2) commitment_signed delivered
312         // revoke_and_ack                        ->
313         //                                          B should send no response here
314         // (4) commitment_signed delivered       ->
315         //                                       <- RAA/commitment_signed delivered
316         // revoke_and_ack                        ->
317
318         // First nodes[0] generates an update_fee
319         let initial_feerate = get_feerate!(nodes[0], channel_id);
320         nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
321         check_added_monitors!(nodes[0], 1);
322
323         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
324         assert_eq!(events_0.len(), 1);
325         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
326                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
327                         (update_fee.as_ref().unwrap(), commitment_signed)
328                 },
329                 _ => panic!("Unexpected event"),
330         };
331
332         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
333         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
334         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
335         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
336         check_added_monitors!(nodes[1], 1);
337
338         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
339         // transaction:
340         nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
341         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
342         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
343
344         // Create the (3) update_fee message that nodes[0] will generate before it does...
345         let mut update_msg_2 = msgs::UpdateFee {
346                 channel_id: update_msg_1.channel_id.clone(),
347                 feerate_per_kw: (initial_feerate + 30) as u32,
348         };
349
350         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
351
352         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
353         // Deliver (3)
354         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
355
356         // Deliver (1), generating (3) and (4)
357         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
358         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
359         check_added_monitors!(nodes[0], 1);
360         assert!(as_second_update.update_add_htlcs.is_empty());
361         assert!(as_second_update.update_fulfill_htlcs.is_empty());
362         assert!(as_second_update.update_fail_htlcs.is_empty());
363         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
364         // Check that the update_fee newly generated matches what we delivered:
365         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
366         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
367
368         // Deliver (2) commitment_signed
369         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
370         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
371         check_added_monitors!(nodes[0], 1);
372         // No commitment_signed so get_event_msg's assert(len == 1) passes
373
374         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
375         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
376         check_added_monitors!(nodes[1], 1);
377
378         // Delever (4)
379         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
380         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
381         check_added_monitors!(nodes[1], 1);
382
383         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
384         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
385         check_added_monitors!(nodes[0], 1);
386
387         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
388         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
389         // No commitment_signed so get_event_msg's assert(len == 1) passes
390         check_added_monitors!(nodes[0], 1);
391
392         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
393         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
394         check_added_monitors!(nodes[1], 1);
395 }
396
397 #[test]
398 fn test_1_conf_open() {
399         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
400         // tests that we properly send one in that case.
401         let mut alice_config = UserConfig::default();
402         alice_config.own_channel_config.minimum_depth = 1;
403         alice_config.channel_options.announced_channel = true;
404         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
405         let mut bob_config = UserConfig::default();
406         bob_config.own_channel_config.minimum_depth = 1;
407         bob_config.channel_options.announced_channel = true;
408         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
409         let chanmon_cfgs = create_chanmon_cfgs(2);
410         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
411         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
412         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
413
414         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
415         mine_transaction(&nodes[1], &tx);
416         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id()));
417
418         mine_transaction(&nodes[0], &tx);
419         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
420         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
421
422         for node in nodes {
423                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
424                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
425                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
426         }
427 }
428
429 fn do_test_sanity_on_in_flight_opens(steps: u8) {
430         // Previously, we had issues deserializing channels when we hadn't connected the first block
431         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
432         // serialization round-trips and simply do steps towards opening a channel and then drop the
433         // Node objects.
434
435         let chanmon_cfgs = create_chanmon_cfgs(2);
436         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
437         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
438         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
439
440         if steps & 0b1000_0000 != 0{
441                 let block = Block {
442                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
443                         txdata: vec![],
444                 };
445                 connect_block(&nodes[0], &block);
446                 connect_block(&nodes[1], &block);
447         }
448
449         if steps & 0x0f == 0 { return; }
450         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
451         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
452
453         if steps & 0x0f == 1 { return; }
454         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
455         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
456
457         if steps & 0x0f == 2 { return; }
458         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
459
460         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
461
462         if steps & 0x0f == 3 { return; }
463         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
464         check_added_monitors!(nodes[0], 0);
465         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
466
467         if steps & 0x0f == 4 { return; }
468         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
469         {
470                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
471                 assert_eq!(added_monitors.len(), 1);
472                 assert_eq!(added_monitors[0].0, funding_output);
473                 added_monitors.clear();
474         }
475         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
476
477         if steps & 0x0f == 5 { return; }
478         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
479         {
480                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
481                 assert_eq!(added_monitors.len(), 1);
482                 assert_eq!(added_monitors[0].0, funding_output);
483                 added_monitors.clear();
484         }
485
486         let events_4 = nodes[0].node.get_and_clear_pending_events();
487         assert_eq!(events_4.len(), 1);
488         match events_4[0] {
489                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
490                         assert_eq!(user_channel_id, 42);
491                         assert_eq!(*funding_txo, funding_output);
492                 },
493                 _ => panic!("Unexpected event"),
494         };
495
496         if steps & 0x0f == 6 { return; }
497         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
498
499         if steps & 0x0f == 7 { return; }
500         confirm_transaction_at(&nodes[0], &tx, 2);
501         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
502         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
503 }
504
505 #[test]
506 fn test_sanity_on_in_flight_opens() {
507         do_test_sanity_on_in_flight_opens(0);
508         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
509         do_test_sanity_on_in_flight_opens(1);
510         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
511         do_test_sanity_on_in_flight_opens(2);
512         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
513         do_test_sanity_on_in_flight_opens(3);
514         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
515         do_test_sanity_on_in_flight_opens(4);
516         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
517         do_test_sanity_on_in_flight_opens(5);
518         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
519         do_test_sanity_on_in_flight_opens(6);
520         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
521         do_test_sanity_on_in_flight_opens(7);
522         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
523         do_test_sanity_on_in_flight_opens(8);
524         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
525 }
526
527 #[test]
528 fn test_update_fee_vanilla() {
529         let chanmon_cfgs = create_chanmon_cfgs(2);
530         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
531         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
532         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
533         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
534         let channel_id = chan.2;
535
536         let feerate = get_feerate!(nodes[0], channel_id);
537         nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
538         check_added_monitors!(nodes[0], 1);
539
540         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
541         assert_eq!(events_0.len(), 1);
542         let (update_msg, commitment_signed) = match events_0[0] {
543                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
544                         (update_fee.as_ref(), commitment_signed)
545                 },
546                 _ => panic!("Unexpected event"),
547         };
548         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
549
550         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
551         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
552         check_added_monitors!(nodes[1], 1);
553
554         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
555         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
556         check_added_monitors!(nodes[0], 1);
557
558         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
559         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
560         // No commitment_signed so get_event_msg's assert(len == 1) passes
561         check_added_monitors!(nodes[0], 1);
562
563         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
564         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
565         check_added_monitors!(nodes[1], 1);
566 }
567
568 #[test]
569 fn test_update_fee_that_funder_cannot_afford() {
570         let chanmon_cfgs = create_chanmon_cfgs(2);
571         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
572         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
573         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
574         let channel_value = 1888;
575         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
576         let channel_id = chan.2;
577
578         let feerate = 260;
579         nodes[0].node.update_fee(channel_id, feerate).unwrap();
580         check_added_monitors!(nodes[0], 1);
581         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
582
583         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
584
585         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
586
587         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
588         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
589         {
590                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
591
592                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
593                 let num_htlcs = commitment_tx.output.len() - 2;
594                 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
595                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
596                 actual_fee = channel_value - actual_fee;
597                 assert_eq!(total_fee, actual_fee);
598         }
599
600         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
601         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
602         nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
603         check_added_monitors!(nodes[0], 1);
604
605         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
606
607         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
608
609         //While producing the commitment_signed response after handling a received update_fee request the
610         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
611         //Should produce and error.
612         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
613         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
614         check_added_monitors!(nodes[1], 1);
615         check_closed_broadcast!(nodes[1], true);
616 }
617
618 #[test]
619 fn test_update_fee_with_fundee_update_add_htlc() {
620         let chanmon_cfgs = create_chanmon_cfgs(2);
621         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
622         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
623         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
624         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
625         let channel_id = chan.2;
626         let logger = test_utils::TestLogger::new();
627
628         // balancing
629         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
630
631         let feerate = get_feerate!(nodes[0], channel_id);
632         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
633         check_added_monitors!(nodes[0], 1);
634
635         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
636         assert_eq!(events_0.len(), 1);
637         let (update_msg, commitment_signed) = match events_0[0] {
638                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
639                         (update_fee.as_ref(), commitment_signed)
640                 },
641                 _ => panic!("Unexpected event"),
642         };
643         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
644         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
645         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
646         check_added_monitors!(nodes[1], 1);
647
648         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
649         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
650         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 800000, TEST_FINAL_CLTV, &logger).unwrap();
651
652         // nothing happens since node[1] is in AwaitingRemoteRevoke
653         nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
654         {
655                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
656                 assert_eq!(added_monitors.len(), 0);
657                 added_monitors.clear();
658         }
659         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
660         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
661         // node[1] has nothing to do
662
663         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
664         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
665         check_added_monitors!(nodes[0], 1);
666
667         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
668         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
669         // No commitment_signed so get_event_msg's assert(len == 1) passes
670         check_added_monitors!(nodes[0], 1);
671         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
672         check_added_monitors!(nodes[1], 1);
673         // AwaitingRemoteRevoke ends here
674
675         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
676         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
677         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
678         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
679         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
680         assert_eq!(commitment_update.update_fee.is_none(), true);
681
682         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
683         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
684         check_added_monitors!(nodes[0], 1);
685         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
686
687         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
688         check_added_monitors!(nodes[1], 1);
689         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
690
691         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
692         check_added_monitors!(nodes[1], 1);
693         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
694         // No commitment_signed so get_event_msg's assert(len == 1) passes
695
696         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
697         check_added_monitors!(nodes[0], 1);
698         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
699
700         expect_pending_htlcs_forwardable!(nodes[0]);
701
702         let events = nodes[0].node.get_and_clear_pending_events();
703         assert_eq!(events.len(), 1);
704         match events[0] {
705                 Event::PaymentReceived { .. } => { },
706                 _ => panic!("Unexpected event"),
707         };
708
709         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
710
711         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
712         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
713         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
714 }
715
716 #[test]
717 fn test_update_fee() {
718         let chanmon_cfgs = create_chanmon_cfgs(2);
719         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
720         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
721         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
722         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
723         let channel_id = chan.2;
724
725         // A                                        B
726         // (1) update_fee/commitment_signed      ->
727         //                                       <- (2) revoke_and_ack
728         //                                       .- send (3) commitment_signed
729         // (4) update_fee/commitment_signed      ->
730         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
731         //                                       <- (3) commitment_signed delivered
732         // send (6) revoke_and_ack               -.
733         //                                       <- (5) deliver revoke_and_ack
734         // (6) deliver revoke_and_ack            ->
735         //                                       .- send (7) commitment_signed in response to (4)
736         //                                       <- (7) deliver commitment_signed
737         // revoke_and_ack                        ->
738
739         // Create and deliver (1)...
740         let feerate = get_feerate!(nodes[0], channel_id);
741         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
742         check_added_monitors!(nodes[0], 1);
743
744         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
745         assert_eq!(events_0.len(), 1);
746         let (update_msg, commitment_signed) = match events_0[0] {
747                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
748                         (update_fee.as_ref(), commitment_signed)
749                 },
750                 _ => panic!("Unexpected event"),
751         };
752         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
753
754         // Generate (2) and (3):
755         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
756         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
757         check_added_monitors!(nodes[1], 1);
758
759         // Deliver (2):
760         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
761         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
762         check_added_monitors!(nodes[0], 1);
763
764         // Create and deliver (4)...
765         nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
766         check_added_monitors!(nodes[0], 1);
767         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
768         assert_eq!(events_0.len(), 1);
769         let (update_msg, commitment_signed) = match events_0[0] {
770                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
771                         (update_fee.as_ref(), commitment_signed)
772                 },
773                 _ => panic!("Unexpected event"),
774         };
775
776         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
777         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
778         check_added_monitors!(nodes[1], 1);
779         // ... creating (5)
780         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
781         // No commitment_signed so get_event_msg's assert(len == 1) passes
782
783         // Handle (3), creating (6):
784         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
785         check_added_monitors!(nodes[0], 1);
786         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
787         // No commitment_signed so get_event_msg's assert(len == 1) passes
788
789         // Deliver (5):
790         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
791         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
792         check_added_monitors!(nodes[0], 1);
793
794         // Deliver (6), creating (7):
795         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
796         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
797         assert!(commitment_update.update_add_htlcs.is_empty());
798         assert!(commitment_update.update_fulfill_htlcs.is_empty());
799         assert!(commitment_update.update_fail_htlcs.is_empty());
800         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
801         assert!(commitment_update.update_fee.is_none());
802         check_added_monitors!(nodes[1], 1);
803
804         // Deliver (7)
805         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
806         check_added_monitors!(nodes[0], 1);
807         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
808         // No commitment_signed so get_event_msg's assert(len == 1) passes
809
810         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
811         check_added_monitors!(nodes[1], 1);
812         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
813
814         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
815         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
816         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
817 }
818
819 #[test]
820 fn pre_funding_lock_shutdown_test() {
821         // Test sending a shutdown prior to funding_locked after funding generation
822         let chanmon_cfgs = create_chanmon_cfgs(2);
823         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
824         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
825         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
826         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
827         mine_transaction(&nodes[0], &tx);
828         mine_transaction(&nodes[1], &tx);
829
830         nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
831         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
832         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
833         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
834         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
835
836         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
837         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
838         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
839         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
840         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
841         assert!(node_0_none.is_none());
842
843         assert!(nodes[0].node.list_channels().is_empty());
844         assert!(nodes[1].node.list_channels().is_empty());
845 }
846
847 #[test]
848 fn updates_shutdown_wait() {
849         // Test sending a shutdown with outstanding updates pending
850         let chanmon_cfgs = create_chanmon_cfgs(3);
851         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
852         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
853         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
854         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
855         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
856         let logger = test_utils::TestLogger::new();
857
858         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
859
860         nodes[0].node.close_channel(&chan_1.2).unwrap();
861         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
862         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
863         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
864         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
865
866         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
867         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
868
869         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
870
871         let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
872         let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
873         let route_1 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler0.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
874         let route_2 = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler1.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
875         unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
876         unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
877
878         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
879         check_added_monitors!(nodes[2], 1);
880         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
881         assert!(updates.update_add_htlcs.is_empty());
882         assert!(updates.update_fail_htlcs.is_empty());
883         assert!(updates.update_fail_malformed_htlcs.is_empty());
884         assert!(updates.update_fee.is_none());
885         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
886         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
887         check_added_monitors!(nodes[1], 1);
888         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
889         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
890
891         assert!(updates_2.update_add_htlcs.is_empty());
892         assert!(updates_2.update_fail_htlcs.is_empty());
893         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
894         assert!(updates_2.update_fee.is_none());
895         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
896         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
897         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
898
899         let events = nodes[0].node.get_and_clear_pending_events();
900         assert_eq!(events.len(), 1);
901         match events[0] {
902                 Event::PaymentSent { ref payment_preimage } => {
903                         assert_eq!(our_payment_preimage, *payment_preimage);
904                 },
905                 _ => panic!("Unexpected event"),
906         }
907
908         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
909         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
910         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
911         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
912         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
913         assert!(node_0_none.is_none());
914
915         assert!(nodes[0].node.list_channels().is_empty());
916
917         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
918         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
919         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
920         assert!(nodes[1].node.list_channels().is_empty());
921         assert!(nodes[2].node.list_channels().is_empty());
922 }
923
924 #[test]
925 fn htlc_fail_async_shutdown() {
926         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
927         let chanmon_cfgs = create_chanmon_cfgs(3);
928         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
929         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
930         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
931         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
932         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
933         let logger = test_utils::TestLogger::new();
934
935         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
936         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
937         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(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
938         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
939         check_added_monitors!(nodes[0], 1);
940         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
941         assert_eq!(updates.update_add_htlcs.len(), 1);
942         assert!(updates.update_fulfill_htlcs.is_empty());
943         assert!(updates.update_fail_htlcs.is_empty());
944         assert!(updates.update_fail_malformed_htlcs.is_empty());
945         assert!(updates.update_fee.is_none());
946
947         nodes[1].node.close_channel(&chan_1.2).unwrap();
948         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
949         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
950         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
951
952         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
953         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
954         check_added_monitors!(nodes[1], 1);
955         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
956         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
957
958         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
959         assert!(updates_2.update_add_htlcs.is_empty());
960         assert!(updates_2.update_fulfill_htlcs.is_empty());
961         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
962         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
963         assert!(updates_2.update_fee.is_none());
964
965         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
966         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
967
968         expect_payment_failed!(nodes[0], our_payment_hash, false);
969
970         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
971         assert_eq!(msg_events.len(), 2);
972         let node_0_closing_signed = match msg_events[0] {
973                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
974                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
975                         (*msg).clone()
976                 },
977                 _ => panic!("Unexpected event"),
978         };
979         match msg_events[1] {
980                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
981                         assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
982                 },
983                 _ => panic!("Unexpected event"),
984         }
985
986         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
987         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
988         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
989         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
990         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
991         assert!(node_0_none.is_none());
992
993         assert!(nodes[0].node.list_channels().is_empty());
994
995         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
996         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
997         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
998         assert!(nodes[1].node.list_channels().is_empty());
999         assert!(nodes[2].node.list_channels().is_empty());
1000 }
1001
1002 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1003         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1004         // messages delivered prior to disconnect
1005         let chanmon_cfgs = create_chanmon_cfgs(3);
1006         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1007         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1008         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1009         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1010         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1011
1012         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1013
1014         nodes[1].node.close_channel(&chan_1.2).unwrap();
1015         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1016         if recv_count > 0 {
1017                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
1018                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1019                 if recv_count > 1 {
1020                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
1021                 }
1022         }
1023
1024         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1025         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1026
1027         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1028         let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1029         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1030         let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1031
1032         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1033         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1034         assert!(node_1_shutdown == node_1_2nd_shutdown);
1035
1036         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1037         let node_0_2nd_shutdown = if recv_count > 0 {
1038                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1039                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1040                 node_0_2nd_shutdown
1041         } else {
1042                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1043                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1044                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1045         };
1046         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_2nd_shutdown);
1047
1048         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1049         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1050
1051         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1052         check_added_monitors!(nodes[2], 1);
1053         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1054         assert!(updates.update_add_htlcs.is_empty());
1055         assert!(updates.update_fail_htlcs.is_empty());
1056         assert!(updates.update_fail_malformed_htlcs.is_empty());
1057         assert!(updates.update_fee.is_none());
1058         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1059         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1060         check_added_monitors!(nodes[1], 1);
1061         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1062         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1063
1064         assert!(updates_2.update_add_htlcs.is_empty());
1065         assert!(updates_2.update_fail_htlcs.is_empty());
1066         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1067         assert!(updates_2.update_fee.is_none());
1068         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1069         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1070         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1071
1072         let events = nodes[0].node.get_and_clear_pending_events();
1073         assert_eq!(events.len(), 1);
1074         match events[0] {
1075                 Event::PaymentSent { ref payment_preimage } => {
1076                         assert_eq!(our_payment_preimage, *payment_preimage);
1077                 },
1078                 _ => panic!("Unexpected event"),
1079         }
1080
1081         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1082         if recv_count > 0 {
1083                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1084                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1085                 assert!(node_1_closing_signed.is_some());
1086         }
1087
1088         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1089         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1090
1091         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1092         let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1093         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1094         if recv_count == 0 {
1095                 // If all closing_signeds weren't delivered we can just resume where we left off...
1096                 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1097
1098                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1099                 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1100                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1101
1102                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1103                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1104                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1105
1106                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_3rd_shutdown);
1107                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1108
1109                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_3rd_shutdown);
1110                 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1111                 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1112
1113                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1114                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1115                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1116                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1117                 assert!(node_0_none.is_none());
1118         } else {
1119                 // If one node, however, received + responded with an identical closing_signed we end
1120                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1121                 // There isn't really anything better we can do simply, but in the future we might
1122                 // explore storing a set of recently-closed channels that got disconnected during
1123                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1124                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1125                 // transaction.
1126                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1127
1128                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1129                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1130                 assert_eq!(msg_events.len(), 1);
1131                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1132                         match action {
1133                                 &ErrorAction::SendErrorMessage { ref msg } => {
1134                                         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1135                                         assert_eq!(msg.channel_id, chan_1.2);
1136                                 },
1137                                 _ => panic!("Unexpected event!"),
1138                         }
1139                 } else { panic!("Needed SendErrorMessage close"); }
1140
1141                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1142                 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1143                 // closing_signed so we do it ourselves
1144                 check_closed_broadcast!(nodes[0], false);
1145                 check_added_monitors!(nodes[0], 1);
1146         }
1147
1148         assert!(nodes[0].node.list_channels().is_empty());
1149
1150         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1151         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1152         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1153         assert!(nodes[1].node.list_channels().is_empty());
1154         assert!(nodes[2].node.list_channels().is_empty());
1155 }
1156
1157 #[test]
1158 fn test_shutdown_rebroadcast() {
1159         do_test_shutdown_rebroadcast(0);
1160         do_test_shutdown_rebroadcast(1);
1161         do_test_shutdown_rebroadcast(2);
1162 }
1163
1164 #[test]
1165 fn fake_network_test() {
1166         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1167         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1168         let chanmon_cfgs = create_chanmon_cfgs(4);
1169         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1170         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1171         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1172
1173         // Create some initial channels
1174         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1175         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1176         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1177
1178         // Rebalance the network a bit by relaying one payment through all the channels...
1179         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1180         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1181         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1182         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1183
1184         // Send some more payments
1185         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1186         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1187         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1188
1189         // Test failure packets
1190         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1191         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1192
1193         // Add a new channel that skips 3
1194         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1195
1196         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1197         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1198         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1199         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1200         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1201         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1202         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1203
1204         // Do some rebalance loop payments, simultaneously
1205         let mut hops = Vec::with_capacity(3);
1206         hops.push(RouteHop {
1207                 pubkey: nodes[2].node.get_our_node_id(),
1208                 node_features: NodeFeatures::empty(),
1209                 short_channel_id: chan_2.0.contents.short_channel_id,
1210                 channel_features: ChannelFeatures::empty(),
1211                 fee_msat: 0,
1212                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1213         });
1214         hops.push(RouteHop {
1215                 pubkey: nodes[3].node.get_our_node_id(),
1216                 node_features: NodeFeatures::empty(),
1217                 short_channel_id: chan_3.0.contents.short_channel_id,
1218                 channel_features: ChannelFeatures::empty(),
1219                 fee_msat: 0,
1220                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1221         });
1222         hops.push(RouteHop {
1223                 pubkey: nodes[1].node.get_our_node_id(),
1224                 node_features: NodeFeatures::empty(),
1225                 short_channel_id: chan_4.0.contents.short_channel_id,
1226                 channel_features: ChannelFeatures::empty(),
1227                 fee_msat: 1000000,
1228                 cltv_expiry_delta: TEST_FINAL_CLTV,
1229         });
1230         hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1231         hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1232         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1233
1234         let mut hops = Vec::with_capacity(3);
1235         hops.push(RouteHop {
1236                 pubkey: nodes[3].node.get_our_node_id(),
1237                 node_features: NodeFeatures::empty(),
1238                 short_channel_id: chan_4.0.contents.short_channel_id,
1239                 channel_features: ChannelFeatures::empty(),
1240                 fee_msat: 0,
1241                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1242         });
1243         hops.push(RouteHop {
1244                 pubkey: nodes[2].node.get_our_node_id(),
1245                 node_features: NodeFeatures::empty(),
1246                 short_channel_id: chan_3.0.contents.short_channel_id,
1247                 channel_features: ChannelFeatures::empty(),
1248                 fee_msat: 0,
1249                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1250         });
1251         hops.push(RouteHop {
1252                 pubkey: nodes[1].node.get_our_node_id(),
1253                 node_features: NodeFeatures::empty(),
1254                 short_channel_id: chan_2.0.contents.short_channel_id,
1255                 channel_features: ChannelFeatures::empty(),
1256                 fee_msat: 1000000,
1257                 cltv_expiry_delta: TEST_FINAL_CLTV,
1258         });
1259         hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1260         hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1261         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1262
1263         // Claim the rebalances...
1264         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1265         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1266
1267         // Add a duplicate new channel from 2 to 4
1268         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1269
1270         // Send some payments across both channels
1271         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1272         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1273         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1274
1275
1276         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1277         let events = nodes[0].node.get_and_clear_pending_msg_events();
1278         assert_eq!(events.len(), 0);
1279         nodes[0].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap(), 1);
1280
1281         //TODO: Test that routes work again here as we've been notified that the channel is full
1282
1283         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1284         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1285         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1286
1287         // Close down the channels...
1288         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1289         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1290         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1291         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1292         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1293 }
1294
1295 #[test]
1296 fn holding_cell_htlc_counting() {
1297         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1298         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1299         // commitment dance rounds.
1300         let chanmon_cfgs = create_chanmon_cfgs(3);
1301         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1302         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1303         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1304         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1305         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1306         let logger = test_utils::TestLogger::new();
1307
1308         let mut payments = Vec::new();
1309         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1310                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1311                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1312                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1313                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1314                 payments.push((payment_preimage, payment_hash));
1315         }
1316         check_added_monitors!(nodes[1], 1);
1317
1318         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1319         assert_eq!(events.len(), 1);
1320         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1321         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1322
1323         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1324         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1325         // another HTLC.
1326         let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1327         {
1328                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1329                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1330                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1331                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1332                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1333                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1334         }
1335
1336         // This should also be true if we try to forward a payment.
1337         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1338         {
1339                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1340                 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(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1341                 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1342                 check_added_monitors!(nodes[0], 1);
1343         }
1344
1345         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1346         assert_eq!(events.len(), 1);
1347         let payment_event = SendEvent::from_event(events.pop().unwrap());
1348         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1349
1350         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1351         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1352         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1353         // fails), the second will process the resulting failure and fail the HTLC backward.
1354         expect_pending_htlcs_forwardable!(nodes[1]);
1355         expect_pending_htlcs_forwardable!(nodes[1]);
1356         check_added_monitors!(nodes[1], 1);
1357
1358         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1359         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1360         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1361
1362         let events = nodes[0].node.get_and_clear_pending_msg_events();
1363         assert_eq!(events.len(), 1);
1364         match events[0] {
1365                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1366                         assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1367                 },
1368                 _ => panic!("Unexpected event"),
1369         }
1370
1371         expect_payment_failed!(nodes[0], payment_hash_2, false);
1372
1373         // Now forward all the pending HTLCs and claim them back
1374         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1375         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1376         check_added_monitors!(nodes[2], 1);
1377
1378         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1379         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1380         check_added_monitors!(nodes[1], 1);
1381         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1382
1383         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1384         check_added_monitors!(nodes[1], 1);
1385         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1386
1387         for ref update in as_updates.update_add_htlcs.iter() {
1388                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1389         }
1390         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1391         check_added_monitors!(nodes[2], 1);
1392         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1393         check_added_monitors!(nodes[2], 1);
1394         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1395
1396         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1397         check_added_monitors!(nodes[1], 1);
1398         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1399         check_added_monitors!(nodes[1], 1);
1400         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1401
1402         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1403         check_added_monitors!(nodes[2], 1);
1404
1405         expect_pending_htlcs_forwardable!(nodes[2]);
1406
1407         let events = nodes[2].node.get_and_clear_pending_events();
1408         assert_eq!(events.len(), payments.len());
1409         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1410                 match event {
1411                         &Event::PaymentReceived { ref payment_hash, .. } => {
1412                                 assert_eq!(*payment_hash, *hash);
1413                         },
1414                         _ => panic!("Unexpected event"),
1415                 };
1416         }
1417
1418         for (preimage, _) in payments.drain(..) {
1419                 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1420         }
1421
1422         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1423 }
1424
1425 #[test]
1426 fn duplicate_htlc_test() {
1427         // Test that we accept duplicate payment_hash HTLCs across the network and that
1428         // claiming/failing them are all separate and don't affect each other
1429         let chanmon_cfgs = create_chanmon_cfgs(6);
1430         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1431         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1432         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1433
1434         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1435         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1436         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1437         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1438         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1439         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1440
1441         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1442
1443         *nodes[0].network_payment_count.borrow_mut() -= 1;
1444         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1445
1446         *nodes[0].network_payment_count.borrow_mut() -= 1;
1447         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1448
1449         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1450         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1451         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1452 }
1453
1454 #[test]
1455 fn test_duplicate_htlc_different_direction_onchain() {
1456         // Test that ChannelMonitor doesn't generate 2 preimage txn
1457         // when we have 2 HTLCs with same preimage that go across a node
1458         // in opposite directions.
1459         let chanmon_cfgs = create_chanmon_cfgs(2);
1460         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1461         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1462         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1463
1464         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1465         let logger = test_utils::TestLogger::new();
1466
1467         // balancing
1468         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1469
1470         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1471
1472         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1473         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 800_000, TEST_FINAL_CLTV, &logger).unwrap();
1474         send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1475
1476         // Provide preimage to node 0 by claiming payment
1477         nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1478         check_added_monitors!(nodes[0], 1);
1479
1480         // Broadcast node 1 commitment txn
1481         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1482
1483         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1484         let mut has_both_htlcs = 0; // check htlcs match ones committed
1485         for outp in remote_txn[0].output.iter() {
1486                 if outp.value == 800_000 / 1000 {
1487                         has_both_htlcs += 1;
1488                 } else if outp.value == 900_000 / 1000 {
1489                         has_both_htlcs += 1;
1490                 }
1491         }
1492         assert_eq!(has_both_htlcs, 2);
1493
1494         mine_transaction(&nodes[0], &remote_txn[0]);
1495         check_added_monitors!(nodes[0], 1);
1496
1497         // Check we only broadcast 1 timeout tx
1498         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1499         let htlc_pair = if claim_txn[0].output[0].value == 800_000 / 1000 { (claim_txn[0].clone(), claim_txn[1].clone()) } else { (claim_txn[1].clone(), claim_txn[0].clone()) };
1500         assert_eq!(claim_txn.len(), 5);
1501         check_spends!(claim_txn[2], chan_1.3);
1502         check_spends!(claim_txn[3], claim_txn[2]);
1503         assert_eq!(htlc_pair.0.input.len(), 1);
1504         assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1505         check_spends!(htlc_pair.0, remote_txn[0]);
1506         assert_eq!(htlc_pair.1.input.len(), 1);
1507         assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1508         check_spends!(htlc_pair.1, remote_txn[0]);
1509
1510         let events = nodes[0].node.get_and_clear_pending_msg_events();
1511         assert_eq!(events.len(), 3);
1512         for e in events {
1513                 match e {
1514                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1515                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1516                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1517                                 assert_eq!(msg.data, "Commitment or closing transaction was confirmed on chain.");
1518                         },
1519                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1520                                 assert!(update_add_htlcs.is_empty());
1521                                 assert!(update_fail_htlcs.is_empty());
1522                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1523                                 assert!(update_fail_malformed_htlcs.is_empty());
1524                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1525                         },
1526                         _ => panic!("Unexpected event"),
1527                 }
1528         }
1529 }
1530
1531 #[test]
1532 fn test_basic_channel_reserve() {
1533         let chanmon_cfgs = create_chanmon_cfgs(2);
1534         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1535         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1536         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1537         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1538         let logger = test_utils::TestLogger::new();
1539
1540         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1541         let channel_reserve = chan_stat.channel_reserve_msat;
1542
1543         // The 2* and +1 are for the fee spike reserve.
1544         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1545         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1546         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1547         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1548         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), None, None, &Vec::new(), max_can_send + 1, TEST_FINAL_CLTV, &logger).unwrap();
1549         let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1550         match err {
1551                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1552                         match &fails[0] {
1553                                 &APIError::ChannelUnavailable{ref err} =>
1554                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1555                                 _ => panic!("Unexpected error variant"),
1556                         }
1557                 },
1558                 _ => panic!("Unexpected error variant"),
1559         }
1560         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1561         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1562
1563         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1564 }
1565
1566 #[test]
1567 fn test_fee_spike_violation_fails_htlc() {
1568         let chanmon_cfgs = create_chanmon_cfgs(2);
1569         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1570         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1571         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1572         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1573         let logger = test_utils::TestLogger::new();
1574
1575         macro_rules! get_route_and_payment_hash {
1576                 ($recv_value: expr) => {{
1577                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1578                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1579                         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes.last().unwrap().node.get_our_node_id(), None, None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1580                         (route, payment_hash, payment_preimage)
1581                 }}
1582         }
1583
1584         let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1585         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1586         let secp_ctx = Secp256k1::new();
1587         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1588
1589         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1590
1591         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1592         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1593         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1594         let msg = msgs::UpdateAddHTLC {
1595                 channel_id: chan.2,
1596                 htlc_id: 0,
1597                 amount_msat: htlc_msat,
1598                 payment_hash: payment_hash,
1599                 cltv_expiry: htlc_cltv,
1600                 onion_routing_packet: onion_packet,
1601         };
1602
1603         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1604
1605         // Now manually create the commitment_signed message corresponding to the update_add
1606         // nodes[0] just sent. In the code for construction of this message, "local" refers
1607         // to the sender of the message, and "remote" refers to the receiver.
1608
1609         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1610
1611         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1612
1613         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1614         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1615         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point) = {
1616                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1617                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1618                 let chan_signer = local_chan.get_signer();
1619                 let pubkeys = chan_signer.pubkeys();
1620                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1621                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1622                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
1623         };
1624         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point) = {
1625                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1626                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1627                 let chan_signer = remote_chan.get_signer();
1628                 let pubkeys = chan_signer.pubkeys();
1629                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1630                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
1631         };
1632
1633         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1634         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1635                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1636
1637         // Build the remote commitment transaction so we can sign it, and then later use the
1638         // signature for the commitment_signed message.
1639         let local_chan_balance = 1313;
1640
1641         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1642                 offered: false,
1643                 amount_msat: 3460001,
1644                 cltv_expiry: htlc_cltv,
1645                 payment_hash,
1646                 transaction_output_index: Some(1),
1647         };
1648
1649         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1650
1651         let res = {
1652                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1653                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1654                 let local_chan_signer = local_chan.get_signer();
1655                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1656                         commitment_number,
1657                         95000,
1658                         local_chan_balance,
1659                         commit_tx_keys.clone(),
1660                         feerate_per_kw,
1661                         &mut vec![(accepted_htlc_info, ())],
1662                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1663                 );
1664                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1665         };
1666
1667         let commit_signed_msg = msgs::CommitmentSigned {
1668                 channel_id: chan.2,
1669                 signature: res.0,
1670                 htlc_signatures: res.1
1671         };
1672
1673         // Send the commitment_signed message to the nodes[1].
1674         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1675         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1676
1677         // Send the RAA to nodes[1].
1678         let raa_msg = msgs::RevokeAndACK {
1679                 channel_id: chan.2,
1680                 per_commitment_secret: local_secret,
1681                 next_per_commitment_point: next_local_point
1682         };
1683         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1684
1685         let events = nodes[1].node.get_and_clear_pending_msg_events();
1686         assert_eq!(events.len(), 1);
1687         // Make sure the HTLC failed in the way we expect.
1688         match events[0] {
1689                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1690                         assert_eq!(update_fail_htlcs.len(), 1);
1691                         update_fail_htlcs[0].clone()
1692                 },
1693                 _ => panic!("Unexpected event"),
1694         };
1695         nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1696
1697         check_added_monitors!(nodes[1], 2);
1698 }
1699
1700 #[test]
1701 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1702         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1703         // Set the fee rate for the channel very high, to the point where the fundee
1704         // sending any above-dust amount would result in a channel reserve violation.
1705         // In this test we check that we would be prevented from sending an HTLC in
1706         // this situation.
1707         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1708         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1709         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1710         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1711         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1712         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1713         let logger = test_utils::TestLogger::new();
1714
1715         macro_rules! get_route_and_payment_hash {
1716                 ($recv_value: expr) => {{
1717                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1718                         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1719                         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.first().unwrap().node.get_our_node_id(), None, None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1720                         (route, payment_hash, payment_preimage)
1721                 }}
1722         }
1723
1724         let (route, our_payment_hash, _) = get_route_and_payment_hash!(4843000);
1725         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1726                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1727         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1728         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
1729 }
1730
1731 #[test]
1732 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1733         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1734         // Set the fee rate for the channel very high, to the point where the funder
1735         // receiving 1 update_add_htlc would result in them closing the channel due
1736         // to channel reserve violation. This close could also happen if the fee went
1737         // up a more realistic amount, but many HTLCs were outstanding at the time of
1738         // the update_add_htlc.
1739         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1740         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1741         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1742         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1743         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1744         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1745         let logger = test_utils::TestLogger::new();
1746
1747         macro_rules! get_route_and_payment_hash {
1748                 ($recv_value: expr) => {{
1749                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1750                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1751                         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.first().unwrap().node.get_our_node_id(), None, None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1752                         (route, payment_hash, payment_preimage)
1753                 }}
1754         }
1755
1756         let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1757         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1758         let secp_ctx = Secp256k1::new();
1759         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1760         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1761         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1762         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1763         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1764         let msg = msgs::UpdateAddHTLC {
1765                 channel_id: chan.2,
1766                 htlc_id: 1,
1767                 amount_msat: htlc_msat + 1,
1768                 payment_hash: payment_hash,
1769                 cltv_expiry: htlc_cltv,
1770                 onion_routing_packet: onion_packet,
1771         };
1772
1773         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1774         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1775         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1776         assert_eq!(nodes[0].node.list_channels().len(), 0);
1777         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1778         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1779         check_added_monitors!(nodes[0], 1);
1780 }
1781
1782 #[test]
1783 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1784         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1785         // calculating our commitment transaction fee (this was previously broken).
1786         let chanmon_cfgs = create_chanmon_cfgs(2);
1787         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1788         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1789         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1790
1791         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1792         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1793         // transaction fee with 0 HTLCs (183 sats)).
1794         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98817000, InitFeatures::known(), InitFeatures::known());
1795
1796         let dust_amt = 546000; // Dust amount
1797         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1798         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1799         // commitment transaction fee.
1800         let (_, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1801 }
1802
1803 #[test]
1804 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1805         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1806         // calculating our counterparty's commitment transaction fee (this was previously broken).
1807         let chanmon_cfgs = create_chanmon_cfgs(2);
1808         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1809         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1810         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1811         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1812
1813         let payment_amt = 46000; // Dust amount
1814         // In the previous code, these first four payments would succeed.
1815         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1816         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1817         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1818         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1819
1820         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1821         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1822         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1823         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1824         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1825         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1826
1827         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1828         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1829         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1830         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1831 }
1832
1833 #[test]
1834 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1835         let chanmon_cfgs = create_chanmon_cfgs(3);
1836         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1837         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1838         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1839         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1840         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1841         let logger = test_utils::TestLogger::new();
1842
1843         macro_rules! get_route_and_payment_hash {
1844                 ($recv_value: expr) => {{
1845                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1846                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1847                         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), None, None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1848                         (route, payment_hash, payment_preimage)
1849                 }}
1850         }
1851
1852         let feemsat = 239;
1853         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1854         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1855         let feerate = get_feerate!(nodes[0], chan.2);
1856
1857         // Add a 2* and +1 for the fee spike reserve.
1858         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1859         let recv_value_1 = (chan_stat.value_to_self_msat - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlc)/2;
1860         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1861
1862         // Add a pending HTLC.
1863         let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1864         let payment_event_1 = {
1865                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1866                 check_added_monitors!(nodes[0], 1);
1867
1868                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1869                 assert_eq!(events.len(), 1);
1870                 SendEvent::from_event(events.remove(0))
1871         };
1872         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1873
1874         // Attempt to trigger a channel reserve violation --> payment failure.
1875         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1876         let recv_value_2 = chan_stat.value_to_self_msat - amt_msat_1 - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlcs + 1;
1877         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1878         let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1879
1880         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1881         let secp_ctx = Secp256k1::new();
1882         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1883         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1884         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1885         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1886         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1887         let msg = msgs::UpdateAddHTLC {
1888                 channel_id: chan.2,
1889                 htlc_id: 1,
1890                 amount_msat: htlc_msat + 1,
1891                 payment_hash: our_payment_hash_1,
1892                 cltv_expiry: htlc_cltv,
1893                 onion_routing_packet: onion_packet,
1894         };
1895
1896         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1897         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1898         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1899         assert_eq!(nodes[1].node.list_channels().len(), 1);
1900         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1901         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1902         check_added_monitors!(nodes[1], 1);
1903 }
1904
1905 #[test]
1906 fn test_inbound_outbound_capacity_is_not_zero() {
1907         let chanmon_cfgs = create_chanmon_cfgs(2);
1908         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1909         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1910         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1911         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1912         let channels0 = node_chanmgrs[0].list_channels();
1913         let channels1 = node_chanmgrs[1].list_channels();
1914         assert_eq!(channels0.len(), 1);
1915         assert_eq!(channels1.len(), 1);
1916
1917         assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1918         assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1919
1920         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1921         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1922 }
1923
1924 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1925         (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1926 }
1927
1928 #[test]
1929 fn test_channel_reserve_holding_cell_htlcs() {
1930         let chanmon_cfgs = create_chanmon_cfgs(3);
1931         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1932         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1933         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1934         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1935         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1936         let logger = test_utils::TestLogger::new();
1937
1938         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1939         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1940
1941         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1942         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1943
1944         macro_rules! get_route_and_payment_hash {
1945                 ($recv_value: expr) => {{
1946                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1947                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1948                         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), None, None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1949                         (route, payment_hash, payment_preimage)
1950                 }}
1951         }
1952
1953         macro_rules! expect_forward {
1954                 ($node: expr) => {{
1955                         let mut events = $node.node.get_and_clear_pending_msg_events();
1956                         assert_eq!(events.len(), 1);
1957                         check_added_monitors!($node, 1);
1958                         let payment_event = SendEvent::from_event(events.remove(0));
1959                         payment_event
1960                 }}
1961         }
1962
1963         let feemsat = 239; // somehow we know?
1964         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1965         let feerate = get_feerate!(nodes[0], chan_1.2);
1966
1967         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1968
1969         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1970         {
1971                 let (mut route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0);
1972                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1973                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1974                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1975                         assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
1976                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1977                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
1978         }
1979
1980         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1981         // nodes[0]'s wealth
1982         loop {
1983                 let amt_msat = recv_value_0 + total_fee_msat;
1984                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1985                 // Also, ensure that each payment has enough to be over the dust limit to
1986                 // ensure it'll be included in each commit tx fee calculation.
1987                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1988                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1989                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1990                         break;
1991                 }
1992                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1993
1994                 let (stat01_, stat11_, stat12_, stat22_) = (
1995                         get_channel_value_stat!(nodes[0], chan_1.2),
1996                         get_channel_value_stat!(nodes[1], chan_1.2),
1997                         get_channel_value_stat!(nodes[1], chan_2.2),
1998                         get_channel_value_stat!(nodes[2], chan_2.2),
1999                 );
2000
2001                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
2002                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
2003                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
2004                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
2005                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
2006         }
2007
2008         // adding pending output.
2009         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
2010         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2011         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2012         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2013         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2014         // cases where 1 msat over X amount will cause a payment failure, but anything less than
2015         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2016         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2017         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2018         // policy.
2019         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2020         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2021         let amt_msat_1 = recv_value_1 + total_fee_msat;
2022
2023         let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2024         let payment_event_1 = {
2025                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
2026                 check_added_monitors!(nodes[0], 1);
2027
2028                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2029                 assert_eq!(events.len(), 1);
2030                 SendEvent::from_event(events.remove(0))
2031         };
2032         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2033
2034         // channel reserve test with htlc pending output > 0
2035         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2036         {
2037                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2038                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2039                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2040                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2041         }
2042
2043         // split the rest to test holding cell
2044         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2045         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2046         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2047         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2048         {
2049                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2050                 assert_eq!(stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 + total_fee_msat + total_fee_msat + commit_tx_fee_3_htlcs), stat.channel_reserve_msat);
2051         }
2052
2053         // now see if they go through on both sides
2054         let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2055         // but this will stuck in the holding cell
2056         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2057         check_added_monitors!(nodes[0], 0);
2058         let events = nodes[0].node.get_and_clear_pending_events();
2059         assert_eq!(events.len(), 0);
2060
2061         // test with outbound holding cell amount > 0
2062         {
2063                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2064                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2065                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2066                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2067                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 2);
2068         }
2069
2070         let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2071         // this will also stuck in the holding cell
2072         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2073         check_added_monitors!(nodes[0], 0);
2074         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2075         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2076
2077         // flush the pending htlc
2078         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2079         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2080         check_added_monitors!(nodes[1], 1);
2081
2082         // the pending htlc should be promoted to committed
2083         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2084         check_added_monitors!(nodes[0], 1);
2085         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2086
2087         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2088         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2089         // No commitment_signed so get_event_msg's assert(len == 1) passes
2090         check_added_monitors!(nodes[0], 1);
2091
2092         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2093         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2094         check_added_monitors!(nodes[1], 1);
2095
2096         expect_pending_htlcs_forwardable!(nodes[1]);
2097
2098         let ref payment_event_11 = expect_forward!(nodes[1]);
2099         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2100         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2101
2102         expect_pending_htlcs_forwardable!(nodes[2]);
2103         expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2104
2105         // flush the htlcs in the holding cell
2106         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2107         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2108         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2109         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2110         expect_pending_htlcs_forwardable!(nodes[1]);
2111
2112         let ref payment_event_3 = expect_forward!(nodes[1]);
2113         assert_eq!(payment_event_3.msgs.len(), 2);
2114         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2115         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2116
2117         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2118         expect_pending_htlcs_forwardable!(nodes[2]);
2119
2120         let events = nodes[2].node.get_and_clear_pending_events();
2121         assert_eq!(events.len(), 2);
2122         match events[0] {
2123                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2124                         assert_eq!(our_payment_hash_21, *payment_hash);
2125                         assert_eq!(*payment_secret, None);
2126                         assert_eq!(recv_value_21, amt);
2127                 },
2128                 _ => panic!("Unexpected event"),
2129         }
2130         match events[1] {
2131                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2132                         assert_eq!(our_payment_hash_22, *payment_hash);
2133                         assert_eq!(None, *payment_secret);
2134                         assert_eq!(recv_value_22, amt);
2135                 },
2136                 _ => panic!("Unexpected event"),
2137         }
2138
2139         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2140         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2141         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2142
2143         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2144         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2145         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2146
2147         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2148         let expected_value_to_self = stat01.value_to_self_msat - (recv_value_1 + total_fee_msat) - (recv_value_21 + total_fee_msat) - (recv_value_22 + total_fee_msat) - (recv_value_3 + total_fee_msat);
2149         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2150         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2151         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2152
2153         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2154         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2155 }
2156
2157 #[test]
2158 fn channel_reserve_in_flight_removes() {
2159         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2160         // can send to its counterparty, but due to update ordering, the other side may not yet have
2161         // considered those HTLCs fully removed.
2162         // This tests that we don't count HTLCs which will not be included in the next remote
2163         // commitment transaction towards the reserve value (as it implies no commitment transaction
2164         // will be generated which violates the remote reserve value).
2165         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2166         // To test this we:
2167         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2168         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2169         //    you only consider the value of the first HTLC, it may not),
2170         //  * start routing a third HTLC from A to B,
2171         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2172         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2173         //  * deliver the first fulfill from B
2174         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2175         //    claim,
2176         //  * deliver A's response CS and RAA.
2177         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2178         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2179         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2180         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2181         let chanmon_cfgs = create_chanmon_cfgs(2);
2182         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2183         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2184         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2185         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2186         let logger = test_utils::TestLogger::new();
2187
2188         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2189         // Route the first two HTLCs.
2190         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2191         let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2192
2193         // Start routing the third HTLC (this is just used to get everyone in the right state).
2194         let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2195         let send_1 = {
2196                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2197                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
2198                 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2199                 check_added_monitors!(nodes[0], 1);
2200                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2201                 assert_eq!(events.len(), 1);
2202                 SendEvent::from_event(events.remove(0))
2203         };
2204
2205         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2206         // initial fulfill/CS.
2207         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2208         check_added_monitors!(nodes[1], 1);
2209         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2210
2211         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2212         // remove the second HTLC when we send the HTLC back from B to A.
2213         assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2214         check_added_monitors!(nodes[1], 1);
2215         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2216
2217         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2218         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2219         check_added_monitors!(nodes[0], 1);
2220         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2221         expect_payment_sent!(nodes[0], payment_preimage_1);
2222
2223         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2224         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2225         check_added_monitors!(nodes[1], 1);
2226         // B is already AwaitingRAA, so cant generate a CS here
2227         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2228
2229         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2230         check_added_monitors!(nodes[1], 1);
2231         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2232
2233         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2234         check_added_monitors!(nodes[0], 1);
2235         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2236
2237         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2238         check_added_monitors!(nodes[1], 1);
2239         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2240
2241         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2242         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2243         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2244         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2245         // on-chain as necessary).
2246         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2247         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2248         check_added_monitors!(nodes[0], 1);
2249         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2250         expect_payment_sent!(nodes[0], payment_preimage_2);
2251
2252         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2253         check_added_monitors!(nodes[1], 1);
2254         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2255
2256         expect_pending_htlcs_forwardable!(nodes[1]);
2257         expect_payment_received!(nodes[1], payment_hash_3, 100000);
2258
2259         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2260         // resolve the second HTLC from A's point of view.
2261         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2262         check_added_monitors!(nodes[0], 1);
2263         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2264
2265         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2266         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2267         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2268         let send_2 = {
2269                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2270                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &[], 10000, TEST_FINAL_CLTV, &logger).unwrap();
2271                 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2272                 check_added_monitors!(nodes[1], 1);
2273                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2274                 assert_eq!(events.len(), 1);
2275                 SendEvent::from_event(events.remove(0))
2276         };
2277
2278         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2279         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2280         check_added_monitors!(nodes[0], 1);
2281         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2282
2283         // Now just resolve all the outstanding messages/HTLCs for completeness...
2284
2285         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2286         check_added_monitors!(nodes[1], 1);
2287         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2288
2289         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2290         check_added_monitors!(nodes[1], 1);
2291
2292         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2293         check_added_monitors!(nodes[0], 1);
2294         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2295
2296         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2297         check_added_monitors!(nodes[1], 1);
2298         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2299
2300         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2301         check_added_monitors!(nodes[0], 1);
2302
2303         expect_pending_htlcs_forwardable!(nodes[0]);
2304         expect_payment_received!(nodes[0], payment_hash_4, 10000);
2305
2306         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2307         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2308 }
2309
2310 #[test]
2311 fn channel_monitor_network_test() {
2312         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2313         // tests that ChannelMonitor is able to recover from various states.
2314         let chanmon_cfgs = create_chanmon_cfgs(5);
2315         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2316         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2317         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2318
2319         // Create some initial channels
2320         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2321         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2322         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2323         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2324
2325         // Make sure all nodes are at the same starting height
2326         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2327         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2328         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2329         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2330         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2331
2332         // Rebalance the network a bit by relaying one payment through all the channels...
2333         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2334         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2335         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2336         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2337
2338         // Simple case with no pending HTLCs:
2339         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2340         check_added_monitors!(nodes[1], 1);
2341         check_closed_broadcast!(nodes[1], false);
2342         {
2343                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2344                 assert_eq!(node_txn.len(), 1);
2345                 mine_transaction(&nodes[0], &node_txn[0]);
2346                 check_added_monitors!(nodes[0], 1);
2347                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2348         }
2349         check_closed_broadcast!(nodes[0], true);
2350         assert_eq!(nodes[0].node.list_channels().len(), 0);
2351         assert_eq!(nodes[1].node.list_channels().len(), 1);
2352
2353         // One pending HTLC is discarded by the force-close:
2354         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2355
2356         // Simple case of one pending HTLC to HTLC-Timeout
2357         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2358         check_closed_broadcast!(nodes[1], false);
2359         check_added_monitors!(nodes[1], 1);
2360         {
2361                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2362                 mine_transaction(&nodes[2], &node_txn[0]);
2363                 check_added_monitors!(nodes[2], 1);
2364                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2365         }
2366         check_closed_broadcast!(nodes[2], true);
2367         assert_eq!(nodes[1].node.list_channels().len(), 0);
2368         assert_eq!(nodes[2].node.list_channels().len(), 1);
2369
2370         macro_rules! claim_funds {
2371                 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2372                         {
2373                                 assert!($node.node.claim_funds($preimage, &None, $amount));
2374                                 check_added_monitors!($node, 1);
2375
2376                                 let events = $node.node.get_and_clear_pending_msg_events();
2377                                 assert_eq!(events.len(), 1);
2378                                 match events[0] {
2379                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2380                                                 assert!(update_add_htlcs.is_empty());
2381                                                 assert!(update_fail_htlcs.is_empty());
2382                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2383                                         },
2384                                         _ => panic!("Unexpected event"),
2385                                 };
2386                         }
2387                 }
2388         }
2389
2390         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2391         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2392         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2393         check_added_monitors!(nodes[2], 1);
2394         check_closed_broadcast!(nodes[2], false);
2395         let node2_commitment_txid;
2396         {
2397                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2398                 node2_commitment_txid = node_txn[0].txid();
2399
2400                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2401                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2402                 mine_transaction(&nodes[3], &node_txn[0]);
2403                 check_added_monitors!(nodes[3], 1);
2404                 check_preimage_claim(&nodes[3], &node_txn);
2405         }
2406         check_closed_broadcast!(nodes[3], true);
2407         assert_eq!(nodes[2].node.list_channels().len(), 0);
2408         assert_eq!(nodes[3].node.list_channels().len(), 1);
2409
2410         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2411         // confusing us in the following tests.
2412         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().remove(&OutPoint { txid: chan_3.3.txid(), index: 0 }).unwrap();
2413
2414         // One pending HTLC to time out:
2415         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2416         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2417         // buffer space).
2418
2419         let (close_chan_update_1, close_chan_update_2) = {
2420                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2421                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2422                 assert_eq!(events.len(), 2);
2423                 let close_chan_update_1 = match events[0] {
2424                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2425                                 msg.clone()
2426                         },
2427                         _ => panic!("Unexpected event"),
2428                 };
2429                 match events[1] {
2430                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2431                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2432                         },
2433                         _ => panic!("Unexpected event"),
2434                 }
2435                 check_added_monitors!(nodes[3], 1);
2436
2437                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2438                 {
2439                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2440                         node_txn.retain(|tx| {
2441                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2442                                         false
2443                                 } else { true }
2444                         });
2445                 }
2446
2447                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2448
2449                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2450                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2451
2452                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2453                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2454                 assert_eq!(events.len(), 2);
2455                 let close_chan_update_2 = match events[0] {
2456                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2457                                 msg.clone()
2458                         },
2459                         _ => panic!("Unexpected event"),
2460                 };
2461                 match events[1] {
2462                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2463                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2464                         },
2465                         _ => panic!("Unexpected event"),
2466                 }
2467                 check_added_monitors!(nodes[4], 1);
2468                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2469
2470                 mine_transaction(&nodes[4], &node_txn[0]);
2471                 check_preimage_claim(&nodes[4], &node_txn);
2472                 (close_chan_update_1, close_chan_update_2)
2473         };
2474         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2475         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2476         assert_eq!(nodes[3].node.list_channels().len(), 0);
2477         assert_eq!(nodes[4].node.list_channels().len(), 0);
2478
2479         nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().insert(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon);
2480 }
2481
2482 #[test]
2483 fn test_justice_tx() {
2484         // Test justice txn built on revoked HTLC-Success tx, against both sides
2485         let mut alice_config = UserConfig::default();
2486         alice_config.channel_options.announced_channel = true;
2487         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2488         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2489         let mut bob_config = UserConfig::default();
2490         bob_config.channel_options.announced_channel = true;
2491         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2492         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2493         let user_cfgs = [Some(alice_config), Some(bob_config)];
2494         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2495         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2496         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2497         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2498         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2499         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2500         // Create some new channels:
2501         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2502
2503         // A pending HTLC which will be revoked:
2504         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2505         // Get the will-be-revoked local txn from nodes[0]
2506         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2507         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2508         assert_eq!(revoked_local_txn[0].input.len(), 1);
2509         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2510         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2511         assert_eq!(revoked_local_txn[1].input.len(), 1);
2512         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2513         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2514         // Revoke the old state
2515         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2516
2517         {
2518                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2519                 {
2520                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2521                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2522                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2523
2524                         check_spends!(node_txn[0], revoked_local_txn[0]);
2525                         node_txn.swap_remove(0);
2526                         node_txn.truncate(1);
2527                 }
2528                 check_added_monitors!(nodes[1], 1);
2529                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2530
2531                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2532                 // Verify broadcast of revoked HTLC-timeout
2533                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2534                 check_added_monitors!(nodes[0], 1);
2535                 // Broadcast revoked HTLC-timeout on node 1
2536                 mine_transaction(&nodes[1], &node_txn[1]);
2537                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2538         }
2539         get_announce_close_broadcast_events(&nodes, 0, 1);
2540
2541         assert_eq!(nodes[0].node.list_channels().len(), 0);
2542         assert_eq!(nodes[1].node.list_channels().len(), 0);
2543
2544         // We test justice_tx build by A on B's revoked HTLC-Success tx
2545         // Create some new channels:
2546         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2547         {
2548                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2549                 node_txn.clear();
2550         }
2551
2552         // A pending HTLC which will be revoked:
2553         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2554         // Get the will-be-revoked local txn from B
2555         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2556         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2557         assert_eq!(revoked_local_txn[0].input.len(), 1);
2558         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2559         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2560         // Revoke the old state
2561         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2562         {
2563                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2564                 {
2565                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2566                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2567                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2568
2569                         check_spends!(node_txn[0], revoked_local_txn[0]);
2570                         node_txn.swap_remove(0);
2571                 }
2572                 check_added_monitors!(nodes[0], 1);
2573                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2574
2575                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2576                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2577                 check_added_monitors!(nodes[1], 1);
2578                 mine_transaction(&nodes[0], &node_txn[1]);
2579                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2580         }
2581         get_announce_close_broadcast_events(&nodes, 0, 1);
2582         assert_eq!(nodes[0].node.list_channels().len(), 0);
2583         assert_eq!(nodes[1].node.list_channels().len(), 0);
2584 }
2585
2586 #[test]
2587 fn revoked_output_claim() {
2588         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2589         // transaction is broadcast by its counterparty
2590         let chanmon_cfgs = create_chanmon_cfgs(2);
2591         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2592         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2593         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2594         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2595         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2596         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2597         assert_eq!(revoked_local_txn.len(), 1);
2598         // Only output is the full channel value back to nodes[0]:
2599         assert_eq!(revoked_local_txn[0].output.len(), 1);
2600         // Send a payment through, updating everyone's latest commitment txn
2601         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2602
2603         // Inform nodes[1] that nodes[0] broadcast a stale tx
2604         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2605         check_added_monitors!(nodes[1], 1);
2606         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2607         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2608
2609         check_spends!(node_txn[0], revoked_local_txn[0]);
2610         check_spends!(node_txn[1], chan_1.3);
2611
2612         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2613         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2614         get_announce_close_broadcast_events(&nodes, 0, 1);
2615         check_added_monitors!(nodes[0], 1)
2616 }
2617
2618 #[test]
2619 fn claim_htlc_outputs_shared_tx() {
2620         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2621         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2622         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2623         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2624         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2625         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2626
2627         // Create some new channel:
2628         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2629
2630         // Rebalance the network to generate htlc in the two directions
2631         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2632         // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx
2633         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2634         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2635
2636         // Get the will-be-revoked local txn from node[0]
2637         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2638         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2639         assert_eq!(revoked_local_txn[0].input.len(), 1);
2640         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2641         assert_eq!(revoked_local_txn[1].input.len(), 1);
2642         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2643         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2644         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2645
2646         //Revoke the old state
2647         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2648
2649         {
2650                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2651                 check_added_monitors!(nodes[0], 1);
2652                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2653                 check_added_monitors!(nodes[1], 1);
2654                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2655                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2656
2657                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2658                 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2659
2660                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2661                 check_spends!(node_txn[0], revoked_local_txn[0]);
2662
2663                 let mut witness_lens = BTreeSet::new();
2664                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2665                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2666                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2667                 assert_eq!(witness_lens.len(), 3);
2668                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2669                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2670                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2671
2672                 // Next nodes[1] broadcasts its current local tx state:
2673                 assert_eq!(node_txn[1].input.len(), 1);
2674                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2675
2676                 assert_eq!(node_txn[2].input.len(), 1);
2677                 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2678                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2679                 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2680                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2681                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2682         }
2683         get_announce_close_broadcast_events(&nodes, 0, 1);
2684         assert_eq!(nodes[0].node.list_channels().len(), 0);
2685         assert_eq!(nodes[1].node.list_channels().len(), 0);
2686 }
2687
2688 #[test]
2689 fn claim_htlc_outputs_single_tx() {
2690         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2691         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2692         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2693         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2694         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2695         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2696
2697         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2698
2699         // Rebalance the network to generate htlc in the two directions
2700         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2701         // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
2702         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2703         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2704         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2705
2706         // Get the will-be-revoked local txn from node[0]
2707         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2708
2709         //Revoke the old state
2710         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2711
2712         {
2713                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2714                 check_added_monitors!(nodes[0], 1);
2715                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2716                 check_added_monitors!(nodes[1], 1);
2717                 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2718
2719                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2720                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2721
2722                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2723                 assert_eq!(node_txn.len(), 9);
2724                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2725                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2726                 // ChannelMonitor: bumped justice tx, after one increase, bumps on HTLC aren't generated not being substantial anymore, bump on revoked to_local isn't generated due to more room for expiration (2)
2727                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2728
2729                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2730                 assert_eq!(node_txn[0].input.len(), 1);
2731                 check_spends!(node_txn[0], chan_1.3);
2732                 assert_eq!(node_txn[1].input.len(), 1);
2733                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2734                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2735                 check_spends!(node_txn[1], node_txn[0]);
2736
2737                 // Justice transactions are indices 1-2-4
2738                 assert_eq!(node_txn[2].input.len(), 1);
2739                 assert_eq!(node_txn[3].input.len(), 1);
2740                 assert_eq!(node_txn[4].input.len(), 1);
2741
2742                 check_spends!(node_txn[2], revoked_local_txn[0]);
2743                 check_spends!(node_txn[3], revoked_local_txn[0]);
2744                 check_spends!(node_txn[4], revoked_local_txn[0]);
2745
2746                 let mut witness_lens = BTreeSet::new();
2747                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2748                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2749                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2750                 assert_eq!(witness_lens.len(), 3);
2751                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2752                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2753                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2754         }
2755         get_announce_close_broadcast_events(&nodes, 0, 1);
2756         assert_eq!(nodes[0].node.list_channels().len(), 0);
2757         assert_eq!(nodes[1].node.list_channels().len(), 0);
2758 }
2759
2760 #[test]
2761 fn test_htlc_on_chain_success() {
2762         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2763         // the preimage backward accordingly. So here we test that ChannelManager is
2764         // broadcasting the right event to other nodes in payment path.
2765         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2766         // A --------------------> B ----------------------> C (preimage)
2767         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2768         // commitment transaction was broadcast.
2769         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2770         // towards B.
2771         // B should be able to claim via preimage if A then broadcasts its local tx.
2772         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2773         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2774         // PaymentSent event).
2775
2776         let chanmon_cfgs = create_chanmon_cfgs(3);
2777         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2778         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2779         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2780
2781         // Create some initial channels
2782         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2783         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2784
2785         // Rebalance the network a bit by relaying one payment through all the channels...
2786         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2787         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2788
2789         let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2790         let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2791
2792         // Broadcast legit commitment tx from C on B's chain
2793         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2794         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2795         assert_eq!(commitment_tx.len(), 1);
2796         check_spends!(commitment_tx[0], chan_2.3);
2797         nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2798         nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2799         check_added_monitors!(nodes[2], 2);
2800         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2801         assert!(updates.update_add_htlcs.is_empty());
2802         assert!(updates.update_fail_htlcs.is_empty());
2803         assert!(updates.update_fail_malformed_htlcs.is_empty());
2804         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2805
2806         mine_transaction(&nodes[2], &commitment_tx[0]);
2807         check_closed_broadcast!(nodes[2], true);
2808         check_added_monitors!(nodes[2], 1);
2809         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx, 2*htlc-success tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
2810         assert_eq!(node_txn.len(), 5);
2811         assert_eq!(node_txn[0], node_txn[3]);
2812         assert_eq!(node_txn[1], node_txn[4]);
2813         assert_eq!(node_txn[2], commitment_tx[0]);
2814         check_spends!(node_txn[0], commitment_tx[0]);
2815         check_spends!(node_txn[1], commitment_tx[0]);
2816         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2817         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2818         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2819         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2820         assert_eq!(node_txn[0].lock_time, 0);
2821         assert_eq!(node_txn[1].lock_time, 0);
2822
2823         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2824         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2825         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2826         {
2827                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2828                 assert_eq!(added_monitors.len(), 1);
2829                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2830                 added_monitors.clear();
2831         }
2832         let events = nodes[1].node.get_and_clear_pending_msg_events();
2833         {
2834                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2835                 assert_eq!(added_monitors.len(), 2);
2836                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2837                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2838                 added_monitors.clear();
2839         }
2840         assert_eq!(events.len(), 3);
2841         match events[0] {
2842                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2843                 _ => panic!("Unexpected event"),
2844         }
2845         match events[1] {
2846                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2847                 _ => panic!("Unexpected event"),
2848         }
2849
2850         match events[2] {
2851                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2852                         assert!(update_add_htlcs.is_empty());
2853                         assert!(update_fail_htlcs.is_empty());
2854                         assert_eq!(update_fulfill_htlcs.len(), 1);
2855                         assert!(update_fail_malformed_htlcs.is_empty());
2856                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2857                 },
2858                 _ => panic!("Unexpected event"),
2859         };
2860         macro_rules! check_tx_local_broadcast {
2861                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2862                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2863                         assert_eq!(node_txn.len(), 5);
2864                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2865                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2866                         check_spends!(node_txn[0], $commitment_tx);
2867                         check_spends!(node_txn[1], $commitment_tx);
2868                         assert_ne!(node_txn[0].lock_time, 0);
2869                         assert_ne!(node_txn[1].lock_time, 0);
2870                         if $htlc_offered {
2871                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2872                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2873                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2874                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2875                         } else {
2876                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2877                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2878                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2879                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2880                         }
2881                         check_spends!(node_txn[2], $chan_tx);
2882                         check_spends!(node_txn[3], node_txn[2]);
2883                         check_spends!(node_txn[4], node_txn[2]);
2884                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2885                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2886                         assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2887                         assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2888                         assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2889                         assert_ne!(node_txn[3].lock_time, 0);
2890                         assert_ne!(node_txn[4].lock_time, 0);
2891                         node_txn.clear();
2892                 } }
2893         }
2894         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2895         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2896         // timeout-claim of the output that nodes[2] just claimed via success.
2897         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2898
2899         // Broadcast legit commitment tx from A on B's chain
2900         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2901         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2902         check_spends!(commitment_tx[0], chan_1.3);
2903         mine_transaction(&nodes[1], &commitment_tx[0]);
2904         check_closed_broadcast!(nodes[1], true);
2905         check_added_monitors!(nodes[1], 1);
2906         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2907         assert_eq!(node_txn.len(), 4);
2908         check_spends!(node_txn[0], commitment_tx[0]);
2909         assert_eq!(node_txn[0].input.len(), 2);
2910         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2911         assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2912         assert_eq!(node_txn[0].lock_time, 0);
2913         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2914         check_spends!(node_txn[1], chan_1.3);
2915         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2916         check_spends!(node_txn[2], node_txn[1]);
2917         check_spends!(node_txn[3], node_txn[1]);
2918         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2919         // we already checked the same situation with A.
2920
2921         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2922         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2923         connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] });
2924         check_closed_broadcast!(nodes[0], true);
2925         check_added_monitors!(nodes[0], 1);
2926         let events = nodes[0].node.get_and_clear_pending_events();
2927         assert_eq!(events.len(), 2);
2928         let mut first_claimed = false;
2929         for event in events {
2930                 match event {
2931                         Event::PaymentSent { payment_preimage } => {
2932                                 if payment_preimage == our_payment_preimage {
2933                                         assert!(!first_claimed);
2934                                         first_claimed = true;
2935                                 } else {
2936                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2937                                 }
2938                         },
2939                         _ => panic!("Unexpected event"),
2940                 }
2941         }
2942         check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2943 }
2944
2945 #[test]
2946 fn test_htlc_on_chain_timeout() {
2947         // Test that in case of a unilateral close onchain, we detect the state of output and
2948         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2949         // broadcasting the right event to other nodes in payment path.
2950         // A ------------------> B ----------------------> C (timeout)
2951         //    B's commitment tx                 C's commitment tx
2952         //            \                                  \
2953         //         B's HTLC timeout tx               B's timeout tx
2954
2955         let chanmon_cfgs = create_chanmon_cfgs(3);
2956         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2957         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2958         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2959
2960         // Create some intial channels
2961         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2962         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2963
2964         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2965         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2966         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2967
2968         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2969
2970         // Broadcast legit commitment tx from C on B's chain
2971         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2972         check_spends!(commitment_tx[0], chan_2.3);
2973         nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2974         check_added_monitors!(nodes[2], 0);
2975         expect_pending_htlcs_forwardable!(nodes[2]);
2976         check_added_monitors!(nodes[2], 1);
2977
2978         let events = nodes[2].node.get_and_clear_pending_msg_events();
2979         assert_eq!(events.len(), 1);
2980         match events[0] {
2981                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2982                         assert!(update_add_htlcs.is_empty());
2983                         assert!(!update_fail_htlcs.is_empty());
2984                         assert!(update_fulfill_htlcs.is_empty());
2985                         assert!(update_fail_malformed_htlcs.is_empty());
2986                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2987                 },
2988                 _ => panic!("Unexpected event"),
2989         };
2990         mine_transaction(&nodes[2], &commitment_tx[0]);
2991         check_closed_broadcast!(nodes[2], true);
2992         check_added_monitors!(nodes[2], 1);
2993         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2994         assert_eq!(node_txn.len(), 1);
2995         check_spends!(node_txn[0], chan_2.3);
2996         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2997
2998         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2999         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3000         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3001         mine_transaction(&nodes[1], &commitment_tx[0]);
3002         let timeout_tx;
3003         {
3004                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3005                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
3006                 assert_eq!(node_txn[0], node_txn[3]);
3007                 assert_eq!(node_txn[1], node_txn[4]);
3008
3009                 check_spends!(node_txn[2], commitment_tx[0]);
3010                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3011
3012                 check_spends!(node_txn[0], chan_2.3);
3013                 check_spends!(node_txn[1], node_txn[0]);
3014                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3015                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3016
3017                 timeout_tx = node_txn[2].clone();
3018                 node_txn.clear();
3019         }
3020
3021         mine_transaction(&nodes[1], &timeout_tx);
3022         check_added_monitors!(nodes[1], 1);
3023         check_closed_broadcast!(nodes[1], true);
3024         {
3025                 // B will rebroadcast a fee-bumped timeout transaction here.
3026                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3027                 assert_eq!(node_txn.len(), 1);
3028                 check_spends!(node_txn[0], commitment_tx[0]);
3029         }
3030
3031         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3032         {
3033                 // B will rebroadcast its own holder commitment transaction here...just because
3034                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3035                 assert_eq!(node_txn.len(), 1);
3036                 check_spends!(node_txn[0], chan_2.3);
3037         }
3038
3039         expect_pending_htlcs_forwardable!(nodes[1]);
3040         check_added_monitors!(nodes[1], 1);
3041         let events = nodes[1].node.get_and_clear_pending_msg_events();
3042         assert_eq!(events.len(), 1);
3043         match events[0] {
3044                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3045                         assert!(update_add_htlcs.is_empty());
3046                         assert!(!update_fail_htlcs.is_empty());
3047                         assert!(update_fulfill_htlcs.is_empty());
3048                         assert!(update_fail_malformed_htlcs.is_empty());
3049                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3050                 },
3051                 _ => panic!("Unexpected event"),
3052         };
3053
3054         // Broadcast legit commitment tx from B on A's chain
3055         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3056         check_spends!(commitment_tx[0], chan_1.3);
3057
3058         mine_transaction(&nodes[0], &commitment_tx[0]);
3059
3060         check_closed_broadcast!(nodes[0], true);
3061         check_added_monitors!(nodes[0], 1);
3062         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3063         assert_eq!(node_txn.len(), 3);
3064         check_spends!(node_txn[0], commitment_tx[0]);
3065         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3066         check_spends!(node_txn[1], chan_1.3);
3067         check_spends!(node_txn[2], node_txn[1]);
3068         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3069         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3070 }
3071
3072 #[test]
3073 fn test_simple_commitment_revoked_fail_backward() {
3074         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3075         // and fail backward accordingly.
3076
3077         let chanmon_cfgs = create_chanmon_cfgs(3);
3078         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3079         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3080         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3081
3082         // Create some initial channels
3083         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3084         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3085
3086         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3087         // Get the will-be-revoked local txn from nodes[2]
3088         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3089         // Revoke the old state
3090         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3091
3092         let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3093
3094         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3095         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3096         check_added_monitors!(nodes[1], 1);
3097         check_closed_broadcast!(nodes[1], true);
3098
3099         expect_pending_htlcs_forwardable!(nodes[1]);
3100         check_added_monitors!(nodes[1], 1);
3101         let events = nodes[1].node.get_and_clear_pending_msg_events();
3102         assert_eq!(events.len(), 1);
3103         match events[0] {
3104                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3105                         assert!(update_add_htlcs.is_empty());
3106                         assert_eq!(update_fail_htlcs.len(), 1);
3107                         assert!(update_fulfill_htlcs.is_empty());
3108                         assert!(update_fail_malformed_htlcs.is_empty());
3109                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3110
3111                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3112                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3113
3114                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3115                         assert_eq!(events.len(), 1);
3116                         match events[0] {
3117                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3118                                 _ => panic!("Unexpected event"),
3119                         }
3120                         expect_payment_failed!(nodes[0], payment_hash, false);
3121                 },
3122                 _ => panic!("Unexpected event"),
3123         }
3124 }
3125
3126 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3127         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3128         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3129         // commitment transaction anymore.
3130         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3131         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3132         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3133         // technically disallowed and we should probably handle it reasonably.
3134         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3135         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3136         // transactions:
3137         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3138         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3139         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3140         //   and once they revoke the previous commitment transaction (allowing us to send a new
3141         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3142         let chanmon_cfgs = create_chanmon_cfgs(3);
3143         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3144         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3145         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3146
3147         // Create some initial channels
3148         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3149         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3150
3151         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3152         // Get the will-be-revoked local txn from nodes[2]
3153         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3154         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3155         // Revoke the old state
3156         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3157
3158         let value = if use_dust {
3159                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3160                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3161                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3162         } else { 3000000 };
3163
3164         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3165         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3166         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3167
3168         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3169         expect_pending_htlcs_forwardable!(nodes[2]);
3170         check_added_monitors!(nodes[2], 1);
3171         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3172         assert!(updates.update_add_htlcs.is_empty());
3173         assert!(updates.update_fulfill_htlcs.is_empty());
3174         assert!(updates.update_fail_malformed_htlcs.is_empty());
3175         assert_eq!(updates.update_fail_htlcs.len(), 1);
3176         assert!(updates.update_fee.is_none());
3177         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3178         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3179         // Drop the last RAA from 3 -> 2
3180
3181         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3182         expect_pending_htlcs_forwardable!(nodes[2]);
3183         check_added_monitors!(nodes[2], 1);
3184         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3185         assert!(updates.update_add_htlcs.is_empty());
3186         assert!(updates.update_fulfill_htlcs.is_empty());
3187         assert!(updates.update_fail_malformed_htlcs.is_empty());
3188         assert_eq!(updates.update_fail_htlcs.len(), 1);
3189         assert!(updates.update_fee.is_none());
3190         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3191         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3192         check_added_monitors!(nodes[1], 1);
3193         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3194         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3195         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3196         check_added_monitors!(nodes[2], 1);
3197
3198         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3199         expect_pending_htlcs_forwardable!(nodes[2]);
3200         check_added_monitors!(nodes[2], 1);
3201         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3202         assert!(updates.update_add_htlcs.is_empty());
3203         assert!(updates.update_fulfill_htlcs.is_empty());
3204         assert!(updates.update_fail_malformed_htlcs.is_empty());
3205         assert_eq!(updates.update_fail_htlcs.len(), 1);
3206         assert!(updates.update_fee.is_none());
3207         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3208         // At this point first_payment_hash has dropped out of the latest two commitment
3209         // transactions that nodes[1] is tracking...
3210         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3211         check_added_monitors!(nodes[1], 1);
3212         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3213         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3214         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3215         check_added_monitors!(nodes[2], 1);
3216
3217         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3218         // on nodes[2]'s RAA.
3219         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3220         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3221         let logger = test_utils::TestLogger::new();
3222         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3223         nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3224         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3225         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3226         check_added_monitors!(nodes[1], 0);
3227
3228         if deliver_bs_raa {
3229                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3230                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3231                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3232                 check_added_monitors!(nodes[1], 1);
3233                 let events = nodes[1].node.get_and_clear_pending_events();
3234                 assert_eq!(events.len(), 1);
3235                 match events[0] {
3236                         Event::PendingHTLCsForwardable { .. } => { },
3237                         _ => panic!("Unexpected event"),
3238                 };
3239                 // Deliberately don't process the pending fail-back so they all fail back at once after
3240                 // block connection just like the !deliver_bs_raa case
3241         }
3242
3243         let mut failed_htlcs = HashSet::new();
3244         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3245
3246         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3247         check_added_monitors!(nodes[1], 1);
3248         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3249
3250         let events = nodes[1].node.get_and_clear_pending_events();
3251         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3252         match events[0] {
3253                 Event::PaymentFailed { ref payment_hash, .. } => {
3254                         assert_eq!(*payment_hash, fourth_payment_hash);
3255                 },
3256                 _ => panic!("Unexpected event"),
3257         }
3258         if !deliver_bs_raa {
3259                 match events[1] {
3260                         Event::PendingHTLCsForwardable { .. } => { },
3261                         _ => panic!("Unexpected event"),
3262                 };
3263         }
3264         nodes[1].node.process_pending_htlc_forwards();
3265         check_added_monitors!(nodes[1], 1);
3266
3267         let events = nodes[1].node.get_and_clear_pending_msg_events();
3268         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3269         match events[if deliver_bs_raa { 1 } else { 0 }] {
3270                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3271                 _ => panic!("Unexpected event"),
3272         }
3273         match events[if deliver_bs_raa { 2 } else { 1 }] {
3274                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3275                         assert_eq!(channel_id, chan_2.2);
3276                         assert_eq!(data.as_str(), "Commitment or closing transaction was confirmed on chain.");
3277                 },
3278                 _ => panic!("Unexpected event"),
3279         }
3280         if deliver_bs_raa {
3281                 match events[0] {
3282                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3283                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3284                                 assert_eq!(update_add_htlcs.len(), 1);
3285                                 assert!(update_fulfill_htlcs.is_empty());
3286                                 assert!(update_fail_htlcs.is_empty());
3287                                 assert!(update_fail_malformed_htlcs.is_empty());
3288                         },
3289                         _ => panic!("Unexpected event"),
3290                 }
3291         }
3292         match events[if deliver_bs_raa { 3 } else { 2 }] {
3293                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3294                         assert!(update_add_htlcs.is_empty());
3295                         assert_eq!(update_fail_htlcs.len(), 3);
3296                         assert!(update_fulfill_htlcs.is_empty());
3297                         assert!(update_fail_malformed_htlcs.is_empty());
3298                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3299
3300                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3301                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3302                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3303
3304                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3305
3306                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3307                         // If we delivered B's RAA we got an unknown preimage error, not something
3308                         // that we should update our routing table for.
3309                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3310                         for event in events {
3311                                 match event {
3312                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3313                                         _ => panic!("Unexpected event"),
3314                                 }
3315                         }
3316                         let events = nodes[0].node.get_and_clear_pending_events();
3317                         assert_eq!(events.len(), 3);
3318                         match events[0] {
3319                                 Event::PaymentFailed { ref payment_hash, .. } => {
3320                                         assert!(failed_htlcs.insert(payment_hash.0));
3321                                 },
3322                                 _ => panic!("Unexpected event"),
3323                         }
3324                         match events[1] {
3325                                 Event::PaymentFailed { ref payment_hash, .. } => {
3326                                         assert!(failed_htlcs.insert(payment_hash.0));
3327                                 },
3328                                 _ => panic!("Unexpected event"),
3329                         }
3330                         match events[2] {
3331                                 Event::PaymentFailed { ref payment_hash, .. } => {
3332                                         assert!(failed_htlcs.insert(payment_hash.0));
3333                                 },
3334                                 _ => panic!("Unexpected event"),
3335                         }
3336                 },
3337                 _ => panic!("Unexpected event"),
3338         }
3339
3340         assert!(failed_htlcs.contains(&first_payment_hash.0));
3341         assert!(failed_htlcs.contains(&second_payment_hash.0));
3342         assert!(failed_htlcs.contains(&third_payment_hash.0));
3343 }
3344
3345 #[test]
3346 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3347         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3348         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3349         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3350         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3351 }
3352
3353 #[test]
3354 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3355         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3356         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3357         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3358         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3359 }
3360
3361 #[test]
3362 fn fail_backward_pending_htlc_upon_channel_failure() {
3363         let chanmon_cfgs = create_chanmon_cfgs(2);
3364         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3365         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3366         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3367         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3368         let logger = test_utils::TestLogger::new();
3369
3370         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3371         {
3372                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3373                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3374                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3375                 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3376                 check_added_monitors!(nodes[0], 1);
3377
3378                 let payment_event = {
3379                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3380                         assert_eq!(events.len(), 1);
3381                         SendEvent::from_event(events.remove(0))
3382                 };
3383                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3384                 assert_eq!(payment_event.msgs.len(), 1);
3385         }
3386
3387         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3388         let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3389         {
3390                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3391                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3392                 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3393                 check_added_monitors!(nodes[0], 0);
3394
3395                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3396         }
3397
3398         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3399         {
3400                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3401
3402                 let secp_ctx = Secp256k1::new();
3403                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3404                 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3405                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3406                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3407                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3408                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3409                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3410
3411                 // Send a 0-msat update_add_htlc to fail the channel.
3412                 let update_add_htlc = msgs::UpdateAddHTLC {
3413                         channel_id: chan.2,
3414                         htlc_id: 0,
3415                         amount_msat: 0,
3416                         payment_hash,
3417                         cltv_expiry,
3418                         onion_routing_packet,
3419                 };
3420                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3421         }
3422
3423         // Check that Alice fails backward the pending HTLC from the second payment.
3424         expect_payment_failed!(nodes[0], failed_payment_hash, true);
3425         check_closed_broadcast!(nodes[0], true);
3426         check_added_monitors!(nodes[0], 1);
3427 }
3428
3429 #[test]
3430 fn test_htlc_ignore_latest_remote_commitment() {
3431         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3432         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3433         let chanmon_cfgs = create_chanmon_cfgs(2);
3434         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3435         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3436         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3437         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3438
3439         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3440         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3441         check_closed_broadcast!(nodes[0], true);
3442         check_added_monitors!(nodes[0], 1);
3443
3444         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3445         assert_eq!(node_txn.len(), 2);
3446
3447         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3448         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3449         check_closed_broadcast!(nodes[1], true);
3450         check_added_monitors!(nodes[1], 1);
3451
3452         // Duplicate the connect_block call since this may happen due to other listeners
3453         // registering new transactions
3454         header.prev_blockhash = header.block_hash();
3455         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3456 }
3457
3458 #[test]
3459 fn test_force_close_fail_back() {
3460         // Check which HTLCs are failed-backwards on channel force-closure
3461         let chanmon_cfgs = create_chanmon_cfgs(3);
3462         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3463         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3464         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3465         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3466         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3467         let logger = test_utils::TestLogger::new();
3468
3469         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3470
3471         let mut payment_event = {
3472                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3473                 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(), None, None, &Vec::new(), 1000000, 42, &logger).unwrap();
3474                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3475                 check_added_monitors!(nodes[0], 1);
3476
3477                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3478                 assert_eq!(events.len(), 1);
3479                 SendEvent::from_event(events.remove(0))
3480         };
3481
3482         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3483         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3484
3485         expect_pending_htlcs_forwardable!(nodes[1]);
3486
3487         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3488         assert_eq!(events_2.len(), 1);
3489         payment_event = SendEvent::from_event(events_2.remove(0));
3490         assert_eq!(payment_event.msgs.len(), 1);
3491
3492         check_added_monitors!(nodes[1], 1);
3493         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3494         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3495         check_added_monitors!(nodes[2], 1);
3496         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3497
3498         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3499         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3500         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3501
3502         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3503         check_closed_broadcast!(nodes[2], true);
3504         check_added_monitors!(nodes[2], 1);
3505         let tx = {
3506                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3507                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3508                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3509                 // back to nodes[1] upon timeout otherwise.
3510                 assert_eq!(node_txn.len(), 1);
3511                 node_txn.remove(0)
3512         };
3513
3514         mine_transaction(&nodes[1], &tx);
3515
3516         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3517         check_closed_broadcast!(nodes[1], true);
3518         check_added_monitors!(nodes[1], 1);
3519
3520         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3521         {
3522                 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3523                 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3524                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3525         }
3526         mine_transaction(&nodes[2], &tx);
3527         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3528         assert_eq!(node_txn.len(), 1);
3529         assert_eq!(node_txn[0].input.len(), 1);
3530         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3531         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3532         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3533
3534         check_spends!(node_txn[0], tx);
3535 }
3536
3537 #[test]
3538 fn test_simple_peer_disconnect() {
3539         // Test that we can reconnect when there are no lost messages
3540         let chanmon_cfgs = create_chanmon_cfgs(3);
3541         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3542         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3543         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3544         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3545         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3546
3547         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3548         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3549         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3550
3551         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3552         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3553         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3554         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3555
3556         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3557         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3558         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3559
3560         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3561         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3562         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3563         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3564
3565         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3566         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3567
3568         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3569         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3570
3571         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3572         {
3573                 let events = nodes[0].node.get_and_clear_pending_events();
3574                 assert_eq!(events.len(), 2);
3575                 match events[0] {
3576                         Event::PaymentSent { payment_preimage } => {
3577                                 assert_eq!(payment_preimage, payment_preimage_3);
3578                         },
3579                         _ => panic!("Unexpected event"),
3580                 }
3581                 match events[1] {
3582                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3583                                 assert_eq!(payment_hash, payment_hash_5);
3584                                 assert!(rejected_by_dest);
3585                         },
3586                         _ => panic!("Unexpected event"),
3587                 }
3588         }
3589
3590         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3591         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3592 }
3593
3594 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3595         // Test that we can reconnect when in-flight HTLC updates get dropped
3596         let chanmon_cfgs = create_chanmon_cfgs(2);
3597         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3598         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3599         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3600         if messages_delivered == 0 {
3601                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3602                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3603         } else {
3604                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3605         }
3606
3607         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3608
3609         let logger = test_utils::TestLogger::new();
3610         let payment_event = {
3611                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3612                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3613                         &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3614                         &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3615                 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3616                 check_added_monitors!(nodes[0], 1);
3617
3618                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3619                 assert_eq!(events.len(), 1);
3620                 SendEvent::from_event(events.remove(0))
3621         };
3622         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3623
3624         if messages_delivered < 2 {
3625                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3626         } else {
3627                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3628                 if messages_delivered >= 3 {
3629                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3630                         check_added_monitors!(nodes[1], 1);
3631                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3632
3633                         if messages_delivered >= 4 {
3634                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3635                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3636                                 check_added_monitors!(nodes[0], 1);
3637
3638                                 if messages_delivered >= 5 {
3639                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3640                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3641                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3642                                         check_added_monitors!(nodes[0], 1);
3643
3644                                         if messages_delivered >= 6 {
3645                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3646                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3647                                                 check_added_monitors!(nodes[1], 1);
3648                                         }
3649                                 }
3650                         }
3651                 }
3652         }
3653
3654         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3655         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3656         if messages_delivered < 3 {
3657                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3658                 // received on either side, both sides will need to resend them.
3659                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3660         } else if messages_delivered == 3 {
3661                 // nodes[0] still wants its RAA + commitment_signed
3662                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3663         } else if messages_delivered == 4 {
3664                 // nodes[0] still wants its commitment_signed
3665                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3666         } else if messages_delivered == 5 {
3667                 // nodes[1] still wants its final RAA
3668                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3669         } else if messages_delivered == 6 {
3670                 // Everything was delivered...
3671                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3672         }
3673
3674         let events_1 = nodes[1].node.get_and_clear_pending_events();
3675         assert_eq!(events_1.len(), 1);
3676         match events_1[0] {
3677                 Event::PendingHTLCsForwardable { .. } => { },
3678                 _ => panic!("Unexpected event"),
3679         };
3680
3681         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3682         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3683         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3684
3685         nodes[1].node.process_pending_htlc_forwards();
3686
3687         let events_2 = nodes[1].node.get_and_clear_pending_events();
3688         assert_eq!(events_2.len(), 1);
3689         match events_2[0] {
3690                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3691                         assert_eq!(payment_hash_1, *payment_hash);
3692                         assert_eq!(*payment_secret, None);
3693                         assert_eq!(amt, 1000000);
3694                 },
3695                 _ => panic!("Unexpected event"),
3696         }
3697
3698         nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3699         check_added_monitors!(nodes[1], 1);
3700
3701         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3702         assert_eq!(events_3.len(), 1);
3703         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3704                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3705                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3706                         assert!(updates.update_add_htlcs.is_empty());
3707                         assert!(updates.update_fail_htlcs.is_empty());
3708                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3709                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3710                         assert!(updates.update_fee.is_none());
3711                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3712                 },
3713                 _ => panic!("Unexpected event"),
3714         };
3715
3716         if messages_delivered >= 1 {
3717                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3718
3719                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3720                 assert_eq!(events_4.len(), 1);
3721                 match events_4[0] {
3722                         Event::PaymentSent { ref payment_preimage } => {
3723                                 assert_eq!(payment_preimage_1, *payment_preimage);
3724                         },
3725                         _ => panic!("Unexpected event"),
3726                 }
3727
3728                 if messages_delivered >= 2 {
3729                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3730                         check_added_monitors!(nodes[0], 1);
3731                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3732
3733                         if messages_delivered >= 3 {
3734                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3735                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3736                                 check_added_monitors!(nodes[1], 1);
3737
3738                                 if messages_delivered >= 4 {
3739                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3740                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3741                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3742                                         check_added_monitors!(nodes[1], 1);
3743
3744                                         if messages_delivered >= 5 {
3745                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3746                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3747                                                 check_added_monitors!(nodes[0], 1);
3748                                         }
3749                                 }
3750                         }
3751                 }
3752         }
3753
3754         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3755         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3756         if messages_delivered < 2 {
3757                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3758                 //TODO: Deduplicate PaymentSent events, then enable this if:
3759                 //if messages_delivered < 1 {
3760                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3761                         assert_eq!(events_4.len(), 1);
3762                         match events_4[0] {
3763                                 Event::PaymentSent { ref payment_preimage } => {
3764                                         assert_eq!(payment_preimage_1, *payment_preimage);
3765                                 },
3766                                 _ => panic!("Unexpected event"),
3767                         }
3768                 //}
3769         } else if messages_delivered == 2 {
3770                 // nodes[0] still wants its RAA + commitment_signed
3771                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3772         } else if messages_delivered == 3 {
3773                 // nodes[0] still wants its commitment_signed
3774                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3775         } else if messages_delivered == 4 {
3776                 // nodes[1] still wants its final RAA
3777                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3778         } else if messages_delivered == 5 {
3779                 // Everything was delivered...
3780                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3781         }
3782
3783         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3784         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3785         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3786
3787         // Channel should still work fine...
3788         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3789         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3790                 &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3791                 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3792         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3793         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3794 }
3795
3796 #[test]
3797 fn test_drop_messages_peer_disconnect_a() {
3798         do_test_drop_messages_peer_disconnect(0);
3799         do_test_drop_messages_peer_disconnect(1);
3800         do_test_drop_messages_peer_disconnect(2);
3801         do_test_drop_messages_peer_disconnect(3);
3802 }
3803
3804 #[test]
3805 fn test_drop_messages_peer_disconnect_b() {
3806         do_test_drop_messages_peer_disconnect(4);
3807         do_test_drop_messages_peer_disconnect(5);
3808         do_test_drop_messages_peer_disconnect(6);
3809 }
3810
3811 #[test]
3812 fn test_funding_peer_disconnect() {
3813         // Test that we can lock in our funding tx while disconnected
3814         let chanmon_cfgs = create_chanmon_cfgs(2);
3815         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3816         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3817         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3818         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3819
3820         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3821         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3822
3823         confirm_transaction(&nodes[0], &tx);
3824         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3825         assert_eq!(events_1.len(), 1);
3826         match events_1[0] {
3827                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3828                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3829                 },
3830                 _ => panic!("Unexpected event"),
3831         }
3832
3833         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3834
3835         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3836         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3837
3838         confirm_transaction(&nodes[1], &tx);
3839         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3840         assert_eq!(events_2.len(), 2);
3841         let funding_locked = match events_2[0] {
3842                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3843                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3844                         msg.clone()
3845                 },
3846                 _ => panic!("Unexpected event"),
3847         };
3848         let bs_announcement_sigs = match events_2[1] {
3849                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3850                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3851                         msg.clone()
3852                 },
3853                 _ => panic!("Unexpected event"),
3854         };
3855
3856         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3857
3858         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3859         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3860         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3861         assert_eq!(events_3.len(), 2);
3862         let as_announcement_sigs = match events_3[0] {
3863                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3864                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3865                         msg.clone()
3866                 },
3867                 _ => panic!("Unexpected event"),
3868         };
3869         let (as_announcement, as_update) = match events_3[1] {
3870                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3871                         (msg.clone(), update_msg.clone())
3872                 },
3873                 _ => panic!("Unexpected event"),
3874         };
3875
3876         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3877         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3878         assert_eq!(events_4.len(), 1);
3879         let (_, bs_update) = match events_4[0] {
3880                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3881                         (msg.clone(), update_msg.clone())
3882                 },
3883                 _ => panic!("Unexpected event"),
3884         };
3885
3886         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3887         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3888         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3889
3890         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3891         let logger = test_utils::TestLogger::new();
3892         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3893         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3894         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3895 }
3896
3897 #[test]
3898 fn test_drop_messages_peer_disconnect_dual_htlc() {
3899         // Test that we can handle reconnecting when both sides of a channel have pending
3900         // commitment_updates when we disconnect.
3901         let chanmon_cfgs = create_chanmon_cfgs(2);
3902         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3903         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3904         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3905         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3906         let logger = test_utils::TestLogger::new();
3907
3908         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3909
3910         // Now try to send a second payment which will fail to send
3911         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3912         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3913         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3914         nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3915         check_added_monitors!(nodes[0], 1);
3916
3917         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3918         assert_eq!(events_1.len(), 1);
3919         match events_1[0] {
3920                 MessageSendEvent::UpdateHTLCs { .. } => {},
3921                 _ => panic!("Unexpected event"),
3922         }
3923
3924         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3925         check_added_monitors!(nodes[1], 1);
3926
3927         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3928         assert_eq!(events_2.len(), 1);
3929         match events_2[0] {
3930                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
3931                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3932                         assert!(update_add_htlcs.is_empty());
3933                         assert_eq!(update_fulfill_htlcs.len(), 1);
3934                         assert!(update_fail_htlcs.is_empty());
3935                         assert!(update_fail_malformed_htlcs.is_empty());
3936                         assert!(update_fee.is_none());
3937
3938                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3939                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3940                         assert_eq!(events_3.len(), 1);
3941                         match events_3[0] {
3942                                 Event::PaymentSent { ref payment_preimage } => {
3943                                         assert_eq!(*payment_preimage, payment_preimage_1);
3944                                 },
3945                                 _ => panic!("Unexpected event"),
3946                         }
3947
3948                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3949                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3950                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3951                         check_added_monitors!(nodes[0], 1);
3952                 },
3953                 _ => panic!("Unexpected event"),
3954         }
3955
3956         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3957         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3958
3959         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3960         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3961         assert_eq!(reestablish_1.len(), 1);
3962         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3963         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3964         assert_eq!(reestablish_2.len(), 1);
3965
3966         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3967         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3968         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3969         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3970
3971         assert!(as_resp.0.is_none());
3972         assert!(bs_resp.0.is_none());
3973
3974         assert!(bs_resp.1.is_none());
3975         assert!(bs_resp.2.is_none());
3976
3977         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3978
3979         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3980         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3981         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3982         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3983         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3984         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3985         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3986         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3987         // No commitment_signed so get_event_msg's assert(len == 1) passes
3988         check_added_monitors!(nodes[1], 1);
3989
3990         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3991         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3992         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3993         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3994         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3995         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3996         assert!(bs_second_commitment_signed.update_fee.is_none());
3997         check_added_monitors!(nodes[1], 1);
3998
3999         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4000         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4001         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4002         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4003         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4004         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4005         assert!(as_commitment_signed.update_fee.is_none());
4006         check_added_monitors!(nodes[0], 1);
4007
4008         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4009         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4010         // No commitment_signed so get_event_msg's assert(len == 1) passes
4011         check_added_monitors!(nodes[0], 1);
4012
4013         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4014         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4015         // No commitment_signed so get_event_msg's assert(len == 1) passes
4016         check_added_monitors!(nodes[1], 1);
4017
4018         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4019         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4020         check_added_monitors!(nodes[1], 1);
4021
4022         expect_pending_htlcs_forwardable!(nodes[1]);
4023
4024         let events_5 = nodes[1].node.get_and_clear_pending_events();
4025         assert_eq!(events_5.len(), 1);
4026         match events_5[0] {
4027                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4028                         assert_eq!(payment_hash_2, *payment_hash);
4029                         assert_eq!(*payment_secret, None);
4030                 },
4031                 _ => panic!("Unexpected event"),
4032         }
4033
4034         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4035         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4036         check_added_monitors!(nodes[0], 1);
4037
4038         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4039 }
4040
4041 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4042         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4043         // to avoid our counterparty failing the channel.
4044         let chanmon_cfgs = create_chanmon_cfgs(2);
4045         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4046         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4047         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4048
4049         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4050         let logger = test_utils::TestLogger::new();
4051
4052         let our_payment_hash = if send_partial_mpp {
4053                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4054                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4055                 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4056                 let payment_secret = PaymentSecret([0xdb; 32]);
4057                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4058                 // indicates there are more HTLCs coming.
4059                 let cur_height = CHAN_CONFIRM_DEPTH + 1; // route_payment calls send_payment, which adds 1 to the current height. So we do the same here to match.
4060                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height).unwrap();
4061                 check_added_monitors!(nodes[0], 1);
4062                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4063                 assert_eq!(events.len(), 1);
4064                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4065                 // hop should *not* yet generate any PaymentReceived event(s).
4066                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4067                 our_payment_hash
4068         } else {
4069                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4070         };
4071
4072         let mut block = Block {
4073                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4074                 txdata: vec![],
4075         };
4076         connect_block(&nodes[0], &block);
4077         connect_block(&nodes[1], &block);
4078         for _ in CHAN_CONFIRM_DEPTH + 2 ..TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4079                 block.header.prev_blockhash = block.block_hash();
4080                 connect_block(&nodes[0], &block);
4081                 connect_block(&nodes[1], &block);
4082         }
4083
4084         expect_pending_htlcs_forwardable!(nodes[1]);
4085
4086         check_added_monitors!(nodes[1], 1);
4087         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4088         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4089         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4090         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4091         assert!(htlc_timeout_updates.update_fee.is_none());
4092
4093         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4094         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4095         // 100_000 msat as u64, followed by a height of TEST_FINAL_CLTV + 2 as u32
4096         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4097         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(TEST_FINAL_CLTV + 2));
4098         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4099 }
4100
4101 #[test]
4102 fn test_htlc_timeout() {
4103         do_test_htlc_timeout(true);
4104         do_test_htlc_timeout(false);
4105 }
4106
4107 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4108         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4109         let chanmon_cfgs = create_chanmon_cfgs(3);
4110         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4111         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4112         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4113         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4114         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4115
4116         // Make sure all nodes are at the same starting height
4117         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4118         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4119         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4120
4121         let logger = test_utils::TestLogger::new();
4122
4123         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4124         let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4125         {
4126                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4127                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4128                 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4129         }
4130         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4131         check_added_monitors!(nodes[1], 1);
4132
4133         // Now attempt to route a second payment, which should be placed in the holding cell
4134         let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4135         if forwarded_htlc {
4136                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4137                 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(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4138                 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4139                 check_added_monitors!(nodes[0], 1);
4140                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4141                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4142                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4143                 expect_pending_htlcs_forwardable!(nodes[1]);
4144                 check_added_monitors!(nodes[1], 0);
4145         } else {
4146                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4147                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4148                 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4149                 check_added_monitors!(nodes[1], 0);
4150         }
4151
4152         connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4153         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4154         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4155         connect_blocks(&nodes[1], 1);
4156
4157         if forwarded_htlc {
4158                 expect_pending_htlcs_forwardable!(nodes[1]);
4159                 check_added_monitors!(nodes[1], 1);
4160                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4161                 assert_eq!(fail_commit.len(), 1);
4162                 match fail_commit[0] {
4163                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4164                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4165                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4166                         },
4167                         _ => unreachable!(),
4168                 }
4169                 expect_payment_failed!(nodes[0], second_payment_hash, false);
4170                 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4171                         match update {
4172                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4173                                 _ => panic!("Unexpected event"),
4174                         }
4175                 } else {
4176                         panic!("Unexpected event");
4177                 }
4178         } else {
4179                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4180         }
4181 }
4182
4183 #[test]
4184 fn test_holding_cell_htlc_add_timeouts() {
4185         do_test_holding_cell_htlc_add_timeouts(false);
4186         do_test_holding_cell_htlc_add_timeouts(true);
4187 }
4188
4189 #[test]
4190 fn test_invalid_channel_announcement() {
4191         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4192         let secp_ctx = Secp256k1::new();
4193         let chanmon_cfgs = create_chanmon_cfgs(2);
4194         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4195         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4196         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4197
4198         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4199
4200         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4201         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4202         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4203         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4204
4205         nodes[0].net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
4206
4207         let as_bitcoin_key = as_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4208         let bs_bitcoin_key = bs_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4209
4210         let as_network_key = nodes[0].node.get_our_node_id();
4211         let bs_network_key = nodes[1].node.get_our_node_id();
4212
4213         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4214
4215         let mut chan_announcement;
4216
4217         macro_rules! dummy_unsigned_msg {
4218                 () => {
4219                         msgs::UnsignedChannelAnnouncement {
4220                                 features: ChannelFeatures::known(),
4221                                 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4222                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4223                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4224                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4225                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4226                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4227                                 excess_data: Vec::new(),
4228                         };
4229                 }
4230         }
4231
4232         macro_rules! sign_msg {
4233                 ($unsigned_msg: expr) => {
4234                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4235                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_signer().inner.funding_key);
4236                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_signer().inner.funding_key);
4237                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4238                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4239                         chan_announcement = msgs::ChannelAnnouncement {
4240                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4241                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4242                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4243                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4244                                 contents: $unsigned_msg
4245                         }
4246                 }
4247         }
4248
4249         let unsigned_msg = dummy_unsigned_msg!();
4250         sign_msg!(unsigned_msg);
4251         assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4252         let _ = nodes[0].net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
4253
4254         // Configured with Network::Testnet
4255         let mut unsigned_msg = dummy_unsigned_msg!();
4256         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4257         sign_msg!(unsigned_msg);
4258         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4259
4260         let mut unsigned_msg = dummy_unsigned_msg!();
4261         unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4262         sign_msg!(unsigned_msg);
4263         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4264 }
4265
4266 #[test]
4267 fn test_no_txn_manager_serialize_deserialize() {
4268         let chanmon_cfgs = create_chanmon_cfgs(2);
4269         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4270         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4271         let logger: test_utils::TestLogger;
4272         let fee_estimator: test_utils::TestFeeEstimator;
4273         let persister: test_utils::TestPersister;
4274         let new_chain_monitor: test_utils::TestChainMonitor;
4275         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4276         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4277
4278         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4279
4280         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4281
4282         let nodes_0_serialized = nodes[0].node.encode();
4283         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4284         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4285
4286         logger = test_utils::TestLogger::new();
4287         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4288         persister = test_utils::TestPersister::new();
4289         let keys_manager = &chanmon_cfgs[0].keys_manager;
4290         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4291         nodes[0].chain_monitor = &new_chain_monitor;
4292         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4293         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4294                 &mut chan_0_monitor_read, keys_manager).unwrap();
4295         assert!(chan_0_monitor_read.is_empty());
4296
4297         let mut nodes_0_read = &nodes_0_serialized[..];
4298         let config = UserConfig::default();
4299         let (_, nodes_0_deserialized_tmp) = {
4300                 let mut channel_monitors = HashMap::new();
4301                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4302                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4303                         default_config: config,
4304                         keys_manager,
4305                         fee_estimator: &fee_estimator,
4306                         chain_monitor: nodes[0].chain_monitor,
4307                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4308                         logger: &logger,
4309                         channel_monitors,
4310                 }).unwrap()
4311         };
4312         nodes_0_deserialized = nodes_0_deserialized_tmp;
4313         assert!(nodes_0_read.is_empty());
4314
4315         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4316         nodes[0].node = &nodes_0_deserialized;
4317         assert_eq!(nodes[0].node.list_channels().len(), 1);
4318         check_added_monitors!(nodes[0], 1);
4319
4320         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4321         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4322         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4323         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4324
4325         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4326         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4327         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4328         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4329
4330         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4331         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4332         for node in nodes.iter() {
4333                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4334                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4335                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4336         }
4337
4338         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4339 }
4340
4341 #[test]
4342 fn test_manager_serialize_deserialize_events() {
4343         // This test makes sure the events field in ChannelManager survives de/serialization
4344         let chanmon_cfgs = create_chanmon_cfgs(2);
4345         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4346         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4347         let fee_estimator: test_utils::TestFeeEstimator;
4348         let persister: test_utils::TestPersister;
4349         let logger: test_utils::TestLogger;
4350         let new_chain_monitor: test_utils::TestChainMonitor;
4351         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4352         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4353
4354         // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4355         let channel_value = 100000;
4356         let push_msat = 10001;
4357         let a_flags = InitFeatures::known();
4358         let b_flags = InitFeatures::known();
4359         let node_a = nodes.remove(0);
4360         let node_b = nodes.remove(0);
4361         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4362         node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id()));
4363         node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id()));
4364
4365         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4366
4367         node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4368         check_added_monitors!(node_a, 0);
4369
4370         node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id()));
4371         {
4372                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4373                 assert_eq!(added_monitors.len(), 1);
4374                 assert_eq!(added_monitors[0].0, funding_output);
4375                 added_monitors.clear();
4376         }
4377
4378         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id()));
4379         {
4380                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4381                 assert_eq!(added_monitors.len(), 1);
4382                 assert_eq!(added_monitors[0].0, funding_output);
4383                 added_monitors.clear();
4384         }
4385         // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4386
4387         nodes.push(node_a);
4388         nodes.push(node_b);
4389
4390         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4391         let nodes_0_serialized = nodes[0].node.encode();
4392         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4393         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4394
4395         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4396         logger = test_utils::TestLogger::new();
4397         persister = test_utils::TestPersister::new();
4398         let keys_manager = &chanmon_cfgs[0].keys_manager;
4399         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4400         nodes[0].chain_monitor = &new_chain_monitor;
4401         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4402         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4403                 &mut chan_0_monitor_read, keys_manager).unwrap();
4404         assert!(chan_0_monitor_read.is_empty());
4405
4406         let mut nodes_0_read = &nodes_0_serialized[..];
4407         let config = UserConfig::default();
4408         let (_, nodes_0_deserialized_tmp) = {
4409                 let mut channel_monitors = HashMap::new();
4410                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4411                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4412                         default_config: config,
4413                         keys_manager,
4414                         fee_estimator: &fee_estimator,
4415                         chain_monitor: nodes[0].chain_monitor,
4416                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4417                         logger: &logger,
4418                         channel_monitors,
4419                 }).unwrap()
4420         };
4421         nodes_0_deserialized = nodes_0_deserialized_tmp;
4422         assert!(nodes_0_read.is_empty());
4423
4424         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4425
4426         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4427         nodes[0].node = &nodes_0_deserialized;
4428
4429         // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4430         let events_4 = nodes[0].node.get_and_clear_pending_events();
4431         assert_eq!(events_4.len(), 1);
4432         match events_4[0] {
4433                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4434                         assert_eq!(user_channel_id, 42);
4435                         assert_eq!(*funding_txo, funding_output);
4436                 },
4437                 _ => panic!("Unexpected event"),
4438         };
4439
4440         // Make sure the channel is functioning as though the de/serialization never happened
4441         assert_eq!(nodes[0].node.list_channels().len(), 1);
4442         check_added_monitors!(nodes[0], 1);
4443
4444         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4445         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4446         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4447         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4448
4449         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4450         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4451         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4452         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4453
4454         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4455         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4456         for node in nodes.iter() {
4457                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4458                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4459                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4460         }
4461
4462         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4463 }
4464
4465 #[test]
4466 fn test_simple_manager_serialize_deserialize() {
4467         let chanmon_cfgs = create_chanmon_cfgs(2);
4468         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4469         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4470         let logger: test_utils::TestLogger;
4471         let fee_estimator: test_utils::TestFeeEstimator;
4472         let persister: test_utils::TestPersister;
4473         let new_chain_monitor: test_utils::TestChainMonitor;
4474         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4475         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4476         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4477
4478         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4479         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4480
4481         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4482
4483         let nodes_0_serialized = nodes[0].node.encode();
4484         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4485         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4486
4487         logger = test_utils::TestLogger::new();
4488         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4489         persister = test_utils::TestPersister::new();
4490         let keys_manager = &chanmon_cfgs[0].keys_manager;
4491         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4492         nodes[0].chain_monitor = &new_chain_monitor;
4493         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4494         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4495                 &mut chan_0_monitor_read, keys_manager).unwrap();
4496         assert!(chan_0_monitor_read.is_empty());
4497
4498         let mut nodes_0_read = &nodes_0_serialized[..];
4499         let (_, nodes_0_deserialized_tmp) = {
4500                 let mut channel_monitors = HashMap::new();
4501                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4502                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4503                         default_config: UserConfig::default(),
4504                         keys_manager,
4505                         fee_estimator: &fee_estimator,
4506                         chain_monitor: nodes[0].chain_monitor,
4507                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4508                         logger: &logger,
4509                         channel_monitors,
4510                 }).unwrap()
4511         };
4512         nodes_0_deserialized = nodes_0_deserialized_tmp;
4513         assert!(nodes_0_read.is_empty());
4514
4515         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4516         nodes[0].node = &nodes_0_deserialized;
4517         check_added_monitors!(nodes[0], 1);
4518
4519         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4520
4521         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4522         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4523 }
4524
4525 #[test]
4526 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4527         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4528         let chanmon_cfgs = create_chanmon_cfgs(4);
4529         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4530         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4531         let logger: test_utils::TestLogger;
4532         let fee_estimator: test_utils::TestFeeEstimator;
4533         let persister: test_utils::TestPersister;
4534         let new_chain_monitor: test_utils::TestChainMonitor;
4535         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4536         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4537         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4538         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4539         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4540
4541         let mut node_0_stale_monitors_serialized = Vec::new();
4542         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4543                 let mut writer = test_utils::TestVecWriter(Vec::new());
4544                 monitor.1.write(&mut writer).unwrap();
4545                 node_0_stale_monitors_serialized.push(writer.0);
4546         }
4547
4548         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4549
4550         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4551         let nodes_0_serialized = nodes[0].node.encode();
4552
4553         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4554         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4555         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4556         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4557
4558         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4559         // nodes[3])
4560         let mut node_0_monitors_serialized = Vec::new();
4561         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4562                 let mut writer = test_utils::TestVecWriter(Vec::new());
4563                 monitor.1.write(&mut writer).unwrap();
4564                 node_0_monitors_serialized.push(writer.0);
4565         }
4566
4567         logger = test_utils::TestLogger::new();
4568         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4569         persister = test_utils::TestPersister::new();
4570         let keys_manager = &chanmon_cfgs[0].keys_manager;
4571         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4572         nodes[0].chain_monitor = &new_chain_monitor;
4573
4574
4575         let mut node_0_stale_monitors = Vec::new();
4576         for serialized in node_0_stale_monitors_serialized.iter() {
4577                 let mut read = &serialized[..];
4578                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4579                 assert!(read.is_empty());
4580                 node_0_stale_monitors.push(monitor);
4581         }
4582
4583         let mut node_0_monitors = Vec::new();
4584         for serialized in node_0_monitors_serialized.iter() {
4585                 let mut read = &serialized[..];
4586                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4587                 assert!(read.is_empty());
4588                 node_0_monitors.push(monitor);
4589         }
4590
4591         let mut nodes_0_read = &nodes_0_serialized[..];
4592         if let Err(msgs::DecodeError::InvalidValue) =
4593                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4594                 default_config: UserConfig::default(),
4595                 keys_manager,
4596                 fee_estimator: &fee_estimator,
4597                 chain_monitor: nodes[0].chain_monitor,
4598                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4599                 logger: &logger,
4600                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4601         }) { } else {
4602                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4603         };
4604
4605         let mut nodes_0_read = &nodes_0_serialized[..];
4606         let (_, nodes_0_deserialized_tmp) =
4607                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4608                 default_config: UserConfig::default(),
4609                 keys_manager,
4610                 fee_estimator: &fee_estimator,
4611                 chain_monitor: nodes[0].chain_monitor,
4612                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4613                 logger: &logger,
4614                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4615         }).unwrap();
4616         nodes_0_deserialized = nodes_0_deserialized_tmp;
4617         assert!(nodes_0_read.is_empty());
4618
4619         { // Channel close should result in a commitment tx and an HTLC tx
4620                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4621                 assert_eq!(txn.len(), 2);
4622                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4623                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4624         }
4625
4626         for monitor in node_0_monitors.drain(..) {
4627                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4628                 check_added_monitors!(nodes[0], 1);
4629         }
4630         nodes[0].node = &nodes_0_deserialized;
4631
4632         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4633         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4634         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4635         //... and we can even still claim the payment!
4636         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4637
4638         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4639         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4640         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4641         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4642         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4643         assert_eq!(msg_events.len(), 1);
4644         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4645                 match action {
4646                         &ErrorAction::SendErrorMessage { ref msg } => {
4647                                 assert_eq!(msg.channel_id, channel_id);
4648                         },
4649                         _ => panic!("Unexpected event!"),
4650                 }
4651         }
4652 }
4653
4654 macro_rules! check_spendable_outputs {
4655         ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4656                 {
4657                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4658                         let mut txn = Vec::new();
4659                         let mut all_outputs = Vec::new();
4660                         let secp_ctx = Secp256k1::new();
4661                         for event in events.drain(..) {
4662                                 match event {
4663                                         Event::SpendableOutputs { mut outputs } => {
4664                                                 for outp in outputs.drain(..) {
4665                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4666                                                         all_outputs.push(outp);
4667                                                 }
4668                                         },
4669                                         _ => panic!("Unexpected event"),
4670                                 };
4671                         }
4672                         if all_outputs.len() > 1 {
4673                                 if let Ok(tx) = $keysinterface.backing.spend_spendable_outputs(&all_outputs.iter().map(|a| a).collect::<Vec<_>>(), Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx) {
4674                                         txn.push(tx);
4675                                 }
4676                         }
4677                         txn
4678                 }
4679         }
4680 }
4681
4682 #[test]
4683 fn test_claim_sizeable_push_msat() {
4684         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4685         let chanmon_cfgs = create_chanmon_cfgs(2);
4686         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4687         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4688         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4689
4690         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4691         nodes[1].node.force_close_channel(&chan.2).unwrap();
4692         check_closed_broadcast!(nodes[1], true);
4693         check_added_monitors!(nodes[1], 1);
4694         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4695         assert_eq!(node_txn.len(), 1);
4696         check_spends!(node_txn[0], chan.3);
4697         assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
4698
4699         mine_transaction(&nodes[1], &node_txn[0]);
4700         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4701
4702         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4703         assert_eq!(spend_txn.len(), 1);
4704         check_spends!(spend_txn[0], node_txn[0]);
4705 }
4706
4707 #[test]
4708 fn test_claim_on_remote_sizeable_push_msat() {
4709         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4710         // to_remote output is encumbered by a P2WPKH
4711         let chanmon_cfgs = create_chanmon_cfgs(2);
4712         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4713         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4714         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4715
4716         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4717         nodes[0].node.force_close_channel(&chan.2).unwrap();
4718         check_closed_broadcast!(nodes[0], true);
4719         check_added_monitors!(nodes[0], 1);
4720
4721         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4722         assert_eq!(node_txn.len(), 1);
4723         check_spends!(node_txn[0], chan.3);
4724         assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
4725
4726         mine_transaction(&nodes[1], &node_txn[0]);
4727         check_closed_broadcast!(nodes[1], true);
4728         check_added_monitors!(nodes[1], 1);
4729         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4730
4731         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4732         assert_eq!(spend_txn.len(), 1);
4733         check_spends!(spend_txn[0], node_txn[0]);
4734 }
4735
4736 #[test]
4737 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4738         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4739         // to_remote output is encumbered by a P2WPKH
4740
4741         let chanmon_cfgs = create_chanmon_cfgs(2);
4742         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4743         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4744         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4745
4746         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4747         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4748         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4749         assert_eq!(revoked_local_txn[0].input.len(), 1);
4750         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4751
4752         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4753         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4754         check_closed_broadcast!(nodes[1], true);
4755         check_added_monitors!(nodes[1], 1);
4756
4757         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4758         mine_transaction(&nodes[1], &node_txn[0]);
4759         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4760
4761         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4762         assert_eq!(spend_txn.len(), 3);
4763         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4764         check_spends!(spend_txn[1], node_txn[0]);
4765         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4766 }
4767
4768 #[test]
4769 fn test_static_spendable_outputs_preimage_tx() {
4770         let chanmon_cfgs = create_chanmon_cfgs(2);
4771         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4772         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4773         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4774
4775         // Create some initial channels
4776         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4777
4778         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4779
4780         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4781         assert_eq!(commitment_tx[0].input.len(), 1);
4782         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4783
4784         // Settle A's commitment tx on B's chain
4785         assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4786         check_added_monitors!(nodes[1], 1);
4787         mine_transaction(&nodes[1], &commitment_tx[0]);
4788         check_added_monitors!(nodes[1], 1);
4789         let events = nodes[1].node.get_and_clear_pending_msg_events();
4790         match events[0] {
4791                 MessageSendEvent::UpdateHTLCs { .. } => {},
4792                 _ => panic!("Unexpected event"),
4793         }
4794         match events[1] {
4795                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4796                 _ => panic!("Unexepected event"),
4797         }
4798
4799         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4800         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4801         assert_eq!(node_txn.len(), 3);
4802         check_spends!(node_txn[0], commitment_tx[0]);
4803         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4804         check_spends!(node_txn[1], chan_1.3);
4805         check_spends!(node_txn[2], node_txn[1]);
4806
4807         mine_transaction(&nodes[1], &node_txn[0]);
4808         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4809
4810         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4811         assert_eq!(spend_txn.len(), 1);
4812         check_spends!(spend_txn[0], node_txn[0]);
4813 }
4814
4815 #[test]
4816 fn test_static_spendable_outputs_timeout_tx() {
4817         let chanmon_cfgs = create_chanmon_cfgs(2);
4818         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4819         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4820         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4821
4822         // Create some initial channels
4823         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4824
4825         // Rebalance the network a bit by relaying one payment through all the channels ...
4826         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4827
4828         let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4829
4830         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4831         assert_eq!(commitment_tx[0].input.len(), 1);
4832         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4833
4834         // Settle A's commitment tx on B' chain
4835         mine_transaction(&nodes[1], &commitment_tx[0]);
4836         check_added_monitors!(nodes[1], 1);
4837         let events = nodes[1].node.get_and_clear_pending_msg_events();
4838         match events[0] {
4839                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4840                 _ => panic!("Unexpected event"),
4841         }
4842
4843         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4844         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4845         assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4846         check_spends!(node_txn[0],  commitment_tx[0].clone());
4847         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4848         check_spends!(node_txn[1], chan_1.3.clone());
4849         check_spends!(node_txn[2], node_txn[1]);
4850
4851         mine_transaction(&nodes[1], &node_txn[0]);
4852         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4853         expect_payment_failed!(nodes[1], our_payment_hash, true);
4854
4855         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4856         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4857         check_spends!(spend_txn[0], commitment_tx[0]);
4858         check_spends!(spend_txn[1], node_txn[0]);
4859         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4860 }
4861
4862 #[test]
4863 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4864         let chanmon_cfgs = create_chanmon_cfgs(2);
4865         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4866         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4867         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4868
4869         // Create some initial channels
4870         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4871
4872         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4873         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4874         assert_eq!(revoked_local_txn[0].input.len(), 1);
4875         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4876
4877         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4878
4879         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4880         check_closed_broadcast!(nodes[1], true);
4881         check_added_monitors!(nodes[1], 1);
4882
4883         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4884         assert_eq!(node_txn.len(), 2);
4885         assert_eq!(node_txn[0].input.len(), 2);
4886         check_spends!(node_txn[0], revoked_local_txn[0]);
4887
4888         mine_transaction(&nodes[1], &node_txn[0]);
4889         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4890
4891         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4892         assert_eq!(spend_txn.len(), 1);
4893         check_spends!(spend_txn[0], node_txn[0]);
4894 }
4895
4896 #[test]
4897 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4898         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4899         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4900         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4901         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4902         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4903
4904         // Create some initial channels
4905         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4906
4907         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4908         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4909         assert_eq!(revoked_local_txn[0].input.len(), 1);
4910         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4911
4912         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4913
4914         // A will generate HTLC-Timeout from revoked commitment tx
4915         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4916         check_closed_broadcast!(nodes[0], true);
4917         check_added_monitors!(nodes[0], 1);
4918
4919         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4920         assert_eq!(revoked_htlc_txn.len(), 2);
4921         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4922         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4923         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4924         check_spends!(revoked_htlc_txn[1], chan_1.3);
4925
4926         // B will generate justice tx from A's revoked commitment/HTLC tx
4927         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4928         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4929         check_closed_broadcast!(nodes[1], true);
4930         check_added_monitors!(nodes[1], 1);
4931
4932         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4933         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4934         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4935         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4936         // transactions next...
4937         assert_eq!(node_txn[0].input.len(), 3);
4938         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4939
4940         assert_eq!(node_txn[1].input.len(), 2);
4941         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4942         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4943                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4944         } else {
4945                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4946                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4947         }
4948
4949         assert_eq!(node_txn[2].input.len(), 1);
4950         check_spends!(node_txn[2], chan_1.3);
4951
4952         mine_transaction(&nodes[1], &node_txn[1]);
4953         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4954
4955         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4956         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4957         assert_eq!(spend_txn.len(), 1);
4958         assert_eq!(spend_txn[0].input.len(), 1);
4959         check_spends!(spend_txn[0], node_txn[1]);
4960 }
4961
4962 #[test]
4963 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4964         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4965         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4966         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4967         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4968         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4969
4970         // Create some initial channels
4971         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4972
4973         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4974         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4975         assert_eq!(revoked_local_txn[0].input.len(), 1);
4976         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4977
4978         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4979         assert_eq!(revoked_local_txn[0].output.len(), 2);
4980
4981         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4982
4983         // B will generate HTLC-Success from revoked commitment tx
4984         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4985         check_closed_broadcast!(nodes[1], true);
4986         check_added_monitors!(nodes[1], 1);
4987         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4988
4989         assert_eq!(revoked_htlc_txn.len(), 2);
4990         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4991         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4992         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4993
4994         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4995         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4996         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4997
4998         // A will generate justice tx from B's revoked commitment/HTLC tx
4999         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5000         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5001         check_closed_broadcast!(nodes[0], true);
5002         check_added_monitors!(nodes[0], 1);
5003
5004         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5005         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5006
5007         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5008         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5009         // transactions next...
5010         assert_eq!(node_txn[0].input.len(), 2);
5011         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5012         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5013                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5014         } else {
5015                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5016                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5017         }
5018
5019         assert_eq!(node_txn[1].input.len(), 1);
5020         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5021
5022         check_spends!(node_txn[2], chan_1.3);
5023
5024         mine_transaction(&nodes[0], &node_txn[1]);
5025         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5026
5027         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5028         // didn't try to generate any new transactions.
5029
5030         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5031         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5032         assert_eq!(spend_txn.len(), 3);
5033         assert_eq!(spend_txn[0].input.len(), 1);
5034         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5035         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5036         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5037         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5038 }
5039
5040 #[test]
5041 fn test_onchain_to_onchain_claim() {
5042         // Test that in case of channel closure, we detect the state of output and claim HTLC
5043         // on downstream peer's remote commitment tx.
5044         // First, have C claim an HTLC against its own latest commitment transaction.
5045         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5046         // channel.
5047         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5048         // gets broadcast.
5049
5050         let chanmon_cfgs = create_chanmon_cfgs(3);
5051         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5052         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5053         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5054
5055         // Create some initial channels
5056         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5057         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5058
5059         // Rebalance the network a bit by relaying one payment through all the channels ...
5060         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5061         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5062
5063         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5064         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5065         check_spends!(commitment_tx[0], chan_2.3);
5066         nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5067         check_added_monitors!(nodes[2], 1);
5068         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5069         assert!(updates.update_add_htlcs.is_empty());
5070         assert!(updates.update_fail_htlcs.is_empty());
5071         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5072         assert!(updates.update_fail_malformed_htlcs.is_empty());
5073
5074         mine_transaction(&nodes[2], &commitment_tx[0]);
5075         check_closed_broadcast!(nodes[2], true);
5076         check_added_monitors!(nodes[2], 1);
5077
5078         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5079         assert_eq!(c_txn.len(), 3);
5080         assert_eq!(c_txn[0], c_txn[2]);
5081         assert_eq!(commitment_tx[0], c_txn[1]);
5082         check_spends!(c_txn[1], chan_2.3);
5083         check_spends!(c_txn[2], c_txn[1]);
5084         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5085         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5086         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5087         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5088
5089         // So we broadcast C's commitment tx and HTLC-Success on B's chain, we should successfully be able to extract preimage and update downstream monitor
5090         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5091         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5092         {
5093                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5094                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5095                 assert_eq!(b_txn.len(), 3);
5096                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5097                 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5098                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5099                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5100                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5101                 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5102                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5103                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5104                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5105                 b_txn.clear();
5106         }
5107         check_added_monitors!(nodes[1], 1);
5108         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5109         assert_eq!(msg_events.len(), 3);
5110         check_added_monitors!(nodes[1], 1);
5111         match msg_events[0] {
5112                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5113                 _ => panic!("Unexpected event"),
5114         }
5115         match msg_events[1] {
5116                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5117                 _ => panic!("Unexpected event"),
5118         }
5119         match msg_events[2] {
5120                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
5121                         assert!(update_add_htlcs.is_empty());
5122                         assert!(update_fail_htlcs.is_empty());
5123                         assert_eq!(update_fulfill_htlcs.len(), 1);
5124                         assert!(update_fail_malformed_htlcs.is_empty());
5125                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5126                 },
5127                 _ => panic!("Unexpected event"),
5128         };
5129         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5130         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5131         mine_transaction(&nodes[1], &commitment_tx[0]);
5132         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5133         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5134         assert_eq!(b_txn.len(), 3);
5135         check_spends!(b_txn[1], chan_1.3);
5136         check_spends!(b_txn[2], b_txn[1]);
5137         check_spends!(b_txn[0], commitment_tx[0]);
5138         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5139         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5140         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5141
5142         check_closed_broadcast!(nodes[1], true);
5143         check_added_monitors!(nodes[1], 1);
5144 }
5145
5146 #[test]
5147 fn test_duplicate_payment_hash_one_failure_one_success() {
5148         // Topology : A --> B --> C
5149         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5150         let chanmon_cfgs = create_chanmon_cfgs(3);
5151         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5152         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5153         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5154
5155         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5156         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5157
5158         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5159         *nodes[0].network_payment_count.borrow_mut() -= 1;
5160         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5161
5162         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5163         assert_eq!(commitment_txn[0].input.len(), 1);
5164         check_spends!(commitment_txn[0], chan_2.3);
5165
5166         mine_transaction(&nodes[1], &commitment_txn[0]);
5167         check_closed_broadcast!(nodes[1], true);
5168         check_added_monitors!(nodes[1], 1);
5169
5170         let htlc_timeout_tx;
5171         { // Extract one of the two HTLC-Timeout transaction
5172                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5173                 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5174                 assert_eq!(node_txn.len(), 5);
5175                 check_spends!(node_txn[0], commitment_txn[0]);
5176                 assert_eq!(node_txn[0].input.len(), 1);
5177                 check_spends!(node_txn[1], commitment_txn[0]);
5178                 assert_eq!(node_txn[1].input.len(), 1);
5179                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5180                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5181                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5182                 check_spends!(node_txn[2], chan_2.3);
5183                 check_spends!(node_txn[3], node_txn[2]);
5184                 check_spends!(node_txn[4], node_txn[2]);
5185                 htlc_timeout_tx = node_txn[1].clone();
5186         }
5187
5188         nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5189         mine_transaction(&nodes[2], &commitment_txn[0]);
5190         check_added_monitors!(nodes[2], 3);
5191         let events = nodes[2].node.get_and_clear_pending_msg_events();
5192         match events[0] {
5193                 MessageSendEvent::UpdateHTLCs { .. } => {},
5194                 _ => panic!("Unexpected event"),
5195         }
5196         match events[1] {
5197                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5198                 _ => panic!("Unexepected event"),
5199         }
5200         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5201         assert_eq!(htlc_success_txn.len(), 5); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs), ChannelManager: local commitment tx + HTLC-Success txn (*2 due to 2-HTLC outputs)
5202         check_spends!(htlc_success_txn[2], chan_2.3);
5203         check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5204         check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5205         assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5206         assert_eq!(htlc_success_txn[0].input.len(), 1);
5207         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5208         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5209         assert_eq!(htlc_success_txn[1].input.len(), 1);
5210         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5211         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5212         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5213         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5214
5215         mine_transaction(&nodes[1], &htlc_timeout_tx);
5216         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5217         expect_pending_htlcs_forwardable!(nodes[1]);
5218         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5219         assert!(htlc_updates.update_add_htlcs.is_empty());
5220         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5221         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5222         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5223         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5224         check_added_monitors!(nodes[1], 1);
5225
5226         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5227         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5228         {
5229                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5230                 let events = nodes[0].node.get_and_clear_pending_msg_events();
5231                 assert_eq!(events.len(), 1);
5232                 match events[0] {
5233                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
5234                         },
5235                         _ => { panic!("Unexpected event"); }
5236                 }
5237         }
5238         expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5239
5240         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5241         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5242         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5243         assert!(updates.update_add_htlcs.is_empty());
5244         assert!(updates.update_fail_htlcs.is_empty());
5245         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5246         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5247         assert!(updates.update_fail_malformed_htlcs.is_empty());
5248         check_added_monitors!(nodes[1], 1);
5249
5250         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5251         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5252
5253         let events = nodes[0].node.get_and_clear_pending_events();
5254         match events[0] {
5255                 Event::PaymentSent { ref payment_preimage } => {
5256                         assert_eq!(*payment_preimage, our_payment_preimage);
5257                 }
5258                 _ => panic!("Unexpected event"),
5259         }
5260 }
5261
5262 #[test]
5263 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5264         let chanmon_cfgs = create_chanmon_cfgs(2);
5265         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5266         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5267         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5268
5269         // Create some initial channels
5270         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5271
5272         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5273         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5274         assert_eq!(local_txn.len(), 1);
5275         assert_eq!(local_txn[0].input.len(), 1);
5276         check_spends!(local_txn[0], chan_1.3);
5277
5278         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5279         nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5280         check_added_monitors!(nodes[1], 1);
5281         mine_transaction(&nodes[1], &local_txn[0]);
5282         check_added_monitors!(nodes[1], 1);
5283         let events = nodes[1].node.get_and_clear_pending_msg_events();
5284         match events[0] {
5285                 MessageSendEvent::UpdateHTLCs { .. } => {},
5286                 _ => panic!("Unexpected event"),
5287         }
5288         match events[1] {
5289                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5290                 _ => panic!("Unexepected event"),
5291         }
5292         let node_tx = {
5293                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5294                 assert_eq!(node_txn.len(), 3);
5295                 assert_eq!(node_txn[0], node_txn[2]);
5296                 assert_eq!(node_txn[1], local_txn[0]);
5297                 assert_eq!(node_txn[0].input.len(), 1);
5298                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5299                 check_spends!(node_txn[0], local_txn[0]);
5300                 node_txn[0].clone()
5301         };
5302
5303         mine_transaction(&nodes[1], &node_tx);
5304         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5305
5306         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5307         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5308         assert_eq!(spend_txn.len(), 1);
5309         check_spends!(spend_txn[0], node_tx);
5310 }
5311
5312 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5313         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5314         // unrevoked commitment transaction.
5315         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5316         // a remote RAA before they could be failed backwards (and combinations thereof).
5317         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5318         // use the same payment hashes.
5319         // Thus, we use a six-node network:
5320         //
5321         // A \         / E
5322         //    - C - D -
5323         // B /         \ F
5324         // And test where C fails back to A/B when D announces its latest commitment transaction
5325         let chanmon_cfgs = create_chanmon_cfgs(6);
5326         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5327         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5328         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5329         let logger = test_utils::TestLogger::new();
5330
5331         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5332         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5333         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5334         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5335         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5336
5337         // Rebalance and check output sanity...
5338         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5339         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5340         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5341
5342         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5343         // 0th HTLC:
5344         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5345         // 1st HTLC:
5346         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5347         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5348         let our_node_id = &nodes[1].node.get_our_node_id();
5349         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5350         // 2nd HTLC:
5351         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], ds_dust_limit*1000, payment_hash_1); // not added < dust limit + HTLC tx fee
5352         // 3rd HTLC:
5353         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], ds_dust_limit*1000, payment_hash_2); // not added < dust limit + HTLC tx fee
5354         // 4th HTLC:
5355         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5356         // 5th HTLC:
5357         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5358         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5359         // 6th HTLC:
5360         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5361         // 7th HTLC:
5362         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5363
5364         // 8th HTLC:
5365         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5366         // 9th HTLC:
5367         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5368         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], ds_dust_limit*1000, payment_hash_5); // not added < dust limit + HTLC tx fee
5369
5370         // 10th HTLC:
5371         let (_, payment_hash_6) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5372         // 11th HTLC:
5373         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5374         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5375
5376         // Double-check that six of the new HTLC were added
5377         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5378         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5379         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5380         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5381
5382         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5383         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5384         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5385         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5386         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5387         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5388         check_added_monitors!(nodes[4], 0);
5389         expect_pending_htlcs_forwardable!(nodes[4]);
5390         check_added_monitors!(nodes[4], 1);
5391
5392         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5393         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5394         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5395         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5396         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5397         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5398
5399         // Fail 3rd below-dust and 7th above-dust HTLCs
5400         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5401         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5402         check_added_monitors!(nodes[5], 0);
5403         expect_pending_htlcs_forwardable!(nodes[5]);
5404         check_added_monitors!(nodes[5], 1);
5405
5406         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5407         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5408         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5409         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5410
5411         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5412
5413         expect_pending_htlcs_forwardable!(nodes[3]);
5414         check_added_monitors!(nodes[3], 1);
5415         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5416         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5417         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5418         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5419         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5420         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5421         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5422         if deliver_last_raa {
5423                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5424         } else {
5425                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5426         }
5427
5428         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5429         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5430         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5431         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5432         //
5433         // We now broadcast the latest commitment transaction, which *should* result in failures for
5434         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5435         // the non-broadcast above-dust HTLCs.
5436         //
5437         // Alternatively, we may broadcast the previous commitment transaction, which should only
5438         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5439         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5440
5441         if announce_latest {
5442                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5443         } else {
5444                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5445         }
5446         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5447         check_closed_broadcast!(nodes[2], true);
5448         expect_pending_htlcs_forwardable!(nodes[2]);
5449         check_added_monitors!(nodes[2], 3);
5450
5451         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5452         assert_eq!(cs_msgs.len(), 2);
5453         let mut a_done = false;
5454         for msg in cs_msgs {
5455                 match msg {
5456                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5457                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5458                                 // should be failed-backwards here.
5459                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5460                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5461                                         for htlc in &updates.update_fail_htlcs {
5462                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 6 || if announce_latest { htlc.htlc_id == 3 || htlc.htlc_id == 5 } else { false });
5463                                         }
5464                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5465                                         assert!(!a_done);
5466                                         a_done = true;
5467                                         &nodes[0]
5468                                 } else {
5469                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5470                                         for htlc in &updates.update_fail_htlcs {
5471                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5472                                         }
5473                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5474                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5475                                         &nodes[1]
5476                                 };
5477                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5478                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5479                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5480                                 if announce_latest {
5481                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5482                                         if *node_id == nodes[0].node.get_our_node_id() {
5483                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5484                                         }
5485                                 }
5486                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5487                         },
5488                         _ => panic!("Unexpected event"),
5489                 }
5490         }
5491
5492         let as_events = nodes[0].node.get_and_clear_pending_events();
5493         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5494         let mut as_failds = HashSet::new();
5495         for event in as_events.iter() {
5496                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5497                         assert!(as_failds.insert(*payment_hash));
5498                         if *payment_hash != payment_hash_2 {
5499                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5500                         } else {
5501                                 assert!(!rejected_by_dest);
5502                         }
5503                 } else { panic!("Unexpected event"); }
5504         }
5505         assert!(as_failds.contains(&payment_hash_1));
5506         assert!(as_failds.contains(&payment_hash_2));
5507         if announce_latest {
5508                 assert!(as_failds.contains(&payment_hash_3));
5509                 assert!(as_failds.contains(&payment_hash_5));
5510         }
5511         assert!(as_failds.contains(&payment_hash_6));
5512
5513         let bs_events = nodes[1].node.get_and_clear_pending_events();
5514         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5515         let mut bs_failds = HashSet::new();
5516         for event in bs_events.iter() {
5517                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5518                         assert!(bs_failds.insert(*payment_hash));
5519                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5520                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5521                         } else {
5522                                 assert!(!rejected_by_dest);
5523                         }
5524                 } else { panic!("Unexpected event"); }
5525         }
5526         assert!(bs_failds.contains(&payment_hash_1));
5527         assert!(bs_failds.contains(&payment_hash_2));
5528         if announce_latest {
5529                 assert!(bs_failds.contains(&payment_hash_4));
5530         }
5531         assert!(bs_failds.contains(&payment_hash_5));
5532
5533         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5534         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5535         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5536         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5537         // PaymentFailureNetworkUpdates.
5538         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5539         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5540         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5541         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5542         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5543                 match event {
5544                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5545                         _ => panic!("Unexpected event"),
5546                 }
5547         }
5548 }
5549
5550 #[test]
5551 fn test_fail_backwards_latest_remote_announce_a() {
5552         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5553 }
5554
5555 #[test]
5556 fn test_fail_backwards_latest_remote_announce_b() {
5557         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5558 }
5559
5560 #[test]
5561 fn test_fail_backwards_previous_remote_announce() {
5562         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5563         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5564         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5565 }
5566
5567 #[test]
5568 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5569         let chanmon_cfgs = create_chanmon_cfgs(2);
5570         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5571         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5572         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5573
5574         // Create some initial channels
5575         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5576
5577         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5578         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5579         assert_eq!(local_txn[0].input.len(), 1);
5580         check_spends!(local_txn[0], chan_1.3);
5581
5582         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5583         mine_transaction(&nodes[0], &local_txn[0]);
5584         check_closed_broadcast!(nodes[0], true);
5585         check_added_monitors!(nodes[0], 1);
5586
5587         let htlc_timeout = {
5588                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5589                 assert_eq!(node_txn[0].input.len(), 1);
5590                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5591                 check_spends!(node_txn[0], local_txn[0]);
5592                 node_txn[0].clone()
5593         };
5594
5595         mine_transaction(&nodes[0], &htlc_timeout);
5596         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5597         expect_payment_failed!(nodes[0], our_payment_hash, true);
5598
5599         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5600         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5601         assert_eq!(spend_txn.len(), 3);
5602         check_spends!(spend_txn[0], local_txn[0]);
5603         check_spends!(spend_txn[1], htlc_timeout);
5604         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5605 }
5606
5607 #[test]
5608 fn test_key_derivation_params() {
5609         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5610         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5611         // let us re-derive the channel key set to then derive a delayed_payment_key.
5612
5613         let chanmon_cfgs = create_chanmon_cfgs(3);
5614
5615         // We manually create the node configuration to backup the seed.
5616         let seed = [42; 32];
5617         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5618         let chain_monitor = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[0].chain_source), &chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator, &chanmon_cfgs[0].persister, &keys_manager);
5619         let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, chain_monitor, keys_manager: &keys_manager, node_seed: seed };
5620         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5621         node_cfgs.remove(0);
5622         node_cfgs.insert(0, node);
5623
5624         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5625         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5626
5627         // Create some initial channels
5628         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5629         // for node 0
5630         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5631         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5632         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5633
5634         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5635         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5636         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5637         assert_eq!(local_txn_1[0].input.len(), 1);
5638         check_spends!(local_txn_1[0], chan_1.3);
5639
5640         // We check funding pubkey are unique
5641         let (from_0_funding_key_0, from_0_funding_key_1) = (PublicKey::from_slice(&local_txn_0[0].input[0].witness[3][2..35]), PublicKey::from_slice(&local_txn_0[0].input[0].witness[3][36..69]));
5642         let (from_1_funding_key_0, from_1_funding_key_1) = (PublicKey::from_slice(&local_txn_1[0].input[0].witness[3][2..35]), PublicKey::from_slice(&local_txn_1[0].input[0].witness[3][36..69]));
5643         if from_0_funding_key_0 == from_1_funding_key_0
5644             || from_0_funding_key_0 == from_1_funding_key_1
5645             || from_0_funding_key_1 == from_1_funding_key_0
5646             || from_0_funding_key_1 == from_1_funding_key_1 {
5647                 panic!("Funding pubkeys aren't unique");
5648         }
5649
5650         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5651         mine_transaction(&nodes[0], &local_txn_1[0]);
5652         check_closed_broadcast!(nodes[0], true);
5653         check_added_monitors!(nodes[0], 1);
5654
5655         let htlc_timeout = {
5656                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5657                 assert_eq!(node_txn[0].input.len(), 1);
5658                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5659                 check_spends!(node_txn[0], local_txn_1[0]);
5660                 node_txn[0].clone()
5661         };
5662
5663         mine_transaction(&nodes[0], &htlc_timeout);
5664         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5665         expect_payment_failed!(nodes[0], our_payment_hash, true);
5666
5667         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5668         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5669         let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5670         assert_eq!(spend_txn.len(), 3);
5671         check_spends!(spend_txn[0], local_txn_1[0]);
5672         check_spends!(spend_txn[1], htlc_timeout);
5673         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5674 }
5675
5676 #[test]
5677 fn test_static_output_closing_tx() {
5678         let chanmon_cfgs = create_chanmon_cfgs(2);
5679         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5680         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5681         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5682
5683         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5684
5685         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5686         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5687
5688         mine_transaction(&nodes[0], &closing_tx);
5689         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5690
5691         let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5692         assert_eq!(spend_txn.len(), 1);
5693         check_spends!(spend_txn[0], closing_tx);
5694
5695         mine_transaction(&nodes[1], &closing_tx);
5696         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5697
5698         let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5699         assert_eq!(spend_txn.len(), 1);
5700         check_spends!(spend_txn[0], closing_tx);
5701 }
5702
5703 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5704         let chanmon_cfgs = create_chanmon_cfgs(2);
5705         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5706         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5707         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5708         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5709
5710         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5711
5712         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5713         // present in B's local commitment transaction, but none of A's commitment transactions.
5714         assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5715         check_added_monitors!(nodes[1], 1);
5716
5717         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5718         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5719         let events = nodes[0].node.get_and_clear_pending_events();
5720         assert_eq!(events.len(), 1);
5721         match events[0] {
5722                 Event::PaymentSent { payment_preimage } => {
5723                         assert_eq!(payment_preimage, our_payment_preimage);
5724                 },
5725                 _ => panic!("Unexpected event"),
5726         }
5727
5728         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5729         check_added_monitors!(nodes[0], 1);
5730         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5731         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5732         check_added_monitors!(nodes[1], 1);
5733
5734         let starting_block = nodes[1].best_block_info();
5735         let mut block = Block {
5736                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5737                 txdata: vec![],
5738         };
5739         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5740                 connect_block(&nodes[1], &block);
5741                 block.header.prev_blockhash = block.block_hash();
5742         }
5743         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5744         check_closed_broadcast!(nodes[1], true);
5745         check_added_monitors!(nodes[1], 1);
5746 }
5747
5748 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5749         let chanmon_cfgs = create_chanmon_cfgs(2);
5750         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5751         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5752         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5753         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5754         let logger = test_utils::TestLogger::new();
5755
5756         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5757         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5758         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV, &logger).unwrap();
5759         nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5760         check_added_monitors!(nodes[0], 1);
5761
5762         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5763
5764         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5765         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5766         // to "time out" the HTLC.
5767
5768         let starting_block = nodes[1].best_block_info();
5769         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5770
5771         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5772                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5773                 header.prev_blockhash = header.block_hash();
5774         }
5775         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5776         check_closed_broadcast!(nodes[0], true);
5777         check_added_monitors!(nodes[0], 1);
5778 }
5779
5780 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5781         let chanmon_cfgs = create_chanmon_cfgs(3);
5782         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5783         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5784         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5785         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5786
5787         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5788         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5789         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5790         // actually revoked.
5791         let htlc_value = if use_dust { 50000 } else { 3000000 };
5792         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5793         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5794         expect_pending_htlcs_forwardable!(nodes[1]);
5795         check_added_monitors!(nodes[1], 1);
5796
5797         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5798         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5799         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5800         check_added_monitors!(nodes[0], 1);
5801         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5802         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5803         check_added_monitors!(nodes[1], 1);
5804         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5805         check_added_monitors!(nodes[1], 1);
5806         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5807
5808         if check_revoke_no_close {
5809                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5810                 check_added_monitors!(nodes[0], 1);
5811         }
5812
5813         let starting_block = nodes[1].best_block_info();
5814         let mut block = Block {
5815                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5816                 txdata: vec![],
5817         };
5818         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5819                 connect_block(&nodes[0], &block);
5820                 block.header.prev_blockhash = block.block_hash();
5821         }
5822         if !check_revoke_no_close {
5823                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5824                 check_closed_broadcast!(nodes[0], true);
5825                 check_added_monitors!(nodes[0], 1);
5826         } else {
5827                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5828         }
5829 }
5830
5831 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5832 // There are only a few cases to test here:
5833 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5834 //    broadcastable commitment transactions result in channel closure,
5835 //  * its included in an unrevoked-but-previous remote commitment transaction,
5836 //  * its included in the latest remote or local commitment transactions.
5837 // We test each of the three possible commitment transactions individually and use both dust and
5838 // non-dust HTLCs.
5839 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5840 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5841 // tested for at least one of the cases in other tests.
5842 #[test]
5843 fn htlc_claim_single_commitment_only_a() {
5844         do_htlc_claim_local_commitment_only(true);
5845         do_htlc_claim_local_commitment_only(false);
5846
5847         do_htlc_claim_current_remote_commitment_only(true);
5848         do_htlc_claim_current_remote_commitment_only(false);
5849 }
5850
5851 #[test]
5852 fn htlc_claim_single_commitment_only_b() {
5853         do_htlc_claim_previous_remote_commitment_only(true, false);
5854         do_htlc_claim_previous_remote_commitment_only(false, false);
5855         do_htlc_claim_previous_remote_commitment_only(true, true);
5856         do_htlc_claim_previous_remote_commitment_only(false, true);
5857 }
5858
5859 #[test]
5860 #[should_panic]
5861 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5862         let chanmon_cfgs = create_chanmon_cfgs(2);
5863         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5864         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5865         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5866         //Force duplicate channel ids
5867         for node in nodes.iter() {
5868                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5869         }
5870
5871         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5872         let channel_value_satoshis=10000;
5873         let push_msat=10001;
5874         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5875         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5876         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5877
5878         //Create a second channel with a channel_id collision
5879         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5880 }
5881
5882 #[test]
5883 fn bolt2_open_channel_sending_node_checks_part2() {
5884         let chanmon_cfgs = create_chanmon_cfgs(2);
5885         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5886         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5887         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5888
5889         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5890         let channel_value_satoshis=2^24;
5891         let push_msat=10001;
5892         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5893
5894         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5895         let channel_value_satoshis=10000;
5896         // Test when push_msat is equal to 1000 * funding_satoshis.
5897         let push_msat=1000*channel_value_satoshis+1;
5898         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5899
5900         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5901         let channel_value_satoshis=10000;
5902         let push_msat=10001;
5903         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_ok()); //Create a valid channel
5904         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5905         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5906
5907         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5908         // Only the least-significant bit of channel_flags is currently defined resulting in channel_flags only having one of two possible states 0 or 1
5909         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5910
5911         // BOLT #2 spec: Sending node should set to_self_delay sufficient to ensure the sender can irreversibly spend a commitment transaction output, in case of misbehaviour by the receiver.
5912         assert!(BREAKDOWN_TIMEOUT>0);
5913         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5914
5915         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5916         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5917         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5918
5919         // BOLT #2 spec: Sending node must set funding_pubkey, revocation_basepoint, htlc_basepoint, payment_basepoint, and delayed_payment_basepoint to valid DER-encoded, compressed, secp256k1 pubkeys.
5920         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5921         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5922         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5923         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5924         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5925 }
5926
5927 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5928 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5929 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5930 // is no longer affordable once it's freed.
5931 #[test]
5932 fn test_fail_holding_cell_htlc_upon_free() {
5933         let chanmon_cfgs = create_chanmon_cfgs(2);
5934         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5935         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5936         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5937         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5938         let logger = test_utils::TestLogger::new();
5939
5940         // First nodes[0] generates an update_fee, setting the channel's
5941         // pending_update_fee.
5942         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
5943         check_added_monitors!(nodes[0], 1);
5944
5945         let events = nodes[0].node.get_and_clear_pending_msg_events();
5946         assert_eq!(events.len(), 1);
5947         let (update_msg, commitment_signed) = match events[0] {
5948                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5949                         (update_fee.as_ref(), commitment_signed)
5950                 },
5951                 _ => panic!("Unexpected event"),
5952         };
5953
5954         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5955
5956         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5957         let channel_reserve = chan_stat.channel_reserve_msat;
5958         let feerate = get_feerate!(nodes[0], chan.2);
5959
5960         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5961         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5962         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5963         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5964         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
5965
5966         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5967         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5968         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5969         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5970
5971         // Flush the pending fee update.
5972         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5973         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5974         check_added_monitors!(nodes[1], 1);
5975         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5976         check_added_monitors!(nodes[0], 1);
5977
5978         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5979         // HTLC, but now that the fee has been raised the payment will now fail, causing
5980         // us to surface its failure to the user.
5981         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5982         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5983         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
5984         let failure_log = format!("Failed to send HTLC with payment_hash {} due to Cannot send value that would put our balance under counterparty-announced channel reserve value ({})", log_bytes!(our_payment_hash.0), chan_stat.channel_reserve_msat);
5985         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5986
5987         // Check that the payment failed to be sent out.
5988         let events = nodes[0].node.get_and_clear_pending_events();
5989         assert_eq!(events.len(), 1);
5990         match &events[0] {
5991                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
5992                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5993                         assert_eq!(*rejected_by_dest, false);
5994                         assert_eq!(*error_code, None);
5995                         assert_eq!(*error_data, None);
5996                 },
5997                 _ => panic!("Unexpected event"),
5998         }
5999 }
6000
6001 // Test that if multiple HTLCs are released from the holding cell and one is
6002 // valid but the other is no longer valid upon release, the valid HTLC can be
6003 // successfully completed while the other one fails as expected.
6004 #[test]
6005 fn test_free_and_fail_holding_cell_htlcs() {
6006         let chanmon_cfgs = create_chanmon_cfgs(2);
6007         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6008         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6009         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6010         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6011         let logger = test_utils::TestLogger::new();
6012
6013         // First nodes[0] generates an update_fee, setting the channel's
6014         // pending_update_fee.
6015         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6016         check_added_monitors!(nodes[0], 1);
6017
6018         let events = nodes[0].node.get_and_clear_pending_msg_events();
6019         assert_eq!(events.len(), 1);
6020         let (update_msg, commitment_signed) = match events[0] {
6021                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6022                         (update_fee.as_ref(), commitment_signed)
6023                 },
6024                 _ => panic!("Unexpected event"),
6025         };
6026
6027         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6028
6029         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6030         let channel_reserve = chan_stat.channel_reserve_msat;
6031         let feerate = get_feerate!(nodes[0], chan.2);
6032
6033         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6034         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6035         let amt_1 = 20000;
6036         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6037         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6038         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6039         let route_1 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], amt_1, TEST_FINAL_CLTV, &logger).unwrap();
6040         let route_2 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], amt_2, TEST_FINAL_CLTV, &logger).unwrap();
6041
6042         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6043         nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6044         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6045         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6046         nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6047         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6048         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6049
6050         // Flush the pending fee update.
6051         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6052         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6053         check_added_monitors!(nodes[1], 1);
6054         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6055         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6056         check_added_monitors!(nodes[0], 2);
6057
6058         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6059         // but now that the fee has been raised the second payment will now fail, causing us
6060         // to surface its failure to the user. The first payment should succeed.
6061         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6062         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6063         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6064         let failure_log = format!("Failed to send HTLC with payment_hash {} due to Cannot send value that would put our balance under counterparty-announced channel reserve value ({})", log_bytes!(payment_hash_2.0), chan_stat.channel_reserve_msat);
6065         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6066
6067         // Check that the second payment failed to be sent out.
6068         let events = nodes[0].node.get_and_clear_pending_events();
6069         assert_eq!(events.len(), 1);
6070         match &events[0] {
6071                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6072                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6073                         assert_eq!(*rejected_by_dest, false);
6074                         assert_eq!(*error_code, None);
6075                         assert_eq!(*error_data, None);
6076                 },
6077                 _ => panic!("Unexpected event"),
6078         }
6079
6080         // Complete the first payment and the RAA from the fee update.
6081         let (payment_event, send_raa_event) = {
6082                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6083                 assert_eq!(msgs.len(), 2);
6084                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6085         };
6086         let raa = match send_raa_event {
6087                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6088                 _ => panic!("Unexpected event"),
6089         };
6090         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6091         check_added_monitors!(nodes[1], 1);
6092         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6093         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6094         let events = nodes[1].node.get_and_clear_pending_events();
6095         assert_eq!(events.len(), 1);
6096         match events[0] {
6097                 Event::PendingHTLCsForwardable { .. } => {},
6098                 _ => panic!("Unexpected event"),
6099         }
6100         nodes[1].node.process_pending_htlc_forwards();
6101         let events = nodes[1].node.get_and_clear_pending_events();
6102         assert_eq!(events.len(), 1);
6103         match events[0] {
6104                 Event::PaymentReceived { .. } => {},
6105                 _ => panic!("Unexpected event"),
6106         }
6107         nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6108         check_added_monitors!(nodes[1], 1);
6109         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6110         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6111         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6112         let events = nodes[0].node.get_and_clear_pending_events();
6113         assert_eq!(events.len(), 1);
6114         match events[0] {
6115                 Event::PaymentSent { ref payment_preimage } => {
6116                         assert_eq!(*payment_preimage, payment_preimage_1);
6117                 }
6118                 _ => panic!("Unexpected event"),
6119         }
6120 }
6121
6122 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6123 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6124 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6125 // once it's freed.
6126 #[test]
6127 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6128         let chanmon_cfgs = create_chanmon_cfgs(3);
6129         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6130         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6131         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6132         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6133         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6134         let logger = test_utils::TestLogger::new();
6135
6136         // First nodes[1] generates an update_fee, setting the channel's
6137         // pending_update_fee.
6138         nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6139         check_added_monitors!(nodes[1], 1);
6140
6141         let events = nodes[1].node.get_and_clear_pending_msg_events();
6142         assert_eq!(events.len(), 1);
6143         let (update_msg, commitment_signed) = match events[0] {
6144                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6145                         (update_fee.as_ref(), commitment_signed)
6146                 },
6147                 _ => panic!("Unexpected event"),
6148         };
6149
6150         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6151
6152         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6153         let channel_reserve = chan_stat.channel_reserve_msat;
6154         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6155
6156         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6157         let feemsat = 239;
6158         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6159         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6160         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6161         let payment_event = {
6162                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6163                 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(), None, None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6164                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6165                 check_added_monitors!(nodes[0], 1);
6166
6167                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6168                 assert_eq!(events.len(), 1);
6169
6170                 SendEvent::from_event(events.remove(0))
6171         };
6172         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6173         check_added_monitors!(nodes[1], 0);
6174         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6175         expect_pending_htlcs_forwardable!(nodes[1]);
6176
6177         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6178         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6179
6180         // Flush the pending fee update.
6181         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6182         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6183         check_added_monitors!(nodes[2], 1);
6184         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6185         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6186         check_added_monitors!(nodes[1], 2);
6187
6188         // A final RAA message is generated to finalize the fee update.
6189         let events = nodes[1].node.get_and_clear_pending_msg_events();
6190         assert_eq!(events.len(), 1);
6191
6192         let raa_msg = match &events[0] {
6193                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6194                         msg.clone()
6195                 },
6196                 _ => panic!("Unexpected event"),
6197         };
6198
6199         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6200         check_added_monitors!(nodes[2], 1);
6201         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6202
6203         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6204         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6205         assert_eq!(process_htlc_forwards_event.len(), 1);
6206         match &process_htlc_forwards_event[0] {
6207                 &Event::PendingHTLCsForwardable { .. } => {},
6208                 _ => panic!("Unexpected event"),
6209         }
6210
6211         // In response, we call ChannelManager's process_pending_htlc_forwards
6212         nodes[1].node.process_pending_htlc_forwards();
6213         check_added_monitors!(nodes[1], 1);
6214
6215         // This causes the HTLC to be failed backwards.
6216         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6217         assert_eq!(fail_event.len(), 1);
6218         let (fail_msg, commitment_signed) = match &fail_event[0] {
6219                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6220                         assert_eq!(updates.update_add_htlcs.len(), 0);
6221                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6222                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6223                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6224                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6225                 },
6226                 _ => panic!("Unexpected event"),
6227         };
6228
6229         // Pass the failure messages back to nodes[0].
6230         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6231         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6232
6233         // Complete the HTLC failure+removal process.
6234         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6235         check_added_monitors!(nodes[0], 1);
6236         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6237         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6238         check_added_monitors!(nodes[1], 2);
6239         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6240         assert_eq!(final_raa_event.len(), 1);
6241         let raa = match &final_raa_event[0] {
6242                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6243                 _ => panic!("Unexpected event"),
6244         };
6245         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6246         let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6247         assert_eq!(fail_msg_event.len(), 1);
6248         match &fail_msg_event[0] {
6249                 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6250                 _ => panic!("Unexpected event"),
6251         }
6252         let failure_event = nodes[0].node.get_and_clear_pending_events();
6253         assert_eq!(failure_event.len(), 1);
6254         match &failure_event[0] {
6255                 &Event::PaymentFailed { rejected_by_dest, .. } => {
6256                         assert!(!rejected_by_dest);
6257                 },
6258                 _ => panic!("Unexpected event"),
6259         }
6260         check_added_monitors!(nodes[0], 1);
6261 }
6262
6263 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6264 // BOLT 2 Requirement: MUST NOT offer amount_msat it cannot pay for in the remote commitment transaction at the current feerate_per_kw (see "Updating Fees") while maintaining its channel reserve.
6265 //TODO: I don't believe this is explicitly enforced when sending an HTLC but as the Fee aspect of the BOLT specs is in flux leaving this as a TODO.
6266
6267 #[test]
6268 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6269         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6270         let chanmon_cfgs = create_chanmon_cfgs(2);
6271         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6272         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6273         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6274         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6275
6276         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6277         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6278         let logger = test_utils::TestLogger::new();
6279         let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6280         route.paths[0][0].fee_msat = 100;
6281
6282         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6283                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6284         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6285         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6286 }
6287
6288 #[test]
6289 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6290         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6291         let chanmon_cfgs = create_chanmon_cfgs(2);
6292         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6293         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6294         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6295         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6296         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6297
6298         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6299         let logger = test_utils::TestLogger::new();
6300         let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6301         route.paths[0][0].fee_msat = 0;
6302         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6303                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6304
6305         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6306         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6307 }
6308
6309 #[test]
6310 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6311         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6312         let chanmon_cfgs = create_chanmon_cfgs(2);
6313         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6314         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6315         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6316         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6317
6318         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6319         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6320         let logger = test_utils::TestLogger::new();
6321         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6322         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6323         check_added_monitors!(nodes[0], 1);
6324         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6325         updates.update_add_htlcs[0].amount_msat = 0;
6326
6327         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6328         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6329         check_closed_broadcast!(nodes[1], true).unwrap();
6330         check_added_monitors!(nodes[1], 1);
6331 }
6332
6333 #[test]
6334 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6335         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6336         //It is enforced when constructing a route.
6337         let chanmon_cfgs = create_chanmon_cfgs(2);
6338         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6339         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6340         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6341         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6342         let logger = test_utils::TestLogger::new();
6343
6344         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6345
6346         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6347         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 100000000, 500000001, &logger).unwrap();
6348         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6349                 assert_eq!(err, &"Channel CLTV overflowed?"));
6350 }
6351
6352 #[test]
6353 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6354         //BOLT 2 Requirement: if result would be offering more than the remote's max_accepted_htlcs HTLCs, in the remote commitment transaction: MUST NOT add an HTLC.
6355         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6356         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6357         let chanmon_cfgs = create_chanmon_cfgs(2);
6358         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6359         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6360         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6361         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6362         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6363
6364         let logger = test_utils::TestLogger::new();
6365         for i in 0..max_accepted_htlcs {
6366                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6367                 let payment_event = {
6368                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6369                         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6370                         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6371                         check_added_monitors!(nodes[0], 1);
6372
6373                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6374                         assert_eq!(events.len(), 1);
6375                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6376                                 assert_eq!(htlcs[0].htlc_id, i);
6377                         } else {
6378                                 assert!(false);
6379                         }
6380                         SendEvent::from_event(events.remove(0))
6381                 };
6382                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6383                 check_added_monitors!(nodes[1], 0);
6384                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6385
6386                 expect_pending_htlcs_forwardable!(nodes[1]);
6387                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6388         }
6389         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6390         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6391         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6392         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6393                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6394
6395         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6396         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6397 }
6398
6399 #[test]
6400 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6401         //BOLT 2 Requirement: if the sum of total offered HTLCs would exceed the remote's max_htlc_value_in_flight_msat: MUST NOT add an HTLC.
6402         let chanmon_cfgs = create_chanmon_cfgs(2);
6403         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6404         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6405         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6406         let channel_value = 100000;
6407         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6408         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6409
6410         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6411
6412         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6413         // Manually create a route over our max in flight (which our router normally automatically
6414         // limits us to.
6415         let route = Route { paths: vec![vec![RouteHop {
6416            pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6417            short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6418            fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6419         }]] };
6420         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6421                 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
6422
6423         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6424         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
6425
6426         send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6427 }
6428
6429 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6430 #[test]
6431 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6432         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6433         let chanmon_cfgs = create_chanmon_cfgs(2);
6434         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6435         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6436         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6437         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6438         let htlc_minimum_msat: u64;
6439         {
6440                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6441                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6442                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6443         }
6444
6445         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6446         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6447         let logger = test_utils::TestLogger::new();
6448         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], htlc_minimum_msat, TEST_FINAL_CLTV, &logger).unwrap();
6449         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6450         check_added_monitors!(nodes[0], 1);
6451         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6452         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6453         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6454         assert!(nodes[1].node.list_channels().is_empty());
6455         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6456         assert!(regex::Regex::new(r"Remote side tried to send less than our minimum HTLC value\. Lower limit: \(\d+\)\. Actual: \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6457         check_added_monitors!(nodes[1], 1);
6458 }
6459
6460 #[test]
6461 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6462         //BOLT2 Requirement: receiving an amount_msat that the sending node cannot afford at the current feerate_per_kw (while maintaining its channel reserve): SHOULD fail the channel
6463         let chanmon_cfgs = create_chanmon_cfgs(2);
6464         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6465         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6466         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6467         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6468         let logger = test_utils::TestLogger::new();
6469
6470         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6471         let channel_reserve = chan_stat.channel_reserve_msat;
6472         let feerate = get_feerate!(nodes[0], chan.2);
6473         // The 2* and +1 are for the fee spike reserve.
6474         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6475
6476         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6477         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6478         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6479         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6480         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6481         check_added_monitors!(nodes[0], 1);
6482         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6483
6484         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6485         // at this time channel-initiatee receivers are not required to enforce that senders
6486         // respect the fee_spike_reserve.
6487         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6488         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6489
6490         assert!(nodes[1].node.list_channels().is_empty());
6491         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6492         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6493         check_added_monitors!(nodes[1], 1);
6494 }
6495
6496 #[test]
6497 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6498         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6499         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6500         let chanmon_cfgs = create_chanmon_cfgs(2);
6501         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6502         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6503         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6504         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6505         let logger = test_utils::TestLogger::new();
6506
6507         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6508         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6509
6510         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6511         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 3999999, TEST_FINAL_CLTV, &logger).unwrap();
6512
6513         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6514         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6515         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6516         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6517
6518         let mut msg = msgs::UpdateAddHTLC {
6519                 channel_id: chan.2,
6520                 htlc_id: 0,
6521                 amount_msat: 1000,
6522                 payment_hash: our_payment_hash,
6523                 cltv_expiry: htlc_cltv,
6524                 onion_routing_packet: onion_packet.clone(),
6525         };
6526
6527         for i in 0..super::channel::OUR_MAX_HTLCS {
6528                 msg.htlc_id = i as u64;
6529                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6530         }
6531         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6532         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6533
6534         assert!(nodes[1].node.list_channels().is_empty());
6535         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6536         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6537         check_added_monitors!(nodes[1], 1);
6538 }
6539
6540 #[test]
6541 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6542         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6543         let chanmon_cfgs = create_chanmon_cfgs(2);
6544         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6545         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6546         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6547         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6548         let logger = test_utils::TestLogger::new();
6549
6550         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6551         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6552         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6553         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6554         check_added_monitors!(nodes[0], 1);
6555         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6556         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6557         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6558
6559         assert!(nodes[1].node.list_channels().is_empty());
6560         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6561         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6562         check_added_monitors!(nodes[1], 1);
6563 }
6564
6565 #[test]
6566 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6567         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6568         let chanmon_cfgs = create_chanmon_cfgs(2);
6569         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6570         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6571         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6572         let logger = test_utils::TestLogger::new();
6573
6574         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6575         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6576         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6577         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6578         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6579         check_added_monitors!(nodes[0], 1);
6580         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6581         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6582         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6583
6584         assert!(nodes[1].node.list_channels().is_empty());
6585         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6586         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6587         check_added_monitors!(nodes[1], 1);
6588 }
6589
6590 #[test]
6591 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6592         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6593         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6594         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6595         let chanmon_cfgs = create_chanmon_cfgs(2);
6596         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6597         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6598         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6599         let logger = test_utils::TestLogger::new();
6600
6601         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6602         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6603         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6604         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6605         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6606         check_added_monitors!(nodes[0], 1);
6607         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6608         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6609
6610         //Disconnect and Reconnect
6611         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6612         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6613         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6614         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6615         assert_eq!(reestablish_1.len(), 1);
6616         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6617         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6618         assert_eq!(reestablish_2.len(), 1);
6619         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6620         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6621         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6622         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6623
6624         //Resend HTLC
6625         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6626         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6627         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6628         check_added_monitors!(nodes[1], 1);
6629         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6630
6631         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6632
6633         assert!(nodes[1].node.list_channels().is_empty());
6634         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6635         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6636         check_added_monitors!(nodes[1], 1);
6637 }
6638
6639 #[test]
6640 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6641         //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions:     MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6642
6643         let chanmon_cfgs = create_chanmon_cfgs(2);
6644         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6645         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6646         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6647         let logger = test_utils::TestLogger::new();
6648         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6649         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6650         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6651         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6652         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6653
6654         check_added_monitors!(nodes[0], 1);
6655         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6656         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6657
6658         let update_msg = msgs::UpdateFulfillHTLC{
6659                 channel_id: chan.2,
6660                 htlc_id: 0,
6661                 payment_preimage: our_payment_preimage,
6662         };
6663
6664         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6665
6666         assert!(nodes[0].node.list_channels().is_empty());
6667         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6668         assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6669         check_added_monitors!(nodes[0], 1);
6670 }
6671
6672 #[test]
6673 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6674         //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions:     MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6675
6676         let chanmon_cfgs = create_chanmon_cfgs(2);
6677         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6678         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6679         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6680         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6681         let logger = test_utils::TestLogger::new();
6682
6683         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6684         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6685         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6686         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6687         check_added_monitors!(nodes[0], 1);
6688         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6689         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6690
6691         let update_msg = msgs::UpdateFailHTLC{
6692                 channel_id: chan.2,
6693                 htlc_id: 0,
6694                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6695         };
6696
6697         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6698
6699         assert!(nodes[0].node.list_channels().is_empty());
6700         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6701         assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6702         check_added_monitors!(nodes[0], 1);
6703 }
6704
6705 #[test]
6706 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6707         //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions:     MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6708
6709         let chanmon_cfgs = create_chanmon_cfgs(2);
6710         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6711         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6712         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6713         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6714         let logger = test_utils::TestLogger::new();
6715
6716         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6717         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6718         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6719         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6720         check_added_monitors!(nodes[0], 1);
6721         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6722         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6723         let update_msg = msgs::UpdateFailMalformedHTLC{
6724                 channel_id: chan.2,
6725                 htlc_id: 0,
6726                 sha256_of_onion: [1; 32],
6727                 failure_code: 0x8000,
6728         };
6729
6730         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6731
6732         assert!(nodes[0].node.list_channels().is_empty());
6733         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6734         assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6735         check_added_monitors!(nodes[0], 1);
6736 }
6737
6738 #[test]
6739 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6740         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6741
6742         let chanmon_cfgs = create_chanmon_cfgs(2);
6743         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6744         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6745         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6746         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6747
6748         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6749
6750         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6751         check_added_monitors!(nodes[1], 1);
6752
6753         let events = nodes[1].node.get_and_clear_pending_msg_events();
6754         assert_eq!(events.len(), 1);
6755         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6756                 match events[0] {
6757                         MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, .. } } => {
6758                                 assert!(update_add_htlcs.is_empty());
6759                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6760                                 assert!(update_fail_htlcs.is_empty());
6761                                 assert!(update_fail_malformed_htlcs.is_empty());
6762                                 assert!(update_fee.is_none());
6763                                 update_fulfill_htlcs[0].clone()
6764                         },
6765                         _ => panic!("Unexpected event"),
6766                 }
6767         };
6768
6769         update_fulfill_msg.htlc_id = 1;
6770
6771         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6772
6773         assert!(nodes[0].node.list_channels().is_empty());
6774         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6775         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6776         check_added_monitors!(nodes[0], 1);
6777 }
6778
6779 #[test]
6780 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6781         //BOLT 2 Requirement: A receiving node: if the payment_preimage value in update_fulfill_htlc doesn't SHA256 hash to the corresponding HTLC payment_hash MUST fail the channel.
6782
6783         let chanmon_cfgs = create_chanmon_cfgs(2);
6784         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6785         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6786         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6787         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6788
6789         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6790
6791         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6792         check_added_monitors!(nodes[1], 1);
6793
6794         let events = nodes[1].node.get_and_clear_pending_msg_events();
6795         assert_eq!(events.len(), 1);
6796         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6797                 match events[0] {
6798                         MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, .. } } => {
6799                                 assert!(update_add_htlcs.is_empty());
6800                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6801                                 assert!(update_fail_htlcs.is_empty());
6802                                 assert!(update_fail_malformed_htlcs.is_empty());
6803                                 assert!(update_fee.is_none());
6804                                 update_fulfill_htlcs[0].clone()
6805                         },
6806                         _ => panic!("Unexpected event"),
6807                 }
6808         };
6809
6810         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6811
6812         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6813
6814         assert!(nodes[0].node.list_channels().is_empty());
6815         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6816         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6817         check_added_monitors!(nodes[0], 1);
6818 }
6819
6820 #[test]
6821 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6822         //BOLT 2 Requirement: A receiving node: if the BADONION bit in failure_code is not set for update_fail_malformed_htlc MUST fail the channel.
6823
6824         let chanmon_cfgs = create_chanmon_cfgs(2);
6825         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6826         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6827         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6828         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6829         let logger = test_utils::TestLogger::new();
6830
6831         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6832         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6833         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6834         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6835         check_added_monitors!(nodes[0], 1);
6836
6837         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6838         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6839
6840         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6841         check_added_monitors!(nodes[1], 0);
6842         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6843
6844         let events = nodes[1].node.get_and_clear_pending_msg_events();
6845
6846         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6847                 match events[0] {
6848                         MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, .. } } => {
6849                                 assert!(update_add_htlcs.is_empty());
6850                                 assert!(update_fulfill_htlcs.is_empty());
6851                                 assert!(update_fail_htlcs.is_empty());
6852                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6853                                 assert!(update_fee.is_none());
6854                                 update_fail_malformed_htlcs[0].clone()
6855                         },
6856                         _ => panic!("Unexpected event"),
6857                 }
6858         };
6859         update_msg.failure_code &= !0x8000;
6860         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6861
6862         assert!(nodes[0].node.list_channels().is_empty());
6863         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6864         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6865         check_added_monitors!(nodes[0], 1);
6866 }
6867
6868 #[test]
6869 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6870         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6871         //    * MUST return an error in the update_fail_htlc sent to the link which originally sent the HTLC, using the failure_code given and setting the data to sha256_of_onion.
6872
6873         let chanmon_cfgs = create_chanmon_cfgs(3);
6874         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6875         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6876         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6877         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6878         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6879         let logger = test_utils::TestLogger::new();
6880
6881         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6882
6883         //First hop
6884         let mut payment_event = {
6885                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6886                 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(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
6887                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6888                 check_added_monitors!(nodes[0], 1);
6889                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6890                 assert_eq!(events.len(), 1);
6891                 SendEvent::from_event(events.remove(0))
6892         };
6893         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6894         check_added_monitors!(nodes[1], 0);
6895         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6896         expect_pending_htlcs_forwardable!(nodes[1]);
6897         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6898         assert_eq!(events_2.len(), 1);
6899         check_added_monitors!(nodes[1], 1);
6900         payment_event = SendEvent::from_event(events_2.remove(0));
6901         assert_eq!(payment_event.msgs.len(), 1);
6902
6903         //Second Hop
6904         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6905         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6906         check_added_monitors!(nodes[2], 0);
6907         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6908
6909         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6910         assert_eq!(events_3.len(), 1);
6911         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6912                 match events_3[0] {
6913                         MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
6914                                 assert!(update_add_htlcs.is_empty());
6915                                 assert!(update_fulfill_htlcs.is_empty());
6916                                 assert!(update_fail_htlcs.is_empty());
6917                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6918                                 assert!(update_fee.is_none());
6919                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6920                         },
6921                         _ => panic!("Unexpected event"),
6922                 }
6923         };
6924
6925         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6926
6927         check_added_monitors!(nodes[1], 0);
6928         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6929         expect_pending_htlcs_forwardable!(nodes[1]);
6930         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6931         assert_eq!(events_4.len(), 1);
6932
6933         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6934         match events_4[0] {
6935                 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, .. } } => {
6936                         assert!(update_add_htlcs.is_empty());
6937                         assert!(update_fulfill_htlcs.is_empty());
6938                         assert_eq!(update_fail_htlcs.len(), 1);
6939                         assert!(update_fail_malformed_htlcs.is_empty());
6940                         assert!(update_fee.is_none());
6941                 },
6942                 _ => panic!("Unexpected event"),
6943         };
6944
6945         check_added_monitors!(nodes[1], 1);
6946 }
6947
6948 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6949         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6950         // We can have at most two valid local commitment tx, so both cases must be covered, and both txs must be checked to get them all as
6951         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6952
6953         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6954         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6955         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6956         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6957         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6958         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6959
6960         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6961
6962         // We route 2 dust-HTLCs between A and B
6963         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6964         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6965         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6966
6967         // Cache one local commitment tx as previous
6968         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6969
6970         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6971         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
6972         check_added_monitors!(nodes[1], 0);
6973         expect_pending_htlcs_forwardable!(nodes[1]);
6974         check_added_monitors!(nodes[1], 1);
6975
6976         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6977         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6978         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6979         check_added_monitors!(nodes[0], 1);
6980
6981         // Cache one local commitment tx as lastest
6982         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6983
6984         let events = nodes[0].node.get_and_clear_pending_msg_events();
6985         match events[0] {
6986                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6987                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6988                 },
6989                 _ => panic!("Unexpected event"),
6990         }
6991         match events[1] {
6992                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6993                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6994                 },
6995                 _ => panic!("Unexpected event"),
6996         }
6997
6998         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6999         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7000         if announce_latest {
7001                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7002         } else {
7003                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7004         }
7005
7006         check_closed_broadcast!(nodes[0], true);
7007         check_added_monitors!(nodes[0], 1);
7008
7009         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7010         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7011         let events = nodes[0].node.get_and_clear_pending_events();
7012         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7013         assert_eq!(events.len(), 2);
7014         let mut first_failed = false;
7015         for event in events {
7016                 match event {
7017                         Event::PaymentFailed { payment_hash, .. } => {
7018                                 if payment_hash == payment_hash_1 {
7019                                         assert!(!first_failed);
7020                                         first_failed = true;
7021                                 } else {
7022                                         assert_eq!(payment_hash, payment_hash_2);
7023                                 }
7024                         }
7025                         _ => panic!("Unexpected event"),
7026                 }
7027         }
7028 }
7029
7030 #[test]
7031 fn test_failure_delay_dust_htlc_local_commitment() {
7032         do_test_failure_delay_dust_htlc_local_commitment(true);
7033         do_test_failure_delay_dust_htlc_local_commitment(false);
7034 }
7035
7036 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7037         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7038         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7039         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7040         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7041         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7042         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7043
7044         let chanmon_cfgs = create_chanmon_cfgs(3);
7045         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7046         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7047         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7048         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7049
7050         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7051
7052         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7053         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7054
7055         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7056         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7057
7058         // We revoked bs_commitment_tx
7059         if revoked {
7060                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7061                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7062         }
7063
7064         let mut timeout_tx = Vec::new();
7065         if local {
7066                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7067                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7068                 check_closed_broadcast!(nodes[0], true);
7069                 check_added_monitors!(nodes[0], 1);
7070                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7071                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7072                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7073                 expect_payment_failed!(nodes[0], dust_hash, true);
7074                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7075                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7076                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7077                 mine_transaction(&nodes[0], &timeout_tx[0]);
7078                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7079                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7080         } else {
7081                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7082                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7083                 check_closed_broadcast!(nodes[0], true);
7084                 check_added_monitors!(nodes[0], 1);
7085                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7086                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7087                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7088                 if !revoked {
7089                         expect_payment_failed!(nodes[0], dust_hash, true);
7090                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7091                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7092                         mine_transaction(&nodes[0], &timeout_tx[0]);
7093                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7094                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7095                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7096                 } else {
7097                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7098                         // commitment tx
7099                         let events = nodes[0].node.get_and_clear_pending_events();
7100                         assert_eq!(events.len(), 2);
7101                         let first;
7102                         match events[0] {
7103                                 Event::PaymentFailed { payment_hash, .. } => {
7104                                         if payment_hash == dust_hash { first = true; }
7105                                         else { first = false; }
7106                                 },
7107                                 _ => panic!("Unexpected event"),
7108                         }
7109                         match events[1] {
7110                                 Event::PaymentFailed { payment_hash, .. } => {
7111                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7112                                         else { assert_eq!(payment_hash, dust_hash); }
7113                                 },
7114                                 _ => panic!("Unexpected event"),
7115                         }
7116                 }
7117         }
7118 }
7119
7120 #[test]
7121 fn test_sweep_outbound_htlc_failure_update() {
7122         do_test_sweep_outbound_htlc_failure_update(false, true);
7123         do_test_sweep_outbound_htlc_failure_update(false, false);
7124         do_test_sweep_outbound_htlc_failure_update(true, false);
7125 }
7126
7127 #[test]
7128 fn test_upfront_shutdown_script() {
7129         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7130         // enforce it at shutdown message
7131
7132         let mut config = UserConfig::default();
7133         config.channel_options.announced_channel = true;
7134         config.peer_channel_config_limits.force_announced_channel_preference = false;
7135         config.channel_options.commit_upfront_shutdown_pubkey = false;
7136         let user_cfgs = [None, Some(config), None];
7137         let chanmon_cfgs = create_chanmon_cfgs(3);
7138         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7139         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7140         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7141
7142         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7143         let flags = InitFeatures::known();
7144         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7145         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7146         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7147         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7148         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
7149         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7150     assert!(regex::Regex::new(r"Got shutdown request with a scriptpubkey \([A-Fa-f0-9]+\) which did not match their previous scriptpubkey.").unwrap().is_match(check_closed_broadcast!(nodes[2], true).unwrap().data.as_str()));
7151         check_added_monitors!(nodes[2], 1);
7152
7153         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7154         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7155         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7156         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7157         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7158         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7159         let events = nodes[2].node.get_and_clear_pending_msg_events();
7160         assert_eq!(events.len(), 1);
7161         match events[0] {
7162                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7163                 _ => panic!("Unexpected event"),
7164         }
7165
7166         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7167         let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7168         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7169         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7170         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7171         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7172         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
7173         let events = nodes[1].node.get_and_clear_pending_msg_events();
7174         assert_eq!(events.len(), 1);
7175         match events[0] {
7176                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7177                 _ => panic!("Unexpected event"),
7178         }
7179
7180         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7181         // channel smoothly, opt-out is from channel initiator here
7182         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7183         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7184         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7185         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7186         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7187         let events = nodes[0].node.get_and_clear_pending_msg_events();
7188         assert_eq!(events.len(), 1);
7189         match events[0] {
7190                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7191                 _ => panic!("Unexpected event"),
7192         }
7193
7194         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7195         //// channel smoothly
7196         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7197         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7198         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7199         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7200         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7201         let events = nodes[0].node.get_and_clear_pending_msg_events();
7202         assert_eq!(events.len(), 2);
7203         match events[0] {
7204                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7205                 _ => panic!("Unexpected event"),
7206         }
7207         match events[1] {
7208                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7209                 _ => panic!("Unexpected event"),
7210         }
7211 }
7212
7213 #[test]
7214 fn test_upfront_shutdown_script_unsupport_segwit() {
7215         // We test that channel is closed early
7216         // if a segwit program is passed as upfront shutdown script,
7217         // but the peer does not support segwit.
7218         let chanmon_cfgs = create_chanmon_cfgs(2);
7219         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7220         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7221         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7222
7223         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
7224
7225         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7226         open_channel.shutdown_scriptpubkey = Present(Builder::new().push_int(16)
7227                 .push_slice(&[0, 0])
7228                 .into_script());
7229
7230         let features = InitFeatures::known().clear_shutdown_anysegwit();
7231         nodes[0].node.handle_open_channel(&nodes[0].node.get_our_node_id(), features, &open_channel);
7232
7233         let events = nodes[0].node.get_and_clear_pending_msg_events();
7234         assert_eq!(events.len(), 1);
7235         match events[0] {
7236                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7237                         assert_eq!(node_id, nodes[0].node.get_our_node_id());
7238                         assert!(regex::Regex::new(r"Peer is signaling upfront_shutdown but has provided a non-accepted scriptpubkey format. script: (\([A-Fa-f0-9]+\))").unwrap().is_match(&*msg.data));
7239                 },
7240                 _ => panic!("Unexpected event"),
7241         }
7242 }
7243
7244 #[test]
7245 fn test_shutdown_script_any_segwit_allowed() {
7246         let mut config = UserConfig::default();
7247         config.channel_options.announced_channel = true;
7248         config.peer_channel_config_limits.force_announced_channel_preference = false;
7249         config.channel_options.commit_upfront_shutdown_pubkey = false;
7250         let user_cfgs = [None, Some(config), None];
7251         let chanmon_cfgs = create_chanmon_cfgs(3);
7252         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7253         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7254         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7255
7256         //// We test if the remote peer accepts opt_shutdown_anysegwit, a witness program can be used on shutdown
7257         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7258         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7259         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7260         node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7261                 .push_slice(&[0, 0])
7262                 .into_script();
7263         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7264         let events = nodes[0].node.get_and_clear_pending_msg_events();
7265         assert_eq!(events.len(), 2);
7266         match events[0] {
7267                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7268                 _ => panic!("Unexpected event"),
7269         }
7270         match events[1] {
7271                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7272                 _ => panic!("Unexpected event"),
7273         }
7274 }
7275
7276 #[test]
7277 fn test_shutdown_script_any_segwit_not_allowed() {
7278         let mut config = UserConfig::default();
7279         config.channel_options.announced_channel = true;
7280         config.peer_channel_config_limits.force_announced_channel_preference = false;
7281         config.channel_options.commit_upfront_shutdown_pubkey = false;
7282         let user_cfgs = [None, Some(config), None];
7283         let chanmon_cfgs = create_chanmon_cfgs(3);
7284         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7285         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7286         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7287
7288         //// We test that if the remote peer does not accept opt_shutdown_anysegwit, the witness program cannot be used on shutdown
7289         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7290         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7291         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7292         // Make an any segwit version script
7293         node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7294                 .push_slice(&[0, 0])
7295                 .into_script();
7296         let flags_no = InitFeatures::known().clear_shutdown_anysegwit();
7297         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &flags_no, &node_0_shutdown);
7298         let events = nodes[0].node.get_and_clear_pending_msg_events();
7299         assert_eq!(events.len(), 2);
7300         match events[1] {
7301                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7302                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7303                         assert_eq!(msg.data, "Got a nonstandard scriptpubkey (60020000) from remote peer".to_owned())
7304                 },
7305                 _ => panic!("Unexpected event"),
7306         }
7307         check_added_monitors!(nodes[0], 1);
7308 }
7309
7310 #[test]
7311 fn test_shutdown_script_segwit_but_not_anysegwit() {
7312         let mut config = UserConfig::default();
7313         config.channel_options.announced_channel = true;
7314         config.peer_channel_config_limits.force_announced_channel_preference = false;
7315         config.channel_options.commit_upfront_shutdown_pubkey = false;
7316         let user_cfgs = [None, Some(config), None];
7317         let chanmon_cfgs = create_chanmon_cfgs(3);
7318         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7319         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7320         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7321
7322         //// We test that if shutdown any segwit is supported and we send a witness script with 0 version, this is not accepted
7323         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7324         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7325         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7326         // Make a segwit script that is not a valid as any segwit
7327         node_0_shutdown.scriptpubkey = Builder::new().push_int(0)
7328                 .push_slice(&[0, 0])
7329                 .into_script();
7330         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7331         let events = nodes[0].node.get_and_clear_pending_msg_events();
7332         assert_eq!(events.len(), 2);
7333         match events[1] {
7334                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7335                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7336                         assert_eq!(msg.data, "Got a nonstandard scriptpubkey (00020000) from remote peer".to_owned())
7337                 },
7338                 _ => panic!("Unexpected event"),
7339         }
7340         check_added_monitors!(nodes[0], 1);
7341 }
7342
7343 #[test]
7344 fn test_user_configurable_csv_delay() {
7345         // We test our channel constructors yield errors when we pass them absurd csv delay
7346
7347         let mut low_our_to_self_config = UserConfig::default();
7348         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7349         let mut high_their_to_self_config = UserConfig::default();
7350         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7351         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7352         let chanmon_cfgs = create_chanmon_cfgs(2);
7353         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7354         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7355         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7356
7357         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7358         if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), 1000000, 1000000, 0, &low_our_to_self_config) {
7359                 match error {
7360                         APIError::APIMisuseError { err } => { assert!(regex::Regex::new(r"Configured with an unreasonable our_to_self_delay \(\d+\) putting user funds at risks").unwrap().is_match(err.as_str())); },
7361                         _ => panic!("Unexpected event"),
7362                 }
7363         } else { assert!(false) }
7364
7365         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7366         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7367         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7368         open_channel.to_self_delay = 200;
7369         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &low_our_to_self_config) {
7370                 match error {
7371                         ChannelError::Close(err) => { assert!(regex::Regex::new(r"Configured with an unreasonable our_to_self_delay \(\d+\) putting user funds at risks").unwrap().is_match(err.as_str()));  },
7372                         _ => panic!("Unexpected event"),
7373                 }
7374         } else { assert!(false); }
7375
7376         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7377         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7378         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
7379         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7380         accept_channel.to_self_delay = 200;
7381         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7382         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7383                 match action {
7384                         &ErrorAction::SendErrorMessage { ref msg } => {
7385                                 assert!(regex::Regex::new(r"They wanted our payments to be delayed by a needlessly long period\. Upper limit: \d+\. Actual: \d+").unwrap().is_match(msg.data.as_str()));
7386                         },
7387                         _ => { assert!(false); }
7388                 }
7389         } else { assert!(false); }
7390
7391         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7392         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7393         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7394         open_channel.to_self_delay = 200;
7395         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &high_their_to_self_config) {
7396                 match error {
7397                         ChannelError::Close(err) => { assert!(regex::Regex::new(r"They wanted our payments to be delayed by a needlessly long period\. Upper limit: \d+\. Actual: \d+").unwrap().is_match(err.as_str())); },
7398                         _ => panic!("Unexpected event"),
7399                 }
7400         } else { assert!(false); }
7401 }
7402
7403 #[test]
7404 fn test_data_loss_protect() {
7405         // We want to be sure that :
7406         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7407         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7408         // * we close channel in case of detecting other being fallen behind
7409         // * we are able to claim our own outputs thanks to to_remote being static
7410         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7411         let persister;
7412         let logger;
7413         let fee_estimator;
7414         let tx_broadcaster;
7415         let chain_source;
7416         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7417         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7418         // during signing due to revoked tx
7419         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7420         let keys_manager = &chanmon_cfgs[0].keys_manager;
7421         let monitor;
7422         let node_state_0;
7423         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7424         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7425         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7426
7427         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7428
7429         // Cache node A state before any channel update
7430         let previous_node_state = nodes[0].node.encode();
7431         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7432         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7433
7434         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7435         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7436
7437         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7438         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7439
7440         // Restore node A from previous state
7441         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7442         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7443         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7444         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7445         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7446         persister = test_utils::TestPersister::new();
7447         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7448         node_state_0 = {
7449                 let mut channel_monitors = HashMap::new();
7450                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7451                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
7452                         keys_manager: keys_manager,
7453                         fee_estimator: &fee_estimator,
7454                         chain_monitor: &monitor,
7455                         logger: &logger,
7456                         tx_broadcaster: &tx_broadcaster,
7457                         default_config: UserConfig::default(),
7458                         channel_monitors,
7459                 }).unwrap().1
7460         };
7461         nodes[0].node = &node_state_0;
7462         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7463         nodes[0].chain_monitor = &monitor;
7464         nodes[0].chain_source = &chain_source;
7465
7466         check_added_monitors!(nodes[0], 1);
7467
7468         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7469         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7470
7471         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7472
7473         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7474         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7475         check_added_monitors!(nodes[0], 1);
7476
7477         {
7478                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7479                 assert_eq!(node_txn.len(), 0);
7480         }
7481
7482         let mut reestablish_1 = Vec::with_capacity(1);
7483         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7484                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7485                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7486                         reestablish_1.push(msg.clone());
7487                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7488                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7489                         match action {
7490                                 &ErrorAction::SendErrorMessage { ref msg } => {
7491                                         assert_eq!(msg.data, "We have fallen behind - we have received proof that if we broadcast remote is going to claim our funds - we can't do any automated broadcasting");
7492                                 },
7493                                 _ => panic!("Unexpected event!"),
7494                         }
7495                 } else {
7496                         panic!("Unexpected event")
7497                 }
7498         }
7499
7500         // Check we close channel detecting A is fallen-behind
7501         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7502         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7503         check_added_monitors!(nodes[1], 1);
7504
7505
7506         // Check A is able to claim to_remote output
7507         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7508         assert_eq!(node_txn.len(), 1);
7509         check_spends!(node_txn[0], chan.3);
7510         assert_eq!(node_txn[0].output.len(), 2);
7511         mine_transaction(&nodes[0], &node_txn[0]);
7512         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7513         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 1000000);
7514         assert_eq!(spend_txn.len(), 1);
7515         check_spends!(spend_txn[0], node_txn[0]);
7516 }
7517
7518 #[test]
7519 fn test_check_htlc_underpaying() {
7520         // Send payment through A -> B but A is maliciously
7521         // sending a probe payment (i.e less than expected value0
7522         // to B, B should refuse payment.
7523
7524         let chanmon_cfgs = create_chanmon_cfgs(2);
7525         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7526         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7527         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7528
7529         // Create some initial channels
7530         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7531
7532         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7533
7534         // Node 3 is expecting payment of 100_000 but receive 10_000,
7535         // fail htlc like we didn't know the preimage.
7536         nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7537         nodes[1].node.process_pending_htlc_forwards();
7538
7539         let events = nodes[1].node.get_and_clear_pending_msg_events();
7540         assert_eq!(events.len(), 1);
7541         let (update_fail_htlc, commitment_signed) = match events[0] {
7542                 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
7543                         assert!(update_add_htlcs.is_empty());
7544                         assert!(update_fulfill_htlcs.is_empty());
7545                         assert_eq!(update_fail_htlcs.len(), 1);
7546                         assert!(update_fail_malformed_htlcs.is_empty());
7547                         assert!(update_fee.is_none());
7548                         (update_fail_htlcs[0].clone(), commitment_signed)
7549                 },
7550                 _ => panic!("Unexpected event"),
7551         };
7552         check_added_monitors!(nodes[1], 1);
7553
7554         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7555         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7556
7557         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7558         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7559         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7560         expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7561         nodes[1].node.get_and_clear_pending_events();
7562 }
7563
7564 #[test]
7565 fn test_announce_disable_channels() {
7566         // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7567         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7568
7569         let chanmon_cfgs = create_chanmon_cfgs(2);
7570         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7571         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7572         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7573
7574         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7575         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7576         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7577
7578         // Disconnect peers
7579         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7580         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7581
7582         nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7583         nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7584         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7585         assert_eq!(msg_events.len(), 3);
7586         for e in msg_events {
7587                 match e {
7588                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7589                                 let short_id = msg.contents.short_channel_id;
7590                                 // Check generated channel_update match list in PendingChannelUpdate
7591                                 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7592                                         panic!("Generated ChannelUpdate for wrong chan!");
7593                                 }
7594                         },
7595                         _ => panic!("Unexpected event"),
7596                 }
7597         }
7598         // Reconnect peers
7599         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7600         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7601         assert_eq!(reestablish_1.len(), 3);
7602         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7603         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7604         assert_eq!(reestablish_2.len(), 3);
7605
7606         // Reestablish chan_1
7607         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7608         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7609         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7610         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7611         // Reestablish chan_2
7612         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7613         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7614         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7615         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7616         // Reestablish chan_3
7617         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7618         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7619         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7620         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7621
7622         nodes[0].node.timer_chan_freshness_every_min();
7623         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7624 }
7625
7626 #[test]
7627 fn test_bump_penalty_txn_on_revoked_commitment() {
7628         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7629         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7630
7631         let chanmon_cfgs = create_chanmon_cfgs(2);
7632         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7633         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7634         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7635
7636         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7637         let logger = test_utils::TestLogger::new();
7638
7639         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7640         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7641         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 3000000, 30, &logger).unwrap();
7642         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7643
7644         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7645         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7646         assert_eq!(revoked_txn[0].output.len(), 4);
7647         assert_eq!(revoked_txn[0].input.len(), 1);
7648         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7649         let revoked_txid = revoked_txn[0].txid();
7650
7651         let mut penalty_sum = 0;
7652         for outp in revoked_txn[0].output.iter() {
7653                 if outp.script_pubkey.is_v0_p2wsh() {
7654                         penalty_sum += outp.value;
7655                 }
7656         }
7657
7658         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7659         let header_114 = connect_blocks(&nodes[1], 14);
7660
7661         // Actually revoke tx by claiming a HTLC
7662         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7663         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7664         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7665         check_added_monitors!(nodes[1], 1);
7666
7667         // One or more justice tx should have been broadcast, check it
7668         let penalty_1;
7669         let feerate_1;
7670         {
7671                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7672                 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7673                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7674                 assert_eq!(node_txn[0].output.len(), 1);
7675                 check_spends!(node_txn[0], revoked_txn[0]);
7676                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7677                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7678                 penalty_1 = node_txn[0].txid();
7679                 node_txn.clear();
7680         };
7681
7682         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7683         connect_blocks(&nodes[1], 15);
7684         let mut penalty_2 = penalty_1;
7685         let mut feerate_2 = 0;
7686         {
7687                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7688                 assert_eq!(node_txn.len(), 1);
7689                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7690                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7691                         assert_eq!(node_txn[0].output.len(), 1);
7692                         check_spends!(node_txn[0], revoked_txn[0]);
7693                         penalty_2 = node_txn[0].txid();
7694                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7695                         assert_ne!(penalty_2, penalty_1);
7696                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7697                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7698                         // Verify 25% bump heuristic
7699                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7700                         node_txn.clear();
7701                 }
7702         }
7703         assert_ne!(feerate_2, 0);
7704
7705         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7706         connect_blocks(&nodes[1], 1);
7707         let penalty_3;
7708         let mut feerate_3 = 0;
7709         {
7710                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7711                 assert_eq!(node_txn.len(), 1);
7712                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7713                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7714                         assert_eq!(node_txn[0].output.len(), 1);
7715                         check_spends!(node_txn[0], revoked_txn[0]);
7716                         penalty_3 = node_txn[0].txid();
7717                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7718                         assert_ne!(penalty_3, penalty_2);
7719                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7720                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7721                         // Verify 25% bump heuristic
7722                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7723                         node_txn.clear();
7724                 }
7725         }
7726         assert_ne!(feerate_3, 0);
7727
7728         nodes[1].node.get_and_clear_pending_events();
7729         nodes[1].node.get_and_clear_pending_msg_events();
7730 }
7731
7732 #[test]
7733 fn test_bump_penalty_txn_on_revoked_htlcs() {
7734         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7735         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7736
7737         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7738         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7739         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7740         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7741         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7742
7743         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7744         // Lock HTLC in both directions
7745         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7746         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7747
7748         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7749         assert_eq!(revoked_local_txn[0].input.len(), 1);
7750         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7751
7752         // Revoke local commitment tx
7753         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7754
7755         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7756         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7757         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7758         check_closed_broadcast!(nodes[1], true);
7759         check_added_monitors!(nodes[1], 1);
7760
7761         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7762         assert_eq!(revoked_htlc_txn.len(), 4);
7763         if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7764                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7765                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7766                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7767                 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7768                 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7769                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7770         } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7771                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7772                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7773                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7774                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7775                 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7776                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7777         }
7778
7779         // Broadcast set of revoked txn on A
7780         let hash_128 = connect_blocks(&nodes[0], 40);
7781         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7782         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7783         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7784         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7785         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7786         let first;
7787         let feerate_1;
7788         let penalty_txn;
7789         {
7790                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7791                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7792                 // Verify claim tx are spending revoked HTLC txn
7793
7794                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7795                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7796                 // which are included in the same block (they are broadcasted because we scan the
7797                 // transactions linearly and generate claims as we go, they likely should be removed in the
7798                 // future).
7799                 assert_eq!(node_txn[0].input.len(), 1);
7800                 check_spends!(node_txn[0], revoked_local_txn[0]);
7801                 assert_eq!(node_txn[1].input.len(), 1);
7802                 check_spends!(node_txn[1], revoked_local_txn[0]);
7803                 assert_eq!(node_txn[2].input.len(), 1);
7804                 check_spends!(node_txn[2], revoked_local_txn[0]);
7805
7806                 // Each of the three justice transactions claim a separate (single) output of the three
7807                 // available, which we check here:
7808                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7809                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7810                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7811
7812                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7813                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7814
7815                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7816                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7817                 // a remote commitment tx has already been confirmed).
7818                 check_spends!(node_txn[3], chan.3);
7819
7820                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7821                 // output, checked above).
7822                 assert_eq!(node_txn[4].input.len(), 2);
7823                 assert_eq!(node_txn[4].output.len(), 1);
7824                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7825
7826                 first = node_txn[4].txid();
7827                 // Store both feerates for later comparison
7828                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7829                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7830                 penalty_txn = vec![node_txn[2].clone()];
7831                 node_txn.clear();
7832         }
7833
7834         // Connect one more block to see if bumped penalty are issued for HTLC txn
7835         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7836         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7837         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7838         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7839         {
7840                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7841                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7842
7843                 check_spends!(node_txn[0], revoked_local_txn[0]);
7844                 check_spends!(node_txn[1], revoked_local_txn[0]);
7845                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7846                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7847                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7848                 } else {
7849                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7850                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7851                 }
7852
7853                 node_txn.clear();
7854         };
7855
7856         // Few more blocks to confirm penalty txn
7857         connect_blocks(&nodes[0], 4);
7858         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7859         let header_144 = connect_blocks(&nodes[0], 9);
7860         let node_txn = {
7861                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7862                 assert_eq!(node_txn.len(), 1);
7863
7864                 assert_eq!(node_txn[0].input.len(), 2);
7865                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7866                 // Verify bumped tx is different and 25% bump heuristic
7867                 assert_ne!(first, node_txn[0].txid());
7868                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7869                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7870                 assert!(feerate_2 * 100 > feerate_1 * 125);
7871                 let txn = vec![node_txn[0].clone()];
7872                 node_txn.clear();
7873                 txn
7874         };
7875         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7876         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7877         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7878         connect_blocks(&nodes[0], 20);
7879         {
7880                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7881                 // We verify than no new transaction has been broadcast because previously
7882                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7883                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7884                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7885                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7886                 // up bumped justice generation.
7887                 assert_eq!(node_txn.len(), 0);
7888                 node_txn.clear();
7889         }
7890         check_closed_broadcast!(nodes[0], true);
7891         check_added_monitors!(nodes[0], 1);
7892 }
7893
7894 #[test]
7895 fn test_bump_penalty_txn_on_remote_commitment() {
7896         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7897         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7898
7899         // Create 2 HTLCs
7900         // Provide preimage for one
7901         // Check aggregation
7902
7903         let chanmon_cfgs = create_chanmon_cfgs(2);
7904         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7905         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7906         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7907
7908         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7909         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7910         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7911
7912         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7913         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7914         assert_eq!(remote_txn[0].output.len(), 4);
7915         assert_eq!(remote_txn[0].input.len(), 1);
7916         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7917
7918         // Claim a HTLC without revocation (provide B monitor with preimage)
7919         nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7920         mine_transaction(&nodes[1], &remote_txn[0]);
7921         check_added_monitors!(nodes[1], 2);
7922
7923         // One or more claim tx should have been broadcast, check it
7924         let timeout;
7925         let preimage;
7926         let feerate_timeout;
7927         let feerate_preimage;
7928         {
7929                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7930                 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7931                 assert_eq!(node_txn[0].input.len(), 1);
7932                 assert_eq!(node_txn[1].input.len(), 1);
7933                 check_spends!(node_txn[0], remote_txn[0]);
7934                 check_spends!(node_txn[1], remote_txn[0]);
7935                 check_spends!(node_txn[2], chan.3);
7936                 check_spends!(node_txn[3], node_txn[2]);
7937                 check_spends!(node_txn[4], node_txn[2]);
7938                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7939                         timeout = node_txn[0].txid();
7940                         let index = node_txn[0].input[0].previous_output.vout;
7941                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7942                         feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7943
7944                         preimage = node_txn[1].txid();
7945                         let index = node_txn[1].input[0].previous_output.vout;
7946                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7947                         feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7948                 } else {
7949                         timeout = node_txn[1].txid();
7950                         let index = node_txn[1].input[0].previous_output.vout;
7951                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7952                         feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7953
7954                         preimage = node_txn[0].txid();
7955                         let index = node_txn[0].input[0].previous_output.vout;
7956                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7957                         feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7958                 }
7959                 node_txn.clear();
7960         };
7961         assert_ne!(feerate_timeout, 0);
7962         assert_ne!(feerate_preimage, 0);
7963
7964         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7965         connect_blocks(&nodes[1], 15);
7966         {
7967                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7968                 assert_eq!(node_txn.len(), 2);
7969                 assert_eq!(node_txn[0].input.len(), 1);
7970                 assert_eq!(node_txn[1].input.len(), 1);
7971                 check_spends!(node_txn[0], remote_txn[0]);
7972                 check_spends!(node_txn[1], remote_txn[0]);
7973                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7974                         let index = node_txn[0].input[0].previous_output.vout;
7975                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7976                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7977                         assert!(new_feerate * 100 > feerate_timeout * 125);
7978                         assert_ne!(timeout, node_txn[0].txid());
7979
7980                         let index = node_txn[1].input[0].previous_output.vout;
7981                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7982                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7983                         assert!(new_feerate * 100 > feerate_preimage * 125);
7984                         assert_ne!(preimage, node_txn[1].txid());
7985                 } else {
7986                         let index = node_txn[1].input[0].previous_output.vout;
7987                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7988                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7989                         assert!(new_feerate * 100 > feerate_timeout * 125);
7990                         assert_ne!(timeout, node_txn[1].txid());
7991
7992                         let index = node_txn[0].input[0].previous_output.vout;
7993                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7994                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7995                         assert!(new_feerate * 100 > feerate_preimage * 125);
7996                         assert_ne!(preimage, node_txn[0].txid());
7997                 }
7998                 node_txn.clear();
7999         }
8000
8001         nodes[1].node.get_and_clear_pending_events();
8002         nodes[1].node.get_and_clear_pending_msg_events();
8003 }
8004
8005 #[test]
8006 fn test_counterparty_raa_skip_no_crash() {
8007         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8008         // commitment transaction, we would have happily carried on and provided them the next
8009         // commitment transaction based on one RAA forward. This would probably eventually have led to
8010         // channel closure, but it would not have resulted in funds loss. Still, our
8011         // EnforcingSigner would have paniced as it doesn't like jumps into the future. Here, we
8012         // check simply that the channel is closed in response to such an RAA, but don't check whether
8013         // we decide to punish our counterparty for revoking their funds (as we don't currently
8014         // implement that).
8015         let chanmon_cfgs = create_chanmon_cfgs(2);
8016         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8017         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8018         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8019         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8020
8021         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8022         let keys = &guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8023         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8024         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8025         // Must revoke without gaps
8026         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8027         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8028                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8029
8030         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8031                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8032         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8033         check_added_monitors!(nodes[1], 1);
8034 }
8035
8036 #[test]
8037 fn test_bump_txn_sanitize_tracking_maps() {
8038         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8039         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8040
8041         let chanmon_cfgs = create_chanmon_cfgs(2);
8042         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8043         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8044         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8045
8046         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8047         // Lock HTLC in both directions
8048         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8049         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8050
8051         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8052         assert_eq!(revoked_local_txn[0].input.len(), 1);
8053         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8054
8055         // Revoke local commitment tx
8056         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8057
8058         // Broadcast set of revoked txn on A
8059         connect_blocks(&nodes[0], 52 - CHAN_CONFIRM_DEPTH);
8060         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8061         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8062
8063         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8064         check_closed_broadcast!(nodes[0], true);
8065         check_added_monitors!(nodes[0], 1);
8066         let penalty_txn = {
8067                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8068                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8069                 check_spends!(node_txn[0], revoked_local_txn[0]);
8070                 check_spends!(node_txn[1], revoked_local_txn[0]);
8071                 check_spends!(node_txn[2], revoked_local_txn[0]);
8072                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8073                 node_txn.clear();
8074                 penalty_txn
8075         };
8076         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8077         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8078         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8079         {
8080                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8081                 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8082                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8083                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8084                 }
8085         }
8086 }
8087
8088 #[test]
8089 fn test_override_channel_config() {
8090         let chanmon_cfgs = create_chanmon_cfgs(2);
8091         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8092         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8093         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8094
8095         // Node0 initiates a channel to node1 using the override config.
8096         let mut override_config = UserConfig::default();
8097         override_config.own_channel_config.our_to_self_delay = 200;
8098
8099         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8100
8101         // Assert the channel created by node0 is using the override config.
8102         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8103         assert_eq!(res.channel_flags, 0);
8104         assert_eq!(res.to_self_delay, 200);
8105 }
8106
8107 #[test]
8108 fn test_override_0msat_htlc_minimum() {
8109         let mut zero_config = UserConfig::default();
8110         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8111         let chanmon_cfgs = create_chanmon_cfgs(2);
8112         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8113         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8114         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8115
8116         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8117         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8118         assert_eq!(res.htlc_minimum_msat, 1);
8119
8120         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8121         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8122         assert_eq!(res.htlc_minimum_msat, 1);
8123 }
8124
8125 #[test]
8126 fn test_simple_payment_secret() {
8127         // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8128         // features, however.
8129         let chanmon_cfgs = create_chanmon_cfgs(3);
8130         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8131         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8132         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8133
8134         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8135         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8136         let logger = test_utils::TestLogger::new();
8137
8138         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8139         let payment_secret = PaymentSecret([0xdb; 32]);
8140         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8141         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(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8142         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8143         // Claiming with all the correct values but the wrong secret should result in nothing...
8144         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8145         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8146         // ...but with the right secret we should be able to claim all the way back
8147         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8148 }
8149
8150 #[test]
8151 fn test_simple_mpp() {
8152         // Simple test of sending a multi-path payment.
8153         let chanmon_cfgs = create_chanmon_cfgs(4);
8154         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8155         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8156         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8157
8158         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8159         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8160         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8161         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8162         let logger = test_utils::TestLogger::new();
8163
8164         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8165         let payment_secret = PaymentSecret([0xdb; 32]);
8166         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8167         let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8168         let path = route.paths[0].clone();
8169         route.paths.push(path);
8170         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8171         route.paths[0][0].short_channel_id = chan_1_id;
8172         route.paths[0][1].short_channel_id = chan_3_id;
8173         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8174         route.paths[1][0].short_channel_id = chan_2_id;
8175         route.paths[1][1].short_channel_id = chan_4_id;
8176         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8177         // Claiming with all the correct values but the wrong secret should result in nothing...
8178         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8179         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8180         // ...but with the right secret we should be able to claim all the way back
8181         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8182 }
8183
8184 #[test]
8185 fn test_update_err_monitor_lockdown() {
8186         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8187         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8188         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8189         //
8190         // This scenario may happen in a watchtower setup, where watchtower process a block height
8191         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8192         // commitment at same time.
8193
8194         let chanmon_cfgs = create_chanmon_cfgs(2);
8195         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8196         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8197         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8198
8199         // Create some initial channel
8200         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8201         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8202
8203         // Rebalance the network to generate htlc in the two directions
8204         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8205
8206         // Route a HTLC from node 0 to node 1 (but don't settle)
8207         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8208
8209         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8210         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8211         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8212         let persister = test_utils::TestPersister::new();
8213         let watchtower = {
8214                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8215                 let monitor = monitors.get(&outpoint).unwrap();
8216                 let mut w = test_utils::TestVecWriter(Vec::new());
8217                 monitor.write(&mut w).unwrap();
8218                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8219                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8220                 assert!(new_monitor == *monitor);
8221                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8222                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8223                 watchtower
8224         };
8225         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8226         watchtower.chain_monitor.block_connected(&header, &[], 200);
8227
8228         // Try to update ChannelMonitor
8229         assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8230         check_added_monitors!(nodes[1], 1);
8231         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8232         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8233         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8234         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8235                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8236                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8237                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8238                 } else { assert!(false); }
8239         } else { assert!(false); };
8240         // Our local monitor is in-sync and hasn't processed yet timeout
8241         check_added_monitors!(nodes[0], 1);
8242         let events = nodes[0].node.get_and_clear_pending_events();
8243         assert_eq!(events.len(), 1);
8244 }
8245
8246 #[test]
8247 fn test_concurrent_monitor_claim() {
8248         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8249         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8250         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8251         // state N+1 confirms. Alice claims output from state N+1.
8252
8253         let chanmon_cfgs = create_chanmon_cfgs(2);
8254         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8255         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8256         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8257
8258         // Create some initial channel
8259         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8260         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8261
8262         // Rebalance the network to generate htlc in the two directions
8263         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8264
8265         // Route a HTLC from node 0 to node 1 (but don't settle)
8266         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8267
8268         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8269         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8270         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8271         let persister = test_utils::TestPersister::new();
8272         let watchtower_alice = {
8273                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8274                 let monitor = monitors.get(&outpoint).unwrap();
8275                 let mut w = test_utils::TestVecWriter(Vec::new());
8276                 monitor.write(&mut w).unwrap();
8277                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8278                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8279                 assert!(new_monitor == *monitor);
8280                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8281                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8282                 watchtower
8283         };
8284         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8285         watchtower_alice.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8286
8287         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8288         {
8289                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8290                 assert_eq!(txn.len(), 2);
8291                 txn.clear();
8292         }
8293
8294         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8295         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8296         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8297         let persister = test_utils::TestPersister::new();
8298         let watchtower_bob = {
8299                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8300                 let monitor = monitors.get(&outpoint).unwrap();
8301                 let mut w = test_utils::TestVecWriter(Vec::new());
8302                 monitor.write(&mut w).unwrap();
8303                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8304                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8305                 assert!(new_monitor == *monitor);
8306                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8307                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8308                 watchtower
8309         };
8310         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8311         watchtower_bob.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8312
8313         // Route another payment to generate another update with still previous HTLC pending
8314         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8315         {
8316                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8317                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 3000000 , TEST_FINAL_CLTV, &logger).unwrap();
8318                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8319         }
8320         check_added_monitors!(nodes[1], 1);
8321
8322         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8323         assert_eq!(updates.update_add_htlcs.len(), 1);
8324         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8325         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8326                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8327                         // Watchtower Alice should already have seen the block and reject the update
8328                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8329                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8330                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8331                 } else { assert!(false); }
8332         } else { assert!(false); };
8333         // Our local monitor is in-sync and hasn't processed yet timeout
8334         check_added_monitors!(nodes[0], 1);
8335
8336         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8337         watchtower_bob.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8338
8339         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8340         let bob_state_y;
8341         {
8342                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8343                 assert_eq!(txn.len(), 2);
8344                 bob_state_y = txn[0].clone();
8345                 txn.clear();
8346         };
8347
8348         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8349         watchtower_alice.chain_monitor.block_connected(&header, &vec![(0, &bob_state_y)], CHAN_CONFIRM_DEPTH + 2 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8350         {
8351                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8352                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8353                 // the onchain detection of the HTLC output
8354                 assert_eq!(htlc_txn.len(), 2);
8355                 check_spends!(htlc_txn[0], bob_state_y);
8356                 check_spends!(htlc_txn[1], bob_state_y);
8357         }
8358 }
8359
8360 #[test]
8361 fn test_pre_lockin_no_chan_closed_update() {
8362         // Test that if a peer closes a channel in response to a funding_created message we don't
8363         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8364         // message).
8365         //
8366         // Doing so would imply a channel monitor update before the initial channel monitor
8367         // registration, violating our API guarantees.
8368         //
8369         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8370         // then opening a second channel with the same funding output as the first (which is not
8371         // rejected because the first channel does not exist in the ChannelManager) and closing it
8372         // before receiving funding_signed.
8373         let chanmon_cfgs = create_chanmon_cfgs(2);
8374         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8375         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8376         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8377
8378         // Create an initial channel
8379         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8380         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8381         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8382         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8383         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8384
8385         // Move the first channel through the funding flow...
8386         let (temporary_channel_id, _tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8387
8388         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8389         check_added_monitors!(nodes[0], 0);
8390
8391         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8392         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8393         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8394         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8395 }
8396
8397 #[test]
8398 fn test_htlc_no_detection() {
8399         // This test is a mutation to underscore the detection logic bug we had
8400         // before #653. HTLC value routed is above the remaining balance, thus
8401         // inverting HTLC and `to_remote` output. HTLC will come second and
8402         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8403         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8404         // outputs order detection for correct spending children filtring.
8405
8406         let chanmon_cfgs = create_chanmon_cfgs(2);
8407         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8408         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8409         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8410
8411         // Create some initial channels
8412         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8413
8414         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000, 1_000_000);
8415         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8416         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8417         assert_eq!(local_txn[0].input.len(), 1);
8418         assert_eq!(local_txn[0].output.len(), 3);
8419         check_spends!(local_txn[0], chan_1.3);
8420
8421         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8422         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8423         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8424         // We deliberately connect the local tx twice as this should provoke a failure calling
8425         // this test before #653 fix.
8426         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &Block { header, txdata: vec![local_txn[0].clone()] }, nodes[0].best_block_info().1 + 1);
8427         check_closed_broadcast!(nodes[0], true);
8428         check_added_monitors!(nodes[0], 1);
8429
8430         let htlc_timeout = {
8431                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8432                 assert_eq!(node_txn[0].input.len(), 1);
8433                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8434                 check_spends!(node_txn[0], local_txn[0]);
8435                 node_txn[0].clone()
8436         };
8437
8438         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8439         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8440         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8441         expect_payment_failed!(nodes[0], our_payment_hash, true);
8442 }
8443
8444 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8445         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8446         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8447         // Carol, Alice would be the upstream node, and Carol the downstream.)
8448         //
8449         // Steps of the test:
8450         // 1) Alice sends a HTLC to Carol through Bob.
8451         // 2) Carol doesn't settle the HTLC.
8452         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8453         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8454         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8455         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8456         // 5) Carol release the preimage to Bob off-chain.
8457         // 6) Bob claims the offered output on the broadcasted commitment.
8458         let chanmon_cfgs = create_chanmon_cfgs(3);
8459         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8460         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8461         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8462
8463         // Create some initial channels
8464         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8465         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8466
8467         // Steps (1) and (2):
8468         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8469         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8470
8471         // Check that Alice's commitment transaction now contains an output for this HTLC.
8472         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8473         check_spends!(alice_txn[0], chan_ab.3);
8474         assert_eq!(alice_txn[0].output.len(), 2);
8475         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8476         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8477         assert_eq!(alice_txn.len(), 2);
8478
8479         // Steps (3) and (4):
8480         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8481         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8482         let mut force_closing_node = 0; // Alice force-closes
8483         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8484         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8485         check_closed_broadcast!(nodes[force_closing_node], true);
8486         check_added_monitors!(nodes[force_closing_node], 1);
8487         if go_onchain_before_fulfill {
8488                 let txn_to_broadcast = match broadcast_alice {
8489                         true => alice_txn.clone(),
8490                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8491                 };
8492                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8493                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8494                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8495                 if broadcast_alice {
8496                         check_closed_broadcast!(nodes[1], true);
8497                         check_added_monitors!(nodes[1], 1);
8498                 }
8499                 assert_eq!(bob_txn.len(), 1);
8500                 check_spends!(bob_txn[0], chan_ab.3);
8501         }
8502
8503         // Step (5):
8504         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8505         // process of removing the HTLC from their commitment transactions.
8506         assert!(nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000));
8507         check_added_monitors!(nodes[2], 1);
8508         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8509         assert!(carol_updates.update_add_htlcs.is_empty());
8510         assert!(carol_updates.update_fail_htlcs.is_empty());
8511         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8512         assert!(carol_updates.update_fee.is_none());
8513         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8514
8515         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8516         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8517         if !go_onchain_before_fulfill && broadcast_alice {
8518                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8519                 assert_eq!(events.len(), 1);
8520                 match events[0] {
8521                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8522                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8523                         },
8524                         _ => panic!("Unexpected event"),
8525                 };
8526         }
8527         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8528         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8529         // Carol<->Bob's updated commitment transaction info.
8530         check_added_monitors!(nodes[1], 2);
8531
8532         let events = nodes[1].node.get_and_clear_pending_msg_events();
8533         assert_eq!(events.len(), 2);
8534         let bob_revocation = match events[0] {
8535                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8536                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8537                         (*msg).clone()
8538                 },
8539                 _ => panic!("Unexpected event"),
8540         };
8541         let bob_updates = match events[1] {
8542                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8543                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8544                         (*updates).clone()
8545                 },
8546                 _ => panic!("Unexpected event"),
8547         };
8548
8549         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8550         check_added_monitors!(nodes[2], 1);
8551         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8552         check_added_monitors!(nodes[2], 1);
8553
8554         let events = nodes[2].node.get_and_clear_pending_msg_events();
8555         assert_eq!(events.len(), 1);
8556         let carol_revocation = match events[0] {
8557                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8558                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8559                         (*msg).clone()
8560                 },
8561                 _ => panic!("Unexpected event"),
8562         };
8563         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8564         check_added_monitors!(nodes[1], 1);
8565
8566         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8567         // here's where we put said channel's commitment tx on-chain.
8568         let mut txn_to_broadcast = alice_txn.clone();
8569         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8570         if !go_onchain_before_fulfill {
8571                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8572                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8573                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8574                 if broadcast_alice {
8575                         check_closed_broadcast!(nodes[1], true);
8576                         check_added_monitors!(nodes[1], 1);
8577                 }
8578                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8579                 if broadcast_alice {
8580                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8581                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8582                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8583                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8584                         // broadcasted.
8585                         assert_eq!(bob_txn.len(), 3);
8586                         check_spends!(bob_txn[1], chan_ab.3);
8587                 } else {
8588                         assert_eq!(bob_txn.len(), 2);
8589                         check_spends!(bob_txn[0], chan_ab.3);
8590                 }
8591         }
8592
8593         // Step (6):
8594         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8595         // broadcasted commitment transaction.
8596         {
8597                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8598                 if go_onchain_before_fulfill {
8599                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8600                         assert_eq!(bob_txn.len(), 2);
8601                 }
8602                 let script_weight = match broadcast_alice {
8603                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8604                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8605                 };
8606                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8607                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8608                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8609                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8610                 if broadcast_alice && !go_onchain_before_fulfill {
8611                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8612                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8613                 } else {
8614                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8615                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8616                 }
8617         }
8618 }
8619
8620 #[test]
8621 fn test_onchain_htlc_settlement_after_close() {
8622         do_test_onchain_htlc_settlement_after_close(true, true);
8623         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8624         do_test_onchain_htlc_settlement_after_close(true, false);
8625         do_test_onchain_htlc_settlement_after_close(false, false);
8626 }
8627
8628 #[test]
8629 fn test_duplicate_chan_id() {
8630         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8631         // already open we reject it and keep the old channel.
8632         //
8633         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8634         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8635         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8636         // updating logic for the existing channel.
8637         let chanmon_cfgs = create_chanmon_cfgs(2);
8638         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8639         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8640         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8641
8642         // Create an initial channel
8643         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8644         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8645         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8646         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8647
8648         // Try to create a second channel with the same temporary_channel_id as the first and check
8649         // that it is rejected.
8650         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8651         {
8652                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8653                 assert_eq!(events.len(), 1);
8654                 match events[0] {
8655                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8656                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8657                                 // first (valid) and second (invalid) channels are closed, given they both have
8658                                 // the same non-temporary channel_id. However, currently we do not, so we just
8659                                 // move forward with it.
8660                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8661                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8662                         },
8663                         _ => panic!("Unexpected event"),
8664                 }
8665         }
8666
8667         // Move the first channel through the funding flow...
8668         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8669
8670         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8671         check_added_monitors!(nodes[0], 0);
8672
8673         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8674         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8675         {
8676                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8677                 assert_eq!(added_monitors.len(), 1);
8678                 assert_eq!(added_monitors[0].0, funding_output);
8679                 added_monitors.clear();
8680         }
8681         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8682
8683         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8684         let channel_id = funding_outpoint.to_channel_id();
8685
8686         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8687         // temporary one).
8688
8689         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8690         // Technically this is allowed by the spec, but we don't support it and there's little reason
8691         // to. Still, it shouldn't cause any other issues.
8692         open_chan_msg.temporary_channel_id = channel_id;
8693         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8694         {
8695                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8696                 assert_eq!(events.len(), 1);
8697                 match events[0] {
8698                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8699                                 // Technically, at this point, nodes[1] would be justified in thinking both
8700                                 // channels are closed, but currently we do not, so we just move forward with it.
8701                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8702                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8703                         },
8704                         _ => panic!("Unexpected event"),
8705                 }
8706         }
8707
8708         // Now try to create a second channel which has a duplicate funding output.
8709         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8710         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8711         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8712         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8713         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8714
8715         let funding_created = {
8716                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8717                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8718                 let logger = test_utils::TestLogger::new();
8719                 as_chan.get_outbound_funding_created(funding_outpoint, &&logger).unwrap()
8720         };
8721         check_added_monitors!(nodes[0], 0);
8722         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8723         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8724         // still needs to be cleared here.
8725         check_added_monitors!(nodes[1], 1);
8726
8727         // ...still, nodes[1] will reject the duplicate channel.
8728         {
8729                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8730                 assert_eq!(events.len(), 1);
8731                 match events[0] {
8732                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8733                                 // Technically, at this point, nodes[1] would be justified in thinking both
8734                                 // channels are closed, but currently we do not, so we just move forward with it.
8735                                 assert_eq!(msg.channel_id, channel_id);
8736                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8737                         },
8738                         _ => panic!("Unexpected event"),
8739                 }
8740         }
8741
8742         // finally, finish creating the original channel and send a payment over it to make sure
8743         // everything is functional.
8744         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8745         {
8746                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8747                 assert_eq!(added_monitors.len(), 1);
8748                 assert_eq!(added_monitors[0].0, funding_output);
8749                 added_monitors.clear();
8750         }
8751
8752         let events_4 = nodes[0].node.get_and_clear_pending_events();
8753         assert_eq!(events_4.len(), 1);
8754         match events_4[0] {
8755                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
8756                         assert_eq!(user_channel_id, 42);
8757                         assert_eq!(*funding_txo, funding_output);
8758                 },
8759                 _ => panic!("Unexpected event"),
8760         };
8761
8762         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8763         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8764         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8765         send_payment(&nodes[0], &[&nodes[1]], 8000000, 8_000_000);
8766 }
8767
8768 #[test]
8769 fn test_error_chans_closed() {
8770         // Test that we properly handle error messages, closing appropriate channels.
8771         //
8772         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8773         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8774         // we can test various edge cases around it to ensure we don't regress.
8775         let chanmon_cfgs = create_chanmon_cfgs(3);
8776         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8777         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8778         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8779
8780         // Create some initial channels
8781         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8782         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8783         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8784
8785         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8786         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8787         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8788
8789         // Closing a channel from a different peer has no effect
8790         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8791         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8792
8793         // Closing one channel doesn't impact others
8794         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8795         check_added_monitors!(nodes[0], 1);
8796         check_closed_broadcast!(nodes[0], false);
8797         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8798         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_1.2 || nodes[0].node.list_usable_channels()[1].channel_id == chan_1.2);
8799         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2 || nodes[0].node.list_usable_channels()[1].channel_id == chan_3.2);
8800
8801         // A null channel ID should close all channels
8802         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8803         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8804         check_added_monitors!(nodes[0], 2);
8805         let events = nodes[0].node.get_and_clear_pending_msg_events();
8806         assert_eq!(events.len(), 2);
8807         match events[0] {
8808                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8809                         assert_eq!(msg.contents.flags & 2, 2);
8810                 },
8811                 _ => panic!("Unexpected event"),
8812         }
8813         match events[1] {
8814                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8815                         assert_eq!(msg.contents.flags & 2, 2);
8816                 },
8817                 _ => panic!("Unexpected event"),
8818         }
8819         // Note that at this point users of a standard PeerHandler will end up calling
8820         // peer_disconnected with no_connection_possible set to false, duplicating the
8821         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8822         // users with their own peer handling logic. We duplicate the call here, however.
8823         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8824         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8825
8826         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8827         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8828         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8829 }