Merge pull request #838 from TheBlueMatt/2021-03-skip-blocks
[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 fn do_test_1_conf_open(connect_style: ConnectStyle) {
398         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
399         // tests that we properly send one in that case.
400         let mut alice_config = UserConfig::default();
401         alice_config.own_channel_config.minimum_depth = 1;
402         alice_config.channel_options.announced_channel = true;
403         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
404         let mut bob_config = UserConfig::default();
405         bob_config.own_channel_config.minimum_depth = 1;
406         bob_config.channel_options.announced_channel = true;
407         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
408         let chanmon_cfgs = create_chanmon_cfgs(2);
409         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
410         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
411         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
412         *nodes[0].connect_style.borrow_mut() = connect_style;
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 #[test]
429 fn test_1_conf_open() {
430         do_test_1_conf_open(ConnectStyle::BestBlockFirst);
431         do_test_1_conf_open(ConnectStyle::TransactionsFirst);
432         do_test_1_conf_open(ConnectStyle::FullBlockViaListen);
433 }
434
435 fn do_test_sanity_on_in_flight_opens(steps: u8) {
436         // Previously, we had issues deserializing channels when we hadn't connected the first block
437         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
438         // serialization round-trips and simply do steps towards opening a channel and then drop the
439         // Node objects.
440
441         let chanmon_cfgs = create_chanmon_cfgs(2);
442         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
443         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
444         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
445
446         if steps & 0b1000_0000 != 0{
447                 let block = Block {
448                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
449                         txdata: vec![],
450                 };
451                 connect_block(&nodes[0], &block);
452                 connect_block(&nodes[1], &block);
453         }
454
455         if steps & 0x0f == 0 { return; }
456         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
457         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
458
459         if steps & 0x0f == 1 { return; }
460         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
461         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
462
463         if steps & 0x0f == 2 { return; }
464         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
465
466         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
467
468         if steps & 0x0f == 3 { return; }
469         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
470         check_added_monitors!(nodes[0], 0);
471         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
472
473         if steps & 0x0f == 4 { return; }
474         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
475         {
476                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
477                 assert_eq!(added_monitors.len(), 1);
478                 assert_eq!(added_monitors[0].0, funding_output);
479                 added_monitors.clear();
480         }
481         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
482
483         if steps & 0x0f == 5 { return; }
484         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
485         {
486                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
487                 assert_eq!(added_monitors.len(), 1);
488                 assert_eq!(added_monitors[0].0, funding_output);
489                 added_monitors.clear();
490         }
491
492         let events_4 = nodes[0].node.get_and_clear_pending_events();
493         assert_eq!(events_4.len(), 1);
494         match events_4[0] {
495                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
496                         assert_eq!(user_channel_id, 42);
497                         assert_eq!(*funding_txo, funding_output);
498                 },
499                 _ => panic!("Unexpected event"),
500         };
501
502         if steps & 0x0f == 6 { return; }
503         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
504
505         if steps & 0x0f == 7 { return; }
506         confirm_transaction_at(&nodes[0], &tx, 2);
507         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
508         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
509 }
510
511 #[test]
512 fn test_sanity_on_in_flight_opens() {
513         do_test_sanity_on_in_flight_opens(0);
514         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
515         do_test_sanity_on_in_flight_opens(1);
516         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
517         do_test_sanity_on_in_flight_opens(2);
518         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
519         do_test_sanity_on_in_flight_opens(3);
520         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
521         do_test_sanity_on_in_flight_opens(4);
522         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
523         do_test_sanity_on_in_flight_opens(5);
524         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
525         do_test_sanity_on_in_flight_opens(6);
526         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
527         do_test_sanity_on_in_flight_opens(7);
528         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
529         do_test_sanity_on_in_flight_opens(8);
530         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
531 }
532
533 #[test]
534 fn test_update_fee_vanilla() {
535         let chanmon_cfgs = create_chanmon_cfgs(2);
536         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
537         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
538         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
539         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
540         let channel_id = chan.2;
541
542         let feerate = get_feerate!(nodes[0], channel_id);
543         nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
544         check_added_monitors!(nodes[0], 1);
545
546         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
547         assert_eq!(events_0.len(), 1);
548         let (update_msg, commitment_signed) = match events_0[0] {
549                         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 } } => {
550                         (update_fee.as_ref(), commitment_signed)
551                 },
552                 _ => panic!("Unexpected event"),
553         };
554         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
555
556         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
557         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
558         check_added_monitors!(nodes[1], 1);
559
560         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
561         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
562         check_added_monitors!(nodes[0], 1);
563
564         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
565         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
566         // No commitment_signed so get_event_msg's assert(len == 1) passes
567         check_added_monitors!(nodes[0], 1);
568
569         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
570         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
571         check_added_monitors!(nodes[1], 1);
572 }
573
574 #[test]
575 fn test_update_fee_that_funder_cannot_afford() {
576         let chanmon_cfgs = create_chanmon_cfgs(2);
577         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
578         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
579         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
580         let channel_value = 1888;
581         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
582         let channel_id = chan.2;
583
584         let feerate = 260;
585         nodes[0].node.update_fee(channel_id, feerate).unwrap();
586         check_added_monitors!(nodes[0], 1);
587         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
588
589         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
590
591         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
592
593         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
594         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
595         {
596                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
597
598                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
599                 let num_htlcs = commitment_tx.output.len() - 2;
600                 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
601                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
602                 actual_fee = channel_value - actual_fee;
603                 assert_eq!(total_fee, actual_fee);
604         }
605
606         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
607         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
608         nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
609         check_added_monitors!(nodes[0], 1);
610
611         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
612
613         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
614
615         //While producing the commitment_signed response after handling a received update_fee request the
616         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
617         //Should produce and error.
618         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
619         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
620         check_added_monitors!(nodes[1], 1);
621         check_closed_broadcast!(nodes[1], true);
622 }
623
624 #[test]
625 fn test_update_fee_with_fundee_update_add_htlc() {
626         let chanmon_cfgs = create_chanmon_cfgs(2);
627         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
628         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
629         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
630         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
631         let channel_id = chan.2;
632         let logger = test_utils::TestLogger::new();
633
634         // balancing
635         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
636
637         let feerate = get_feerate!(nodes[0], channel_id);
638         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
639         check_added_monitors!(nodes[0], 1);
640
641         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
642         assert_eq!(events_0.len(), 1);
643         let (update_msg, commitment_signed) = match events_0[0] {
644                         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 } } => {
645                         (update_fee.as_ref(), commitment_signed)
646                 },
647                 _ => panic!("Unexpected event"),
648         };
649         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
650         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
651         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
652         check_added_monitors!(nodes[1], 1);
653
654         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
655         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
656         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();
657
658         // nothing happens since node[1] is in AwaitingRemoteRevoke
659         nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
660         {
661                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
662                 assert_eq!(added_monitors.len(), 0);
663                 added_monitors.clear();
664         }
665         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
666         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
667         // node[1] has nothing to do
668
669         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
670         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
671         check_added_monitors!(nodes[0], 1);
672
673         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
674         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
675         // No commitment_signed so get_event_msg's assert(len == 1) passes
676         check_added_monitors!(nodes[0], 1);
677         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
678         check_added_monitors!(nodes[1], 1);
679         // AwaitingRemoteRevoke ends here
680
681         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
682         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
683         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
684         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
685         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
686         assert_eq!(commitment_update.update_fee.is_none(), true);
687
688         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
689         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
690         check_added_monitors!(nodes[0], 1);
691         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
692
693         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
694         check_added_monitors!(nodes[1], 1);
695         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
696
697         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
698         check_added_monitors!(nodes[1], 1);
699         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
700         // No commitment_signed so get_event_msg's assert(len == 1) passes
701
702         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
703         check_added_monitors!(nodes[0], 1);
704         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
705
706         expect_pending_htlcs_forwardable!(nodes[0]);
707
708         let events = nodes[0].node.get_and_clear_pending_events();
709         assert_eq!(events.len(), 1);
710         match events[0] {
711                 Event::PaymentReceived { .. } => { },
712                 _ => panic!("Unexpected event"),
713         };
714
715         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
716
717         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
718         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
719         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
720 }
721
722 #[test]
723 fn test_update_fee() {
724         let chanmon_cfgs = create_chanmon_cfgs(2);
725         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
726         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
727         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
728         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
729         let channel_id = chan.2;
730
731         // A                                        B
732         // (1) update_fee/commitment_signed      ->
733         //                                       <- (2) revoke_and_ack
734         //                                       .- send (3) commitment_signed
735         // (4) update_fee/commitment_signed      ->
736         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
737         //                                       <- (3) commitment_signed delivered
738         // send (6) revoke_and_ack               -.
739         //                                       <- (5) deliver revoke_and_ack
740         // (6) deliver revoke_and_ack            ->
741         //                                       .- send (7) commitment_signed in response to (4)
742         //                                       <- (7) deliver commitment_signed
743         // revoke_and_ack                        ->
744
745         // Create and deliver (1)...
746         let feerate = get_feerate!(nodes[0], channel_id);
747         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
748         check_added_monitors!(nodes[0], 1);
749
750         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
751         assert_eq!(events_0.len(), 1);
752         let (update_msg, commitment_signed) = match events_0[0] {
753                         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 } } => {
754                         (update_fee.as_ref(), commitment_signed)
755                 },
756                 _ => panic!("Unexpected event"),
757         };
758         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
759
760         // Generate (2) and (3):
761         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
762         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
763         check_added_monitors!(nodes[1], 1);
764
765         // Deliver (2):
766         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
767         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
768         check_added_monitors!(nodes[0], 1);
769
770         // Create and deliver (4)...
771         nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
772         check_added_monitors!(nodes[0], 1);
773         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
774         assert_eq!(events_0.len(), 1);
775         let (update_msg, commitment_signed) = match events_0[0] {
776                         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 } } => {
777                         (update_fee.as_ref(), commitment_signed)
778                 },
779                 _ => panic!("Unexpected event"),
780         };
781
782         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
783         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
784         check_added_monitors!(nodes[1], 1);
785         // ... creating (5)
786         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
787         // No commitment_signed so get_event_msg's assert(len == 1) passes
788
789         // Handle (3), creating (6):
790         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
791         check_added_monitors!(nodes[0], 1);
792         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
793         // No commitment_signed so get_event_msg's assert(len == 1) passes
794
795         // Deliver (5):
796         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
797         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
798         check_added_monitors!(nodes[0], 1);
799
800         // Deliver (6), creating (7):
801         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
802         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
803         assert!(commitment_update.update_add_htlcs.is_empty());
804         assert!(commitment_update.update_fulfill_htlcs.is_empty());
805         assert!(commitment_update.update_fail_htlcs.is_empty());
806         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
807         assert!(commitment_update.update_fee.is_none());
808         check_added_monitors!(nodes[1], 1);
809
810         // Deliver (7)
811         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
812         check_added_monitors!(nodes[0], 1);
813         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
814         // No commitment_signed so get_event_msg's assert(len == 1) passes
815
816         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
817         check_added_monitors!(nodes[1], 1);
818         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
819
820         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
821         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
822         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
823 }
824
825 #[test]
826 fn pre_funding_lock_shutdown_test() {
827         // Test sending a shutdown prior to funding_locked after funding generation
828         let chanmon_cfgs = create_chanmon_cfgs(2);
829         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
830         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
831         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
832         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
833         mine_transaction(&nodes[0], &tx);
834         mine_transaction(&nodes[1], &tx);
835
836         nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
837         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
838         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
839         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
840         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
841
842         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
843         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
844         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
845         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
846         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
847         assert!(node_0_none.is_none());
848
849         assert!(nodes[0].node.list_channels().is_empty());
850         assert!(nodes[1].node.list_channels().is_empty());
851 }
852
853 #[test]
854 fn updates_shutdown_wait() {
855         // Test sending a shutdown with outstanding updates pending
856         let chanmon_cfgs = create_chanmon_cfgs(3);
857         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
858         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
859         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
860         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
861         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
862         let logger = test_utils::TestLogger::new();
863
864         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
865
866         nodes[0].node.close_channel(&chan_1.2).unwrap();
867         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
868         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
869         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
870         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
871
872         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
873         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
874
875         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
876
877         let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
878         let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
879         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();
880         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();
881         unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
882         unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
883
884         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
885         check_added_monitors!(nodes[2], 1);
886         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
887         assert!(updates.update_add_htlcs.is_empty());
888         assert!(updates.update_fail_htlcs.is_empty());
889         assert!(updates.update_fail_malformed_htlcs.is_empty());
890         assert!(updates.update_fee.is_none());
891         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
892         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
893         check_added_monitors!(nodes[1], 1);
894         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
895         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
896
897         assert!(updates_2.update_add_htlcs.is_empty());
898         assert!(updates_2.update_fail_htlcs.is_empty());
899         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
900         assert!(updates_2.update_fee.is_none());
901         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
902         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
903         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
904
905         let events = nodes[0].node.get_and_clear_pending_events();
906         assert_eq!(events.len(), 1);
907         match events[0] {
908                 Event::PaymentSent { ref payment_preimage } => {
909                         assert_eq!(our_payment_preimage, *payment_preimage);
910                 },
911                 _ => panic!("Unexpected event"),
912         }
913
914         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
915         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
916         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
917         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
918         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
919         assert!(node_0_none.is_none());
920
921         assert!(nodes[0].node.list_channels().is_empty());
922
923         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
924         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
925         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
926         assert!(nodes[1].node.list_channels().is_empty());
927         assert!(nodes[2].node.list_channels().is_empty());
928 }
929
930 #[test]
931 fn htlc_fail_async_shutdown() {
932         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
933         let chanmon_cfgs = create_chanmon_cfgs(3);
934         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
935         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
936         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
937         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
938         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
939         let logger = test_utils::TestLogger::new();
940
941         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
942         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
943         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();
944         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
945         check_added_monitors!(nodes[0], 1);
946         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
947         assert_eq!(updates.update_add_htlcs.len(), 1);
948         assert!(updates.update_fulfill_htlcs.is_empty());
949         assert!(updates.update_fail_htlcs.is_empty());
950         assert!(updates.update_fail_malformed_htlcs.is_empty());
951         assert!(updates.update_fee.is_none());
952
953         nodes[1].node.close_channel(&chan_1.2).unwrap();
954         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
955         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
956         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
957
958         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
959         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
960         check_added_monitors!(nodes[1], 1);
961         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
962         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
963
964         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
965         assert!(updates_2.update_add_htlcs.is_empty());
966         assert!(updates_2.update_fulfill_htlcs.is_empty());
967         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
968         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
969         assert!(updates_2.update_fee.is_none());
970
971         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
972         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
973
974         expect_payment_failed!(nodes[0], our_payment_hash, false);
975
976         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
977         assert_eq!(msg_events.len(), 2);
978         let node_0_closing_signed = match msg_events[0] {
979                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
980                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
981                         (*msg).clone()
982                 },
983                 _ => panic!("Unexpected event"),
984         };
985         match msg_events[1] {
986                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
987                         assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
988                 },
989                 _ => panic!("Unexpected event"),
990         }
991
992         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
993         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
994         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
995         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
996         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
997         assert!(node_0_none.is_none());
998
999         assert!(nodes[0].node.list_channels().is_empty());
1000
1001         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1002         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1003         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1004         assert!(nodes[1].node.list_channels().is_empty());
1005         assert!(nodes[2].node.list_channels().is_empty());
1006 }
1007
1008 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1009         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1010         // messages delivered prior to disconnect
1011         let chanmon_cfgs = create_chanmon_cfgs(3);
1012         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1013         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1014         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1015         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1016         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1017
1018         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1019
1020         nodes[1].node.close_channel(&chan_1.2).unwrap();
1021         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1022         if recv_count > 0 {
1023                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
1024                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1025                 if recv_count > 1 {
1026                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
1027                 }
1028         }
1029
1030         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1031         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1032
1033         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1034         let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1035         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1036         let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1037
1038         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1039         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1040         assert!(node_1_shutdown == node_1_2nd_shutdown);
1041
1042         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1043         let node_0_2nd_shutdown = if recv_count > 0 {
1044                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1045                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1046                 node_0_2nd_shutdown
1047         } else {
1048                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1049                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1050                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1051         };
1052         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_2nd_shutdown);
1053
1054         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1055         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1056
1057         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1058         check_added_monitors!(nodes[2], 1);
1059         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1060         assert!(updates.update_add_htlcs.is_empty());
1061         assert!(updates.update_fail_htlcs.is_empty());
1062         assert!(updates.update_fail_malformed_htlcs.is_empty());
1063         assert!(updates.update_fee.is_none());
1064         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1065         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1066         check_added_monitors!(nodes[1], 1);
1067         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1068         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1069
1070         assert!(updates_2.update_add_htlcs.is_empty());
1071         assert!(updates_2.update_fail_htlcs.is_empty());
1072         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1073         assert!(updates_2.update_fee.is_none());
1074         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1075         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1076         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1077
1078         let events = nodes[0].node.get_and_clear_pending_events();
1079         assert_eq!(events.len(), 1);
1080         match events[0] {
1081                 Event::PaymentSent { ref payment_preimage } => {
1082                         assert_eq!(our_payment_preimage, *payment_preimage);
1083                 },
1084                 _ => panic!("Unexpected event"),
1085         }
1086
1087         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1088         if recv_count > 0 {
1089                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1090                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1091                 assert!(node_1_closing_signed.is_some());
1092         }
1093
1094         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1095         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1096
1097         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1098         let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1099         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1100         if recv_count == 0 {
1101                 // If all closing_signeds weren't delivered we can just resume where we left off...
1102                 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1103
1104                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1105                 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1106                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1107
1108                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1109                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1110                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1111
1112                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_3rd_shutdown);
1113                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1114
1115                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_3rd_shutdown);
1116                 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1117                 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1118
1119                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1120                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1121                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1122                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1123                 assert!(node_0_none.is_none());
1124         } else {
1125                 // If one node, however, received + responded with an identical closing_signed we end
1126                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1127                 // There isn't really anything better we can do simply, but in the future we might
1128                 // explore storing a set of recently-closed channels that got disconnected during
1129                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1130                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1131                 // transaction.
1132                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1133
1134                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1135                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1136                 assert_eq!(msg_events.len(), 1);
1137                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1138                         match action {
1139                                 &ErrorAction::SendErrorMessage { ref msg } => {
1140                                         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1141                                         assert_eq!(msg.channel_id, chan_1.2);
1142                                 },
1143                                 _ => panic!("Unexpected event!"),
1144                         }
1145                 } else { panic!("Needed SendErrorMessage close"); }
1146
1147                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1148                 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1149                 // closing_signed so we do it ourselves
1150                 check_closed_broadcast!(nodes[0], false);
1151                 check_added_monitors!(nodes[0], 1);
1152         }
1153
1154         assert!(nodes[0].node.list_channels().is_empty());
1155
1156         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1157         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1158         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1159         assert!(nodes[1].node.list_channels().is_empty());
1160         assert!(nodes[2].node.list_channels().is_empty());
1161 }
1162
1163 #[test]
1164 fn test_shutdown_rebroadcast() {
1165         do_test_shutdown_rebroadcast(0);
1166         do_test_shutdown_rebroadcast(1);
1167         do_test_shutdown_rebroadcast(2);
1168 }
1169
1170 #[test]
1171 fn fake_network_test() {
1172         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1173         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1174         let chanmon_cfgs = create_chanmon_cfgs(4);
1175         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1176         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1177         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1178
1179         // Create some initial channels
1180         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1181         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1182         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1183
1184         // Rebalance the network a bit by relaying one payment through all the channels...
1185         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1186         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1187         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1188         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1189
1190         // Send some more payments
1191         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1192         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1193         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1194
1195         // Test failure packets
1196         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1197         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1198
1199         // Add a new channel that skips 3
1200         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1201
1202         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1203         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1204         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1205         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1206         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1207         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1208         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1209
1210         // Do some rebalance loop payments, simultaneously
1211         let mut hops = Vec::with_capacity(3);
1212         hops.push(RouteHop {
1213                 pubkey: nodes[2].node.get_our_node_id(),
1214                 node_features: NodeFeatures::empty(),
1215                 short_channel_id: chan_2.0.contents.short_channel_id,
1216                 channel_features: ChannelFeatures::empty(),
1217                 fee_msat: 0,
1218                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1219         });
1220         hops.push(RouteHop {
1221                 pubkey: nodes[3].node.get_our_node_id(),
1222                 node_features: NodeFeatures::empty(),
1223                 short_channel_id: chan_3.0.contents.short_channel_id,
1224                 channel_features: ChannelFeatures::empty(),
1225                 fee_msat: 0,
1226                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1227         });
1228         hops.push(RouteHop {
1229                 pubkey: nodes[1].node.get_our_node_id(),
1230                 node_features: NodeFeatures::empty(),
1231                 short_channel_id: chan_4.0.contents.short_channel_id,
1232                 channel_features: ChannelFeatures::empty(),
1233                 fee_msat: 1000000,
1234                 cltv_expiry_delta: TEST_FINAL_CLTV,
1235         });
1236         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;
1237         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;
1238         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1239
1240         let mut hops = Vec::with_capacity(3);
1241         hops.push(RouteHop {
1242                 pubkey: nodes[3].node.get_our_node_id(),
1243                 node_features: NodeFeatures::empty(),
1244                 short_channel_id: chan_4.0.contents.short_channel_id,
1245                 channel_features: ChannelFeatures::empty(),
1246                 fee_msat: 0,
1247                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1248         });
1249         hops.push(RouteHop {
1250                 pubkey: nodes[2].node.get_our_node_id(),
1251                 node_features: NodeFeatures::empty(),
1252                 short_channel_id: chan_3.0.contents.short_channel_id,
1253                 channel_features: ChannelFeatures::empty(),
1254                 fee_msat: 0,
1255                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1256         });
1257         hops.push(RouteHop {
1258                 pubkey: nodes[1].node.get_our_node_id(),
1259                 node_features: NodeFeatures::empty(),
1260                 short_channel_id: chan_2.0.contents.short_channel_id,
1261                 channel_features: ChannelFeatures::empty(),
1262                 fee_msat: 1000000,
1263                 cltv_expiry_delta: TEST_FINAL_CLTV,
1264         });
1265         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;
1266         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;
1267         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1268
1269         // Claim the rebalances...
1270         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1271         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1272
1273         // Add a duplicate new channel from 2 to 4
1274         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1275
1276         // Send some payments across both channels
1277         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1278         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1279         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1280
1281
1282         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1283         let events = nodes[0].node.get_and_clear_pending_msg_events();
1284         assert_eq!(events.len(), 0);
1285         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);
1286
1287         //TODO: Test that routes work again here as we've been notified that the channel is full
1288
1289         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1290         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1291         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1292
1293         // Close down the channels...
1294         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1295         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1296         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1297         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1298         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1299 }
1300
1301 #[test]
1302 fn holding_cell_htlc_counting() {
1303         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1304         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1305         // commitment dance rounds.
1306         let chanmon_cfgs = create_chanmon_cfgs(3);
1307         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1308         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1309         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1310         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1311         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1312         let logger = test_utils::TestLogger::new();
1313
1314         let mut payments = Vec::new();
1315         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1316                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1317                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1318                 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();
1319                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1320                 payments.push((payment_preimage, payment_hash));
1321         }
1322         check_added_monitors!(nodes[1], 1);
1323
1324         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1325         assert_eq!(events.len(), 1);
1326         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1327         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1328
1329         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1330         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1331         // another HTLC.
1332         let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1333         {
1334                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1335                 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();
1336                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1337                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1338                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1339                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1340         }
1341
1342         // This should also be true if we try to forward a payment.
1343         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1344         {
1345                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1346                 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();
1347                 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1348                 check_added_monitors!(nodes[0], 1);
1349         }
1350
1351         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1352         assert_eq!(events.len(), 1);
1353         let payment_event = SendEvent::from_event(events.pop().unwrap());
1354         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1355
1356         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1357         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1358         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1359         // fails), the second will process the resulting failure and fail the HTLC backward.
1360         expect_pending_htlcs_forwardable!(nodes[1]);
1361         expect_pending_htlcs_forwardable!(nodes[1]);
1362         check_added_monitors!(nodes[1], 1);
1363
1364         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1365         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1366         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1367
1368         let events = nodes[0].node.get_and_clear_pending_msg_events();
1369         assert_eq!(events.len(), 1);
1370         match events[0] {
1371                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1372                         assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1373                 },
1374                 _ => panic!("Unexpected event"),
1375         }
1376
1377         expect_payment_failed!(nodes[0], payment_hash_2, false);
1378
1379         // Now forward all the pending HTLCs and claim them back
1380         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1381         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1382         check_added_monitors!(nodes[2], 1);
1383
1384         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1385         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1386         check_added_monitors!(nodes[1], 1);
1387         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1388
1389         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1390         check_added_monitors!(nodes[1], 1);
1391         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1392
1393         for ref update in as_updates.update_add_htlcs.iter() {
1394                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1395         }
1396         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1397         check_added_monitors!(nodes[2], 1);
1398         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1399         check_added_monitors!(nodes[2], 1);
1400         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1401
1402         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1403         check_added_monitors!(nodes[1], 1);
1404         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1405         check_added_monitors!(nodes[1], 1);
1406         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1407
1408         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1409         check_added_monitors!(nodes[2], 1);
1410
1411         expect_pending_htlcs_forwardable!(nodes[2]);
1412
1413         let events = nodes[2].node.get_and_clear_pending_events();
1414         assert_eq!(events.len(), payments.len());
1415         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1416                 match event {
1417                         &Event::PaymentReceived { ref payment_hash, .. } => {
1418                                 assert_eq!(*payment_hash, *hash);
1419                         },
1420                         _ => panic!("Unexpected event"),
1421                 };
1422         }
1423
1424         for (preimage, _) in payments.drain(..) {
1425                 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1426         }
1427
1428         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1429 }
1430
1431 #[test]
1432 fn duplicate_htlc_test() {
1433         // Test that we accept duplicate payment_hash HTLCs across the network and that
1434         // claiming/failing them are all separate and don't affect each other
1435         let chanmon_cfgs = create_chanmon_cfgs(6);
1436         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1437         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1438         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1439
1440         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1441         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1442         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1443         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1444         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1445         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1446
1447         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1448
1449         *nodes[0].network_payment_count.borrow_mut() -= 1;
1450         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1451
1452         *nodes[0].network_payment_count.borrow_mut() -= 1;
1453         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1454
1455         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1456         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1457         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1458 }
1459
1460 #[test]
1461 fn test_duplicate_htlc_different_direction_onchain() {
1462         // Test that ChannelMonitor doesn't generate 2 preimage txn
1463         // when we have 2 HTLCs with same preimage that go across a node
1464         // in opposite directions.
1465         let chanmon_cfgs = create_chanmon_cfgs(2);
1466         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1467         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1468         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1469
1470         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1471         let logger = test_utils::TestLogger::new();
1472
1473         // balancing
1474         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1475
1476         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1477
1478         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1479         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();
1480         send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1481
1482         // Provide preimage to node 0 by claiming payment
1483         nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1484         check_added_monitors!(nodes[0], 1);
1485
1486         // Broadcast node 1 commitment txn
1487         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1488
1489         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1490         let mut has_both_htlcs = 0; // check htlcs match ones committed
1491         for outp in remote_txn[0].output.iter() {
1492                 if outp.value == 800_000 / 1000 {
1493                         has_both_htlcs += 1;
1494                 } else if outp.value == 900_000 / 1000 {
1495                         has_both_htlcs += 1;
1496                 }
1497         }
1498         assert_eq!(has_both_htlcs, 2);
1499
1500         mine_transaction(&nodes[0], &remote_txn[0]);
1501         check_added_monitors!(nodes[0], 1);
1502
1503         // Check we only broadcast 1 timeout tx
1504         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1505         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()) };
1506         assert_eq!(claim_txn.len(), 5);
1507         check_spends!(claim_txn[2], chan_1.3);
1508         check_spends!(claim_txn[3], claim_txn[2]);
1509         assert_eq!(htlc_pair.0.input.len(), 1);
1510         assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1511         check_spends!(htlc_pair.0, remote_txn[0]);
1512         assert_eq!(htlc_pair.1.input.len(), 1);
1513         assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1514         check_spends!(htlc_pair.1, remote_txn[0]);
1515
1516         let events = nodes[0].node.get_and_clear_pending_msg_events();
1517         assert_eq!(events.len(), 3);
1518         for e in events {
1519                 match e {
1520                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1521                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1522                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1523                                 assert_eq!(msg.data, "Commitment or closing transaction was confirmed on chain.");
1524                         },
1525                         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, .. } } => {
1526                                 assert!(update_add_htlcs.is_empty());
1527                                 assert!(update_fail_htlcs.is_empty());
1528                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1529                                 assert!(update_fail_malformed_htlcs.is_empty());
1530                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1531                         },
1532                         _ => panic!("Unexpected event"),
1533                 }
1534         }
1535 }
1536
1537 #[test]
1538 fn test_basic_channel_reserve() {
1539         let chanmon_cfgs = create_chanmon_cfgs(2);
1540         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1541         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1542         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1543         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1544         let logger = test_utils::TestLogger::new();
1545
1546         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1547         let channel_reserve = chan_stat.channel_reserve_msat;
1548
1549         // The 2* and +1 are for the fee spike reserve.
1550         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1551         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1552         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1553         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1554         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();
1555         let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1556         match err {
1557                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1558                         match &fails[0] {
1559                                 &APIError::ChannelUnavailable{ref err} =>
1560                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1561                                 _ => panic!("Unexpected error variant"),
1562                         }
1563                 },
1564                 _ => panic!("Unexpected error variant"),
1565         }
1566         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1567         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);
1568
1569         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1570 }
1571
1572 #[test]
1573 fn test_fee_spike_violation_fails_htlc() {
1574         let chanmon_cfgs = create_chanmon_cfgs(2);
1575         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1576         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1577         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1578         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1579         let logger = test_utils::TestLogger::new();
1580
1581         macro_rules! get_route_and_payment_hash {
1582                 ($recv_value: expr) => {{
1583                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1584                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1585                         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();
1586                         (route, payment_hash, payment_preimage)
1587                 }}
1588         }
1589
1590         let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1591         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1592         let secp_ctx = Secp256k1::new();
1593         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1594
1595         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1596
1597         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1598         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1599         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1600         let msg = msgs::UpdateAddHTLC {
1601                 channel_id: chan.2,
1602                 htlc_id: 0,
1603                 amount_msat: htlc_msat,
1604                 payment_hash: payment_hash,
1605                 cltv_expiry: htlc_cltv,
1606                 onion_routing_packet: onion_packet,
1607         };
1608
1609         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1610
1611         // Now manually create the commitment_signed message corresponding to the update_add
1612         // nodes[0] just sent. In the code for construction of this message, "local" refers
1613         // to the sender of the message, and "remote" refers to the receiver.
1614
1615         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1616
1617         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1618
1619         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1620         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1621         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point) = {
1622                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1623                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1624                 let chan_signer = local_chan.get_signer();
1625                 let pubkeys = chan_signer.pubkeys();
1626                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1627                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1628                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
1629         };
1630         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point) = {
1631                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1632                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1633                 let chan_signer = remote_chan.get_signer();
1634                 let pubkeys = chan_signer.pubkeys();
1635                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1636                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
1637         };
1638
1639         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1640         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1641                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1642
1643         // Build the remote commitment transaction so we can sign it, and then later use the
1644         // signature for the commitment_signed message.
1645         let local_chan_balance = 1313;
1646
1647         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1648                 offered: false,
1649                 amount_msat: 3460001,
1650                 cltv_expiry: htlc_cltv,
1651                 payment_hash,
1652                 transaction_output_index: Some(1),
1653         };
1654
1655         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1656
1657         let res = {
1658                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1659                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1660                 let local_chan_signer = local_chan.get_signer();
1661                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1662                         commitment_number,
1663                         95000,
1664                         local_chan_balance,
1665                         commit_tx_keys.clone(),
1666                         feerate_per_kw,
1667                         &mut vec![(accepted_htlc_info, ())],
1668                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1669                 );
1670                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1671         };
1672
1673         let commit_signed_msg = msgs::CommitmentSigned {
1674                 channel_id: chan.2,
1675                 signature: res.0,
1676                 htlc_signatures: res.1
1677         };
1678
1679         // Send the commitment_signed message to the nodes[1].
1680         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1681         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1682
1683         // Send the RAA to nodes[1].
1684         let raa_msg = msgs::RevokeAndACK {
1685                 channel_id: chan.2,
1686                 per_commitment_secret: local_secret,
1687                 next_per_commitment_point: next_local_point
1688         };
1689         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1690
1691         let events = nodes[1].node.get_and_clear_pending_msg_events();
1692         assert_eq!(events.len(), 1);
1693         // Make sure the HTLC failed in the way we expect.
1694         match events[0] {
1695                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1696                         assert_eq!(update_fail_htlcs.len(), 1);
1697                         update_fail_htlcs[0].clone()
1698                 },
1699                 _ => panic!("Unexpected event"),
1700         };
1701         nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1702
1703         check_added_monitors!(nodes[1], 2);
1704 }
1705
1706 #[test]
1707 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1708         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1709         // Set the fee rate for the channel very high, to the point where the fundee
1710         // sending any above-dust amount would result in a channel reserve violation.
1711         // In this test we check that we would be prevented from sending an HTLC in
1712         // this situation.
1713         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1714         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1715         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1716         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1717         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1718         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1719         let logger = test_utils::TestLogger::new();
1720
1721         macro_rules! get_route_and_payment_hash {
1722                 ($recv_value: expr) => {{
1723                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1724                         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1725                         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();
1726                         (route, payment_hash, payment_preimage)
1727                 }}
1728         }
1729
1730         let (route, our_payment_hash, _) = get_route_and_payment_hash!(4843000);
1731         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1732                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1733         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1734         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);
1735 }
1736
1737 #[test]
1738 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1739         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1740         // Set the fee rate for the channel very high, to the point where the funder
1741         // receiving 1 update_add_htlc would result in them closing the channel due
1742         // to channel reserve violation. This close could also happen if the fee went
1743         // up a more realistic amount, but many HTLCs were outstanding at the time of
1744         // the update_add_htlc.
1745         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1746         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1747         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1748         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1749         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1750         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1751         let logger = test_utils::TestLogger::new();
1752
1753         macro_rules! get_route_and_payment_hash {
1754                 ($recv_value: expr) => {{
1755                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1756                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1757                         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();
1758                         (route, payment_hash, payment_preimage)
1759                 }}
1760         }
1761
1762         let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1763         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1764         let secp_ctx = Secp256k1::new();
1765         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1766         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1767         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1768         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1769         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1770         let msg = msgs::UpdateAddHTLC {
1771                 channel_id: chan.2,
1772                 htlc_id: 1,
1773                 amount_msat: htlc_msat + 1,
1774                 payment_hash: payment_hash,
1775                 cltv_expiry: htlc_cltv,
1776                 onion_routing_packet: onion_packet,
1777         };
1778
1779         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1780         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1781         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);
1782         assert_eq!(nodes[0].node.list_channels().len(), 0);
1783         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1784         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1785         check_added_monitors!(nodes[0], 1);
1786 }
1787
1788 #[test]
1789 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1790         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1791         // calculating our commitment transaction fee (this was previously broken).
1792         let chanmon_cfgs = create_chanmon_cfgs(2);
1793         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1794         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1795         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1796
1797         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1798         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1799         // transaction fee with 0 HTLCs (183 sats)).
1800         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98817000, InitFeatures::known(), InitFeatures::known());
1801
1802         let dust_amt = 546000; // Dust amount
1803         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1804         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1805         // commitment transaction fee.
1806         let (_, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1807 }
1808
1809 #[test]
1810 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1811         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1812         // calculating our counterparty's commitment transaction fee (this was previously broken).
1813         let chanmon_cfgs = create_chanmon_cfgs(2);
1814         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1815         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1816         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1817         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1818
1819         let payment_amt = 46000; // Dust amount
1820         // In the previous code, these first four payments would succeed.
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
1826         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1827         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1828         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1829         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1830         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1831         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1832
1833         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1834         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1835         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1836         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1837 }
1838
1839 #[test]
1840 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1841         let chanmon_cfgs = create_chanmon_cfgs(3);
1842         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1843         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1844         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1845         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1846         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1847         let logger = test_utils::TestLogger::new();
1848
1849         macro_rules! get_route_and_payment_hash {
1850                 ($recv_value: expr) => {{
1851                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1852                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1853                         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();
1854                         (route, payment_hash, payment_preimage)
1855                 }}
1856         }
1857
1858         let feemsat = 239;
1859         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1860         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1861         let feerate = get_feerate!(nodes[0], chan.2);
1862
1863         // Add a 2* and +1 for the fee spike reserve.
1864         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1865         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;
1866         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1867
1868         // Add a pending HTLC.
1869         let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1870         let payment_event_1 = {
1871                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1872                 check_added_monitors!(nodes[0], 1);
1873
1874                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1875                 assert_eq!(events.len(), 1);
1876                 SendEvent::from_event(events.remove(0))
1877         };
1878         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1879
1880         // Attempt to trigger a channel reserve violation --> payment failure.
1881         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1882         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;
1883         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1884         let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1885
1886         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1887         let secp_ctx = Secp256k1::new();
1888         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1889         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1890         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1891         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1892         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1893         let msg = msgs::UpdateAddHTLC {
1894                 channel_id: chan.2,
1895                 htlc_id: 1,
1896                 amount_msat: htlc_msat + 1,
1897                 payment_hash: our_payment_hash_1,
1898                 cltv_expiry: htlc_cltv,
1899                 onion_routing_packet: onion_packet,
1900         };
1901
1902         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1903         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1904         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1905         assert_eq!(nodes[1].node.list_channels().len(), 1);
1906         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1907         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1908         check_added_monitors!(nodes[1], 1);
1909 }
1910
1911 #[test]
1912 fn test_inbound_outbound_capacity_is_not_zero() {
1913         let chanmon_cfgs = create_chanmon_cfgs(2);
1914         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1915         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1916         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1917         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1918         let channels0 = node_chanmgrs[0].list_channels();
1919         let channels1 = node_chanmgrs[1].list_channels();
1920         assert_eq!(channels0.len(), 1);
1921         assert_eq!(channels1.len(), 1);
1922
1923         assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1924         assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1925
1926         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1927         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1928 }
1929
1930 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1931         (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1932 }
1933
1934 #[test]
1935 fn test_channel_reserve_holding_cell_htlcs() {
1936         let chanmon_cfgs = create_chanmon_cfgs(3);
1937         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1938         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1939         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1940         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1941         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1942         let logger = test_utils::TestLogger::new();
1943
1944         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1945         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1946
1947         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1948         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1949
1950         macro_rules! get_route_and_payment_hash {
1951                 ($recv_value: expr) => {{
1952                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1953                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1954                         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();
1955                         (route, payment_hash, payment_preimage)
1956                 }}
1957         }
1958
1959         macro_rules! expect_forward {
1960                 ($node: expr) => {{
1961                         let mut events = $node.node.get_and_clear_pending_msg_events();
1962                         assert_eq!(events.len(), 1);
1963                         check_added_monitors!($node, 1);
1964                         let payment_event = SendEvent::from_event(events.remove(0));
1965                         payment_event
1966                 }}
1967         }
1968
1969         let feemsat = 239; // somehow we know?
1970         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1971         let feerate = get_feerate!(nodes[0], chan_1.2);
1972
1973         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1974
1975         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1976         {
1977                 let (mut route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0);
1978                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1979                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1980                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1981                         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)));
1982                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1983                 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);
1984         }
1985
1986         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1987         // nodes[0]'s wealth
1988         loop {
1989                 let amt_msat = recv_value_0 + total_fee_msat;
1990                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1991                 // Also, ensure that each payment has enough to be over the dust limit to
1992                 // ensure it'll be included in each commit tx fee calculation.
1993                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1994                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1995                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1996                         break;
1997                 }
1998                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1999
2000                 let (stat01_, stat11_, stat12_, stat22_) = (
2001                         get_channel_value_stat!(nodes[0], chan_1.2),
2002                         get_channel_value_stat!(nodes[1], chan_1.2),
2003                         get_channel_value_stat!(nodes[1], chan_2.2),
2004                         get_channel_value_stat!(nodes[2], chan_2.2),
2005                 );
2006
2007                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
2008                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
2009                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
2010                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
2011                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
2012         }
2013
2014         // adding pending output.
2015         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
2016         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2017         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2018         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2019         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2020         // cases where 1 msat over X amount will cause a payment failure, but anything less than
2021         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2022         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2023         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2024         // policy.
2025         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2026         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2027         let amt_msat_1 = recv_value_1 + total_fee_msat;
2028
2029         let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2030         let payment_event_1 = {
2031                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
2032                 check_added_monitors!(nodes[0], 1);
2033
2034                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2035                 assert_eq!(events.len(), 1);
2036                 SendEvent::from_event(events.remove(0))
2037         };
2038         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2039
2040         // channel reserve test with htlc pending output > 0
2041         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2042         {
2043                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2044                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2045                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2046                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2047         }
2048
2049         // split the rest to test holding cell
2050         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2051         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2052         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2053         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2054         {
2055                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2056                 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);
2057         }
2058
2059         // now see if they go through on both sides
2060         let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2061         // but this will stuck in the holding cell
2062         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2063         check_added_monitors!(nodes[0], 0);
2064         let events = nodes[0].node.get_and_clear_pending_events();
2065         assert_eq!(events.len(), 0);
2066
2067         // test with outbound holding cell amount > 0
2068         {
2069                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2070                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2071                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2072                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2073                 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);
2074         }
2075
2076         let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2077         // this will also stuck in the holding cell
2078         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2079         check_added_monitors!(nodes[0], 0);
2080         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2081         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2082
2083         // flush the pending htlc
2084         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2085         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2086         check_added_monitors!(nodes[1], 1);
2087
2088         // the pending htlc should be promoted to committed
2089         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2090         check_added_monitors!(nodes[0], 1);
2091         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2092
2093         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2094         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2095         // No commitment_signed so get_event_msg's assert(len == 1) passes
2096         check_added_monitors!(nodes[0], 1);
2097
2098         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2099         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2100         check_added_monitors!(nodes[1], 1);
2101
2102         expect_pending_htlcs_forwardable!(nodes[1]);
2103
2104         let ref payment_event_11 = expect_forward!(nodes[1]);
2105         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2106         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2107
2108         expect_pending_htlcs_forwardable!(nodes[2]);
2109         expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2110
2111         // flush the htlcs in the holding cell
2112         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2113         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2114         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2115         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2116         expect_pending_htlcs_forwardable!(nodes[1]);
2117
2118         let ref payment_event_3 = expect_forward!(nodes[1]);
2119         assert_eq!(payment_event_3.msgs.len(), 2);
2120         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2121         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2122
2123         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2124         expect_pending_htlcs_forwardable!(nodes[2]);
2125
2126         let events = nodes[2].node.get_and_clear_pending_events();
2127         assert_eq!(events.len(), 2);
2128         match events[0] {
2129                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2130                         assert_eq!(our_payment_hash_21, *payment_hash);
2131                         assert_eq!(*payment_secret, None);
2132                         assert_eq!(recv_value_21, amt);
2133                 },
2134                 _ => panic!("Unexpected event"),
2135         }
2136         match events[1] {
2137                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2138                         assert_eq!(our_payment_hash_22, *payment_hash);
2139                         assert_eq!(None, *payment_secret);
2140                         assert_eq!(recv_value_22, amt);
2141                 },
2142                 _ => panic!("Unexpected event"),
2143         }
2144
2145         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2146         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2147         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2148
2149         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2150         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2151         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2152
2153         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2154         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);
2155         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2156         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2157         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2158
2159         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2160         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2161 }
2162
2163 #[test]
2164 fn channel_reserve_in_flight_removes() {
2165         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2166         // can send to its counterparty, but due to update ordering, the other side may not yet have
2167         // considered those HTLCs fully removed.
2168         // This tests that we don't count HTLCs which will not be included in the next remote
2169         // commitment transaction towards the reserve value (as it implies no commitment transaction
2170         // will be generated which violates the remote reserve value).
2171         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2172         // To test this we:
2173         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2174         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2175         //    you only consider the value of the first HTLC, it may not),
2176         //  * start routing a third HTLC from A to B,
2177         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2178         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2179         //  * deliver the first fulfill from B
2180         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2181         //    claim,
2182         //  * deliver A's response CS and RAA.
2183         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2184         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2185         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2186         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2187         let chanmon_cfgs = create_chanmon_cfgs(2);
2188         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2189         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2190         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2191         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2192         let logger = test_utils::TestLogger::new();
2193
2194         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2195         // Route the first two HTLCs.
2196         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2197         let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2198
2199         // Start routing the third HTLC (this is just used to get everyone in the right state).
2200         let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2201         let send_1 = {
2202                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2203                 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();
2204                 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2205                 check_added_monitors!(nodes[0], 1);
2206                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2207                 assert_eq!(events.len(), 1);
2208                 SendEvent::from_event(events.remove(0))
2209         };
2210
2211         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2212         // initial fulfill/CS.
2213         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2214         check_added_monitors!(nodes[1], 1);
2215         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2216
2217         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2218         // remove the second HTLC when we send the HTLC back from B to A.
2219         assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2220         check_added_monitors!(nodes[1], 1);
2221         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2222
2223         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2224         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2225         check_added_monitors!(nodes[0], 1);
2226         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2227         expect_payment_sent!(nodes[0], payment_preimage_1);
2228
2229         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2230         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2231         check_added_monitors!(nodes[1], 1);
2232         // B is already AwaitingRAA, so cant generate a CS here
2233         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2234
2235         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2236         check_added_monitors!(nodes[1], 1);
2237         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2238
2239         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2240         check_added_monitors!(nodes[0], 1);
2241         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2242
2243         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2244         check_added_monitors!(nodes[1], 1);
2245         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2246
2247         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2248         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2249         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2250         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2251         // on-chain as necessary).
2252         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2253         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2254         check_added_monitors!(nodes[0], 1);
2255         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2256         expect_payment_sent!(nodes[0], payment_preimage_2);
2257
2258         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2259         check_added_monitors!(nodes[1], 1);
2260         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2261
2262         expect_pending_htlcs_forwardable!(nodes[1]);
2263         expect_payment_received!(nodes[1], payment_hash_3, 100000);
2264
2265         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2266         // resolve the second HTLC from A's point of view.
2267         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2268         check_added_monitors!(nodes[0], 1);
2269         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2270
2271         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2272         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2273         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2274         let send_2 = {
2275                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2276                 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();
2277                 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2278                 check_added_monitors!(nodes[1], 1);
2279                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2280                 assert_eq!(events.len(), 1);
2281                 SendEvent::from_event(events.remove(0))
2282         };
2283
2284         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2285         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2286         check_added_monitors!(nodes[0], 1);
2287         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2288
2289         // Now just resolve all the outstanding messages/HTLCs for completeness...
2290
2291         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2292         check_added_monitors!(nodes[1], 1);
2293         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2294
2295         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2296         check_added_monitors!(nodes[1], 1);
2297
2298         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2299         check_added_monitors!(nodes[0], 1);
2300         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2301
2302         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2303         check_added_monitors!(nodes[1], 1);
2304         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2305
2306         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2307         check_added_monitors!(nodes[0], 1);
2308
2309         expect_pending_htlcs_forwardable!(nodes[0]);
2310         expect_payment_received!(nodes[0], payment_hash_4, 10000);
2311
2312         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2313         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2314 }
2315
2316 #[test]
2317 fn channel_monitor_network_test() {
2318         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2319         // tests that ChannelMonitor is able to recover from various states.
2320         let chanmon_cfgs = create_chanmon_cfgs(5);
2321         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2322         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2323         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2324
2325         // Create some initial channels
2326         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2327         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2328         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2329         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2330
2331         // Make sure all nodes are at the same starting height
2332         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2333         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2334         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2335         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2336         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2337
2338         // Rebalance the network a bit by relaying one payment through all the channels...
2339         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2340         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2341         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2342         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2343
2344         // Simple case with no pending HTLCs:
2345         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2346         check_added_monitors!(nodes[1], 1);
2347         check_closed_broadcast!(nodes[1], false);
2348         {
2349                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2350                 assert_eq!(node_txn.len(), 1);
2351                 mine_transaction(&nodes[0], &node_txn[0]);
2352                 check_added_monitors!(nodes[0], 1);
2353                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2354         }
2355         check_closed_broadcast!(nodes[0], true);
2356         assert_eq!(nodes[0].node.list_channels().len(), 0);
2357         assert_eq!(nodes[1].node.list_channels().len(), 1);
2358
2359         // One pending HTLC is discarded by the force-close:
2360         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2361
2362         // Simple case of one pending HTLC to HTLC-Timeout
2363         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2364         check_closed_broadcast!(nodes[1], false);
2365         check_added_monitors!(nodes[1], 1);
2366         {
2367                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2368                 mine_transaction(&nodes[2], &node_txn[0]);
2369                 check_added_monitors!(nodes[2], 1);
2370                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2371         }
2372         check_closed_broadcast!(nodes[2], true);
2373         assert_eq!(nodes[1].node.list_channels().len(), 0);
2374         assert_eq!(nodes[2].node.list_channels().len(), 1);
2375
2376         macro_rules! claim_funds {
2377                 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2378                         {
2379                                 assert!($node.node.claim_funds($preimage, &None, $amount));
2380                                 check_added_monitors!($node, 1);
2381
2382                                 let events = $node.node.get_and_clear_pending_msg_events();
2383                                 assert_eq!(events.len(), 1);
2384                                 match events[0] {
2385                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2386                                                 assert!(update_add_htlcs.is_empty());
2387                                                 assert!(update_fail_htlcs.is_empty());
2388                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2389                                         },
2390                                         _ => panic!("Unexpected event"),
2391                                 };
2392                         }
2393                 }
2394         }
2395
2396         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2397         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2398         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2399         check_added_monitors!(nodes[2], 1);
2400         check_closed_broadcast!(nodes[2], false);
2401         let node2_commitment_txid;
2402         {
2403                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2404                 node2_commitment_txid = node_txn[0].txid();
2405
2406                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2407                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2408                 mine_transaction(&nodes[3], &node_txn[0]);
2409                 check_added_monitors!(nodes[3], 1);
2410                 check_preimage_claim(&nodes[3], &node_txn);
2411         }
2412         check_closed_broadcast!(nodes[3], true);
2413         assert_eq!(nodes[2].node.list_channels().len(), 0);
2414         assert_eq!(nodes[3].node.list_channels().len(), 1);
2415
2416         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2417         // confusing us in the following tests.
2418         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().remove(&OutPoint { txid: chan_3.3.txid(), index: 0 }).unwrap();
2419
2420         // One pending HTLC to time out:
2421         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2422         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2423         // buffer space).
2424
2425         let (close_chan_update_1, close_chan_update_2) = {
2426                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2427                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2428                 assert_eq!(events.len(), 2);
2429                 let close_chan_update_1 = match events[0] {
2430                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2431                                 msg.clone()
2432                         },
2433                         _ => panic!("Unexpected event"),
2434                 };
2435                 match events[1] {
2436                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2437                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2438                         },
2439                         _ => panic!("Unexpected event"),
2440                 }
2441                 check_added_monitors!(nodes[3], 1);
2442
2443                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2444                 {
2445                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2446                         node_txn.retain(|tx| {
2447                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2448                                         false
2449                                 } else { true }
2450                         });
2451                 }
2452
2453                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2454
2455                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2456                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2457
2458                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2459                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2460                 assert_eq!(events.len(), 2);
2461                 let close_chan_update_2 = match events[0] {
2462                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2463                                 msg.clone()
2464                         },
2465                         _ => panic!("Unexpected event"),
2466                 };
2467                 match events[1] {
2468                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2469                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2470                         },
2471                         _ => panic!("Unexpected event"),
2472                 }
2473                 check_added_monitors!(nodes[4], 1);
2474                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2475
2476                 mine_transaction(&nodes[4], &node_txn[0]);
2477                 check_preimage_claim(&nodes[4], &node_txn);
2478                 (close_chan_update_1, close_chan_update_2)
2479         };
2480         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2481         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2482         assert_eq!(nodes[3].node.list_channels().len(), 0);
2483         assert_eq!(nodes[4].node.list_channels().len(), 0);
2484
2485         nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().insert(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon);
2486 }
2487
2488 #[test]
2489 fn test_justice_tx() {
2490         // Test justice txn built on revoked HTLC-Success tx, against both sides
2491         let mut alice_config = UserConfig::default();
2492         alice_config.channel_options.announced_channel = true;
2493         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2494         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2495         let mut bob_config = UserConfig::default();
2496         bob_config.channel_options.announced_channel = true;
2497         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2498         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2499         let user_cfgs = [Some(alice_config), Some(bob_config)];
2500         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2501         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2502         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2503         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2504         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2505         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2506         // Create some new channels:
2507         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2508
2509         // A pending HTLC which will be revoked:
2510         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2511         // Get the will-be-revoked local txn from nodes[0]
2512         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2513         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2514         assert_eq!(revoked_local_txn[0].input.len(), 1);
2515         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2516         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2517         assert_eq!(revoked_local_txn[1].input.len(), 1);
2518         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2519         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2520         // Revoke the old state
2521         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2522
2523         {
2524                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2525                 {
2526                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2527                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2528                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2529
2530                         check_spends!(node_txn[0], revoked_local_txn[0]);
2531                         node_txn.swap_remove(0);
2532                         node_txn.truncate(1);
2533                 }
2534                 check_added_monitors!(nodes[1], 1);
2535                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2536
2537                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2538                 // Verify broadcast of revoked HTLC-timeout
2539                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2540                 check_added_monitors!(nodes[0], 1);
2541                 // Broadcast revoked HTLC-timeout on node 1
2542                 mine_transaction(&nodes[1], &node_txn[1]);
2543                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2544         }
2545         get_announce_close_broadcast_events(&nodes, 0, 1);
2546
2547         assert_eq!(nodes[0].node.list_channels().len(), 0);
2548         assert_eq!(nodes[1].node.list_channels().len(), 0);
2549
2550         // We test justice_tx build by A on B's revoked HTLC-Success tx
2551         // Create some new channels:
2552         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2553         {
2554                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2555                 node_txn.clear();
2556         }
2557
2558         // A pending HTLC which will be revoked:
2559         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2560         // Get the will-be-revoked local txn from B
2561         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2562         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2563         assert_eq!(revoked_local_txn[0].input.len(), 1);
2564         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2565         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2566         // Revoke the old state
2567         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2568         {
2569                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2570                 {
2571                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2572                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2573                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2574
2575                         check_spends!(node_txn[0], revoked_local_txn[0]);
2576                         node_txn.swap_remove(0);
2577                 }
2578                 check_added_monitors!(nodes[0], 1);
2579                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2580
2581                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2582                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2583                 check_added_monitors!(nodes[1], 1);
2584                 mine_transaction(&nodes[0], &node_txn[1]);
2585                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2586         }
2587         get_announce_close_broadcast_events(&nodes, 0, 1);
2588         assert_eq!(nodes[0].node.list_channels().len(), 0);
2589         assert_eq!(nodes[1].node.list_channels().len(), 0);
2590 }
2591
2592 #[test]
2593 fn revoked_output_claim() {
2594         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2595         // transaction is broadcast by its counterparty
2596         let chanmon_cfgs = create_chanmon_cfgs(2);
2597         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2598         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2599         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2600         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2601         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2602         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2603         assert_eq!(revoked_local_txn.len(), 1);
2604         // Only output is the full channel value back to nodes[0]:
2605         assert_eq!(revoked_local_txn[0].output.len(), 1);
2606         // Send a payment through, updating everyone's latest commitment txn
2607         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2608
2609         // Inform nodes[1] that nodes[0] broadcast a stale tx
2610         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2611         check_added_monitors!(nodes[1], 1);
2612         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2613         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2614
2615         check_spends!(node_txn[0], revoked_local_txn[0]);
2616         check_spends!(node_txn[1], chan_1.3);
2617
2618         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2619         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2620         get_announce_close_broadcast_events(&nodes, 0, 1);
2621         check_added_monitors!(nodes[0], 1)
2622 }
2623
2624 #[test]
2625 fn claim_htlc_outputs_shared_tx() {
2626         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2627         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2628         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2629         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2630         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2631         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2632
2633         // Create some new channel:
2634         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2635
2636         // Rebalance the network to generate htlc in the two directions
2637         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2638         // 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
2639         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2640         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2641
2642         // Get the will-be-revoked local txn from node[0]
2643         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2644         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2645         assert_eq!(revoked_local_txn[0].input.len(), 1);
2646         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2647         assert_eq!(revoked_local_txn[1].input.len(), 1);
2648         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2649         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2650         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2651
2652         //Revoke the old state
2653         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2654
2655         {
2656                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2657                 check_added_monitors!(nodes[0], 1);
2658                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2659                 check_added_monitors!(nodes[1], 1);
2660                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2661                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2662
2663                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2664                 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2665
2666                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2667                 check_spends!(node_txn[0], revoked_local_txn[0]);
2668
2669                 let mut witness_lens = BTreeSet::new();
2670                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2671                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2672                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2673                 assert_eq!(witness_lens.len(), 3);
2674                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2675                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2676                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2677
2678                 // Next nodes[1] broadcasts its current local tx state:
2679                 assert_eq!(node_txn[1].input.len(), 1);
2680                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2681
2682                 assert_eq!(node_txn[2].input.len(), 1);
2683                 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2684                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2685                 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2686                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2687                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2688         }
2689         get_announce_close_broadcast_events(&nodes, 0, 1);
2690         assert_eq!(nodes[0].node.list_channels().len(), 0);
2691         assert_eq!(nodes[1].node.list_channels().len(), 0);
2692 }
2693
2694 #[test]
2695 fn claim_htlc_outputs_single_tx() {
2696         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2697         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2698         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2699         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2700         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2701         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2702
2703         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2704
2705         // Rebalance the network to generate htlc in the two directions
2706         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2707         // 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
2708         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2709         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2710         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2711
2712         // Get the will-be-revoked local txn from node[0]
2713         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2714
2715         //Revoke the old state
2716         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2717
2718         {
2719                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2720                 check_added_monitors!(nodes[0], 1);
2721                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2722                 check_added_monitors!(nodes[1], 1);
2723                 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2724
2725                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2726                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2727
2728                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2729                 assert_eq!(node_txn.len(), 9);
2730                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2731                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2732                 // 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)
2733                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2734
2735                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2736                 assert_eq!(node_txn[0].input.len(), 1);
2737                 check_spends!(node_txn[0], chan_1.3);
2738                 assert_eq!(node_txn[1].input.len(), 1);
2739                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2740                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2741                 check_spends!(node_txn[1], node_txn[0]);
2742
2743                 // Justice transactions are indices 1-2-4
2744                 assert_eq!(node_txn[2].input.len(), 1);
2745                 assert_eq!(node_txn[3].input.len(), 1);
2746                 assert_eq!(node_txn[4].input.len(), 1);
2747
2748                 check_spends!(node_txn[2], revoked_local_txn[0]);
2749                 check_spends!(node_txn[3], revoked_local_txn[0]);
2750                 check_spends!(node_txn[4], revoked_local_txn[0]);
2751
2752                 let mut witness_lens = BTreeSet::new();
2753                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2754                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2755                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2756                 assert_eq!(witness_lens.len(), 3);
2757                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2758                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2759                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2760         }
2761         get_announce_close_broadcast_events(&nodes, 0, 1);
2762         assert_eq!(nodes[0].node.list_channels().len(), 0);
2763         assert_eq!(nodes[1].node.list_channels().len(), 0);
2764 }
2765
2766 #[test]
2767 fn test_htlc_on_chain_success() {
2768         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2769         // the preimage backward accordingly. So here we test that ChannelManager is
2770         // broadcasting the right event to other nodes in payment path.
2771         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2772         // A --------------------> B ----------------------> C (preimage)
2773         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2774         // commitment transaction was broadcast.
2775         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2776         // towards B.
2777         // B should be able to claim via preimage if A then broadcasts its local tx.
2778         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2779         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2780         // PaymentSent event).
2781
2782         let chanmon_cfgs = create_chanmon_cfgs(3);
2783         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2784         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2785         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2786
2787         // Create some initial channels
2788         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2789         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2790
2791         // Rebalance the network a bit by relaying one payment through all the channels...
2792         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2793         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2794
2795         let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2796         let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2797
2798         // Broadcast legit commitment tx from C on B's chain
2799         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2800         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2801         assert_eq!(commitment_tx.len(), 1);
2802         check_spends!(commitment_tx[0], chan_2.3);
2803         nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2804         nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2805         check_added_monitors!(nodes[2], 2);
2806         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2807         assert!(updates.update_add_htlcs.is_empty());
2808         assert!(updates.update_fail_htlcs.is_empty());
2809         assert!(updates.update_fail_malformed_htlcs.is_empty());
2810         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2811
2812         mine_transaction(&nodes[2], &commitment_tx[0]);
2813         check_closed_broadcast!(nodes[2], true);
2814         check_added_monitors!(nodes[2], 1);
2815         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)
2816         assert_eq!(node_txn.len(), 5);
2817         assert_eq!(node_txn[0], node_txn[3]);
2818         assert_eq!(node_txn[1], node_txn[4]);
2819         assert_eq!(node_txn[2], commitment_tx[0]);
2820         check_spends!(node_txn[0], commitment_tx[0]);
2821         check_spends!(node_txn[1], commitment_tx[0]);
2822         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2823         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2824         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2825         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2826         assert_eq!(node_txn[0].lock_time, 0);
2827         assert_eq!(node_txn[1].lock_time, 0);
2828
2829         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2830         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2831         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2832         {
2833                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2834                 assert_eq!(added_monitors.len(), 1);
2835                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2836                 added_monitors.clear();
2837         }
2838         let events = nodes[1].node.get_and_clear_pending_msg_events();
2839         {
2840                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2841                 assert_eq!(added_monitors.len(), 2);
2842                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2843                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2844                 added_monitors.clear();
2845         }
2846         assert_eq!(events.len(), 3);
2847         match events[0] {
2848                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2849                 _ => panic!("Unexpected event"),
2850         }
2851         match events[1] {
2852                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2853                 _ => panic!("Unexpected event"),
2854         }
2855
2856         match events[2] {
2857                 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, .. } } => {
2858                         assert!(update_add_htlcs.is_empty());
2859                         assert!(update_fail_htlcs.is_empty());
2860                         assert_eq!(update_fulfill_htlcs.len(), 1);
2861                         assert!(update_fail_malformed_htlcs.is_empty());
2862                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2863                 },
2864                 _ => panic!("Unexpected event"),
2865         };
2866         macro_rules! check_tx_local_broadcast {
2867                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2868                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2869                         assert_eq!(node_txn.len(), 5);
2870                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2871                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2872                         check_spends!(node_txn[0], $commitment_tx);
2873                         check_spends!(node_txn[1], $commitment_tx);
2874                         assert_ne!(node_txn[0].lock_time, 0);
2875                         assert_ne!(node_txn[1].lock_time, 0);
2876                         if $htlc_offered {
2877                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2878                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2879                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2880                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2881                         } else {
2882                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2883                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2884                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2885                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2886                         }
2887                         check_spends!(node_txn[2], $chan_tx);
2888                         check_spends!(node_txn[3], node_txn[2]);
2889                         check_spends!(node_txn[4], node_txn[2]);
2890                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2891                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2892                         assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2893                         assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2894                         assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2895                         assert_ne!(node_txn[3].lock_time, 0);
2896                         assert_ne!(node_txn[4].lock_time, 0);
2897                         node_txn.clear();
2898                 } }
2899         }
2900         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2901         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2902         // timeout-claim of the output that nodes[2] just claimed via success.
2903         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2904
2905         // Broadcast legit commitment tx from A on B's chain
2906         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2907         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2908         check_spends!(commitment_tx[0], chan_1.3);
2909         mine_transaction(&nodes[1], &commitment_tx[0]);
2910         check_closed_broadcast!(nodes[1], true);
2911         check_added_monitors!(nodes[1], 1);
2912         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2913         assert_eq!(node_txn.len(), 4);
2914         check_spends!(node_txn[0], commitment_tx[0]);
2915         assert_eq!(node_txn[0].input.len(), 2);
2916         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2917         assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2918         assert_eq!(node_txn[0].lock_time, 0);
2919         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2920         check_spends!(node_txn[1], chan_1.3);
2921         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2922         check_spends!(node_txn[2], node_txn[1]);
2923         check_spends!(node_txn[3], node_txn[1]);
2924         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2925         // we already checked the same situation with A.
2926
2927         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2928         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2929         connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] });
2930         check_closed_broadcast!(nodes[0], true);
2931         check_added_monitors!(nodes[0], 1);
2932         let events = nodes[0].node.get_and_clear_pending_events();
2933         assert_eq!(events.len(), 2);
2934         let mut first_claimed = false;
2935         for event in events {
2936                 match event {
2937                         Event::PaymentSent { payment_preimage } => {
2938                                 if payment_preimage == our_payment_preimage {
2939                                         assert!(!first_claimed);
2940                                         first_claimed = true;
2941                                 } else {
2942                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2943                                 }
2944                         },
2945                         _ => panic!("Unexpected event"),
2946                 }
2947         }
2948         check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2949 }
2950
2951 #[test]
2952 fn test_htlc_on_chain_timeout() {
2953         // Test that in case of a unilateral close onchain, we detect the state of output and
2954         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2955         // broadcasting the right event to other nodes in payment path.
2956         // A ------------------> B ----------------------> C (timeout)
2957         //    B's commitment tx                 C's commitment tx
2958         //            \                                  \
2959         //         B's HTLC timeout tx               B's timeout tx
2960
2961         let chanmon_cfgs = create_chanmon_cfgs(3);
2962         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2963         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2964         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2965
2966         // Create some intial channels
2967         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2968         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2969
2970         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2971         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2972         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2973
2974         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2975
2976         // Broadcast legit commitment tx from C on B's chain
2977         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2978         check_spends!(commitment_tx[0], chan_2.3);
2979         nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2980         check_added_monitors!(nodes[2], 0);
2981         expect_pending_htlcs_forwardable!(nodes[2]);
2982         check_added_monitors!(nodes[2], 1);
2983
2984         let events = nodes[2].node.get_and_clear_pending_msg_events();
2985         assert_eq!(events.len(), 1);
2986         match events[0] {
2987                 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, .. } } => {
2988                         assert!(update_add_htlcs.is_empty());
2989                         assert!(!update_fail_htlcs.is_empty());
2990                         assert!(update_fulfill_htlcs.is_empty());
2991                         assert!(update_fail_malformed_htlcs.is_empty());
2992                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2993                 },
2994                 _ => panic!("Unexpected event"),
2995         };
2996         mine_transaction(&nodes[2], &commitment_tx[0]);
2997         check_closed_broadcast!(nodes[2], true);
2998         check_added_monitors!(nodes[2], 1);
2999         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
3000         assert_eq!(node_txn.len(), 1);
3001         check_spends!(node_txn[0], chan_2.3);
3002         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
3003
3004         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3005         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3006         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3007         mine_transaction(&nodes[1], &commitment_tx[0]);
3008         let timeout_tx;
3009         {
3010                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3011                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
3012                 assert_eq!(node_txn[0], node_txn[3]);
3013                 assert_eq!(node_txn[1], node_txn[4]);
3014
3015                 check_spends!(node_txn[2], commitment_tx[0]);
3016                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3017
3018                 check_spends!(node_txn[0], chan_2.3);
3019                 check_spends!(node_txn[1], node_txn[0]);
3020                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3021                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3022
3023                 timeout_tx = node_txn[2].clone();
3024                 node_txn.clear();
3025         }
3026
3027         mine_transaction(&nodes[1], &timeout_tx);
3028         check_added_monitors!(nodes[1], 1);
3029         check_closed_broadcast!(nodes[1], true);
3030         {
3031                 // B will rebroadcast a fee-bumped timeout transaction here.
3032                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3033                 assert_eq!(node_txn.len(), 1);
3034                 check_spends!(node_txn[0], commitment_tx[0]);
3035         }
3036
3037         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3038         {
3039                 // B will rebroadcast its own holder commitment transaction here...just because
3040                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3041                 assert_eq!(node_txn.len(), 1);
3042                 check_spends!(node_txn[0], chan_2.3);
3043         }
3044
3045         expect_pending_htlcs_forwardable!(nodes[1]);
3046         check_added_monitors!(nodes[1], 1);
3047         let events = nodes[1].node.get_and_clear_pending_msg_events();
3048         assert_eq!(events.len(), 1);
3049         match events[0] {
3050                 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, .. } } => {
3051                         assert!(update_add_htlcs.is_empty());
3052                         assert!(!update_fail_htlcs.is_empty());
3053                         assert!(update_fulfill_htlcs.is_empty());
3054                         assert!(update_fail_malformed_htlcs.is_empty());
3055                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3056                 },
3057                 _ => panic!("Unexpected event"),
3058         };
3059
3060         // Broadcast legit commitment tx from B on A's chain
3061         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3062         check_spends!(commitment_tx[0], chan_1.3);
3063
3064         mine_transaction(&nodes[0], &commitment_tx[0]);
3065
3066         check_closed_broadcast!(nodes[0], true);
3067         check_added_monitors!(nodes[0], 1);
3068         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3069         assert_eq!(node_txn.len(), 3);
3070         check_spends!(node_txn[0], commitment_tx[0]);
3071         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3072         check_spends!(node_txn[1], chan_1.3);
3073         check_spends!(node_txn[2], node_txn[1]);
3074         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3075         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3076 }
3077
3078 #[test]
3079 fn test_simple_commitment_revoked_fail_backward() {
3080         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3081         // and fail backward accordingly.
3082
3083         let chanmon_cfgs = create_chanmon_cfgs(3);
3084         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3085         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3086         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3087
3088         // Create some initial channels
3089         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3090         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3091
3092         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3093         // Get the will-be-revoked local txn from nodes[2]
3094         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3095         // Revoke the old state
3096         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3097
3098         let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3099
3100         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3101         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3102         check_added_monitors!(nodes[1], 1);
3103         check_closed_broadcast!(nodes[1], true);
3104
3105         expect_pending_htlcs_forwardable!(nodes[1]);
3106         check_added_monitors!(nodes[1], 1);
3107         let events = nodes[1].node.get_and_clear_pending_msg_events();
3108         assert_eq!(events.len(), 1);
3109         match events[0] {
3110                 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, .. } } => {
3111                         assert!(update_add_htlcs.is_empty());
3112                         assert_eq!(update_fail_htlcs.len(), 1);
3113                         assert!(update_fulfill_htlcs.is_empty());
3114                         assert!(update_fail_malformed_htlcs.is_empty());
3115                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3116
3117                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3118                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3119
3120                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3121                         assert_eq!(events.len(), 1);
3122                         match events[0] {
3123                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3124                                 _ => panic!("Unexpected event"),
3125                         }
3126                         expect_payment_failed!(nodes[0], payment_hash, false);
3127                 },
3128                 _ => panic!("Unexpected event"),
3129         }
3130 }
3131
3132 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3133         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3134         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3135         // commitment transaction anymore.
3136         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3137         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3138         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3139         // technically disallowed and we should probably handle it reasonably.
3140         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3141         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3142         // transactions:
3143         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3144         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3145         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3146         //   and once they revoke the previous commitment transaction (allowing us to send a new
3147         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3148         let chanmon_cfgs = create_chanmon_cfgs(3);
3149         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3150         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3151         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3152
3153         // Create some initial channels
3154         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3155         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3156
3157         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3158         // Get the will-be-revoked local txn from nodes[2]
3159         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3160         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3161         // Revoke the old state
3162         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3163
3164         let value = if use_dust {
3165                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3166                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3167                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3168         } else { 3000000 };
3169
3170         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3171         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3172         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3173
3174         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3175         expect_pending_htlcs_forwardable!(nodes[2]);
3176         check_added_monitors!(nodes[2], 1);
3177         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3178         assert!(updates.update_add_htlcs.is_empty());
3179         assert!(updates.update_fulfill_htlcs.is_empty());
3180         assert!(updates.update_fail_malformed_htlcs.is_empty());
3181         assert_eq!(updates.update_fail_htlcs.len(), 1);
3182         assert!(updates.update_fee.is_none());
3183         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3184         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3185         // Drop the last RAA from 3 -> 2
3186
3187         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3188         expect_pending_htlcs_forwardable!(nodes[2]);
3189         check_added_monitors!(nodes[2], 1);
3190         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3191         assert!(updates.update_add_htlcs.is_empty());
3192         assert!(updates.update_fulfill_htlcs.is_empty());
3193         assert!(updates.update_fail_malformed_htlcs.is_empty());
3194         assert_eq!(updates.update_fail_htlcs.len(), 1);
3195         assert!(updates.update_fee.is_none());
3196         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3197         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3198         check_added_monitors!(nodes[1], 1);
3199         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3200         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3201         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3202         check_added_monitors!(nodes[2], 1);
3203
3204         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3205         expect_pending_htlcs_forwardable!(nodes[2]);
3206         check_added_monitors!(nodes[2], 1);
3207         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3208         assert!(updates.update_add_htlcs.is_empty());
3209         assert!(updates.update_fulfill_htlcs.is_empty());
3210         assert!(updates.update_fail_malformed_htlcs.is_empty());
3211         assert_eq!(updates.update_fail_htlcs.len(), 1);
3212         assert!(updates.update_fee.is_none());
3213         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3214         // At this point first_payment_hash has dropped out of the latest two commitment
3215         // transactions that nodes[1] is tracking...
3216         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3217         check_added_monitors!(nodes[1], 1);
3218         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3219         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3220         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3221         check_added_monitors!(nodes[2], 1);
3222
3223         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3224         // on nodes[2]'s RAA.
3225         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3226         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3227         let logger = test_utils::TestLogger::new();
3228         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();
3229         nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3230         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3231         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3232         check_added_monitors!(nodes[1], 0);
3233
3234         if deliver_bs_raa {
3235                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3236                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3237                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3238                 check_added_monitors!(nodes[1], 1);
3239                 let events = nodes[1].node.get_and_clear_pending_events();
3240                 assert_eq!(events.len(), 1);
3241                 match events[0] {
3242                         Event::PendingHTLCsForwardable { .. } => { },
3243                         _ => panic!("Unexpected event"),
3244                 };
3245                 // Deliberately don't process the pending fail-back so they all fail back at once after
3246                 // block connection just like the !deliver_bs_raa case
3247         }
3248
3249         let mut failed_htlcs = HashSet::new();
3250         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3251
3252         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3253         check_added_monitors!(nodes[1], 1);
3254         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3255
3256         let events = nodes[1].node.get_and_clear_pending_events();
3257         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3258         match events[0] {
3259                 Event::PaymentFailed { ref payment_hash, .. } => {
3260                         assert_eq!(*payment_hash, fourth_payment_hash);
3261                 },
3262                 _ => panic!("Unexpected event"),
3263         }
3264         if !deliver_bs_raa {
3265                 match events[1] {
3266                         Event::PendingHTLCsForwardable { .. } => { },
3267                         _ => panic!("Unexpected event"),
3268                 };
3269         }
3270         nodes[1].node.process_pending_htlc_forwards();
3271         check_added_monitors!(nodes[1], 1);
3272
3273         let events = nodes[1].node.get_and_clear_pending_msg_events();
3274         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3275         match events[if deliver_bs_raa { 1 } else { 0 }] {
3276                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3277                 _ => panic!("Unexpected event"),
3278         }
3279         match events[if deliver_bs_raa { 2 } else { 1 }] {
3280                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3281                         assert_eq!(channel_id, chan_2.2);
3282                         assert_eq!(data.as_str(), "Commitment or closing transaction was confirmed on chain.");
3283                 },
3284                 _ => panic!("Unexpected event"),
3285         }
3286         if deliver_bs_raa {
3287                 match events[0] {
3288                         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, .. } } => {
3289                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3290                                 assert_eq!(update_add_htlcs.len(), 1);
3291                                 assert!(update_fulfill_htlcs.is_empty());
3292                                 assert!(update_fail_htlcs.is_empty());
3293                                 assert!(update_fail_malformed_htlcs.is_empty());
3294                         },
3295                         _ => panic!("Unexpected event"),
3296                 }
3297         }
3298         match events[if deliver_bs_raa { 3 } else { 2 }] {
3299                 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, .. } } => {
3300                         assert!(update_add_htlcs.is_empty());
3301                         assert_eq!(update_fail_htlcs.len(), 3);
3302                         assert!(update_fulfill_htlcs.is_empty());
3303                         assert!(update_fail_malformed_htlcs.is_empty());
3304                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3305
3306                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3307                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3308                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3309
3310                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3311
3312                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3313                         // If we delivered B's RAA we got an unknown preimage error, not something
3314                         // that we should update our routing table for.
3315                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3316                         for event in events {
3317                                 match event {
3318                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3319                                         _ => panic!("Unexpected event"),
3320                                 }
3321                         }
3322                         let events = nodes[0].node.get_and_clear_pending_events();
3323                         assert_eq!(events.len(), 3);
3324                         match events[0] {
3325                                 Event::PaymentFailed { ref payment_hash, .. } => {
3326                                         assert!(failed_htlcs.insert(payment_hash.0));
3327                                 },
3328                                 _ => panic!("Unexpected event"),
3329                         }
3330                         match events[1] {
3331                                 Event::PaymentFailed { ref payment_hash, .. } => {
3332                                         assert!(failed_htlcs.insert(payment_hash.0));
3333                                 },
3334                                 _ => panic!("Unexpected event"),
3335                         }
3336                         match events[2] {
3337                                 Event::PaymentFailed { ref payment_hash, .. } => {
3338                                         assert!(failed_htlcs.insert(payment_hash.0));
3339                                 },
3340                                 _ => panic!("Unexpected event"),
3341                         }
3342                 },
3343                 _ => panic!("Unexpected event"),
3344         }
3345
3346         assert!(failed_htlcs.contains(&first_payment_hash.0));
3347         assert!(failed_htlcs.contains(&second_payment_hash.0));
3348         assert!(failed_htlcs.contains(&third_payment_hash.0));
3349 }
3350
3351 #[test]
3352 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3353         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3354         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3355         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3356         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3357 }
3358
3359 #[test]
3360 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3361         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3362         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3363         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3364         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3365 }
3366
3367 #[test]
3368 fn fail_backward_pending_htlc_upon_channel_failure() {
3369         let chanmon_cfgs = create_chanmon_cfgs(2);
3370         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3371         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3372         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3373         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3374         let logger = test_utils::TestLogger::new();
3375
3376         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3377         {
3378                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3379                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3380                 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();
3381                 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3382                 check_added_monitors!(nodes[0], 1);
3383
3384                 let payment_event = {
3385                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3386                         assert_eq!(events.len(), 1);
3387                         SendEvent::from_event(events.remove(0))
3388                 };
3389                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3390                 assert_eq!(payment_event.msgs.len(), 1);
3391         }
3392
3393         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3394         let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3395         {
3396                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3397                 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();
3398                 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3399                 check_added_monitors!(nodes[0], 0);
3400
3401                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3402         }
3403
3404         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3405         {
3406                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3407
3408                 let secp_ctx = Secp256k1::new();
3409                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3410                 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3411                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3412                 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();
3413                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3414                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3415                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3416
3417                 // Send a 0-msat update_add_htlc to fail the channel.
3418                 let update_add_htlc = msgs::UpdateAddHTLC {
3419                         channel_id: chan.2,
3420                         htlc_id: 0,
3421                         amount_msat: 0,
3422                         payment_hash,
3423                         cltv_expiry,
3424                         onion_routing_packet,
3425                 };
3426                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3427         }
3428
3429         // Check that Alice fails backward the pending HTLC from the second payment.
3430         expect_payment_failed!(nodes[0], failed_payment_hash, true);
3431         check_closed_broadcast!(nodes[0], true);
3432         check_added_monitors!(nodes[0], 1);
3433 }
3434
3435 #[test]
3436 fn test_htlc_ignore_latest_remote_commitment() {
3437         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3438         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3439         let chanmon_cfgs = create_chanmon_cfgs(2);
3440         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3441         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3442         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3443         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3444
3445         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3446         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3447         check_closed_broadcast!(nodes[0], true);
3448         check_added_monitors!(nodes[0], 1);
3449
3450         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3451         assert_eq!(node_txn.len(), 2);
3452
3453         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3454         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3455         check_closed_broadcast!(nodes[1], true);
3456         check_added_monitors!(nodes[1], 1);
3457
3458         // Duplicate the connect_block call since this may happen due to other listeners
3459         // registering new transactions
3460         header.prev_blockhash = header.block_hash();
3461         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3462 }
3463
3464 #[test]
3465 fn test_force_close_fail_back() {
3466         // Check which HTLCs are failed-backwards on channel force-closure
3467         let chanmon_cfgs = create_chanmon_cfgs(3);
3468         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3469         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3470         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3471         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3472         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3473         let logger = test_utils::TestLogger::new();
3474
3475         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3476
3477         let mut payment_event = {
3478                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3479                 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();
3480                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3481                 check_added_monitors!(nodes[0], 1);
3482
3483                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3484                 assert_eq!(events.len(), 1);
3485                 SendEvent::from_event(events.remove(0))
3486         };
3487
3488         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3489         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3490
3491         expect_pending_htlcs_forwardable!(nodes[1]);
3492
3493         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3494         assert_eq!(events_2.len(), 1);
3495         payment_event = SendEvent::from_event(events_2.remove(0));
3496         assert_eq!(payment_event.msgs.len(), 1);
3497
3498         check_added_monitors!(nodes[1], 1);
3499         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3500         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3501         check_added_monitors!(nodes[2], 1);
3502         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3503
3504         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3505         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3506         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3507
3508         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3509         check_closed_broadcast!(nodes[2], true);
3510         check_added_monitors!(nodes[2], 1);
3511         let tx = {
3512                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3513                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3514                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3515                 // back to nodes[1] upon timeout otherwise.
3516                 assert_eq!(node_txn.len(), 1);
3517                 node_txn.remove(0)
3518         };
3519
3520         mine_transaction(&nodes[1], &tx);
3521
3522         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3523         check_closed_broadcast!(nodes[1], true);
3524         check_added_monitors!(nodes[1], 1);
3525
3526         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3527         {
3528                 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3529                 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3530                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3531         }
3532         mine_transaction(&nodes[2], &tx);
3533         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3534         assert_eq!(node_txn.len(), 1);
3535         assert_eq!(node_txn[0].input.len(), 1);
3536         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3537         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3538         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3539
3540         check_spends!(node_txn[0], tx);
3541 }
3542
3543 #[test]
3544 fn test_simple_peer_disconnect() {
3545         // Test that we can reconnect when there are no lost messages
3546         let chanmon_cfgs = create_chanmon_cfgs(3);
3547         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3548         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3549         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3550         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3551         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3552
3553         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3554         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3555         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3556
3557         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3558         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3559         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3560         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3561
3562         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3563         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3564         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3565
3566         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3567         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3568         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3569         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3570
3571         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3572         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3573
3574         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3575         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3576
3577         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3578         {
3579                 let events = nodes[0].node.get_and_clear_pending_events();
3580                 assert_eq!(events.len(), 2);
3581                 match events[0] {
3582                         Event::PaymentSent { payment_preimage } => {
3583                                 assert_eq!(payment_preimage, payment_preimage_3);
3584                         },
3585                         _ => panic!("Unexpected event"),
3586                 }
3587                 match events[1] {
3588                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3589                                 assert_eq!(payment_hash, payment_hash_5);
3590                                 assert!(rejected_by_dest);
3591                         },
3592                         _ => panic!("Unexpected event"),
3593                 }
3594         }
3595
3596         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3597         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3598 }
3599
3600 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3601         // Test that we can reconnect when in-flight HTLC updates get dropped
3602         let chanmon_cfgs = create_chanmon_cfgs(2);
3603         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3604         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3605         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3606         if messages_delivered == 0 {
3607                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3608                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3609         } else {
3610                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3611         }
3612
3613         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3614
3615         let logger = test_utils::TestLogger::new();
3616         let payment_event = {
3617                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3618                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3619                         &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3620                         &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3621                 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3622                 check_added_monitors!(nodes[0], 1);
3623
3624                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3625                 assert_eq!(events.len(), 1);
3626                 SendEvent::from_event(events.remove(0))
3627         };
3628         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3629
3630         if messages_delivered < 2 {
3631                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3632         } else {
3633                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3634                 if messages_delivered >= 3 {
3635                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3636                         check_added_monitors!(nodes[1], 1);
3637                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3638
3639                         if messages_delivered >= 4 {
3640                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3641                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3642                                 check_added_monitors!(nodes[0], 1);
3643
3644                                 if messages_delivered >= 5 {
3645                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3646                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3647                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3648                                         check_added_monitors!(nodes[0], 1);
3649
3650                                         if messages_delivered >= 6 {
3651                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3652                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3653                                                 check_added_monitors!(nodes[1], 1);
3654                                         }
3655                                 }
3656                         }
3657                 }
3658         }
3659
3660         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3661         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3662         if messages_delivered < 3 {
3663                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3664                 // received on either side, both sides will need to resend them.
3665                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3666         } else if messages_delivered == 3 {
3667                 // nodes[0] still wants its RAA + commitment_signed
3668                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3669         } else if messages_delivered == 4 {
3670                 // nodes[0] still wants its commitment_signed
3671                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3672         } else if messages_delivered == 5 {
3673                 // nodes[1] still wants its final RAA
3674                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3675         } else if messages_delivered == 6 {
3676                 // Everything was delivered...
3677                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3678         }
3679
3680         let events_1 = nodes[1].node.get_and_clear_pending_events();
3681         assert_eq!(events_1.len(), 1);
3682         match events_1[0] {
3683                 Event::PendingHTLCsForwardable { .. } => { },
3684                 _ => panic!("Unexpected event"),
3685         };
3686
3687         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3688         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3689         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3690
3691         nodes[1].node.process_pending_htlc_forwards();
3692
3693         let events_2 = nodes[1].node.get_and_clear_pending_events();
3694         assert_eq!(events_2.len(), 1);
3695         match events_2[0] {
3696                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3697                         assert_eq!(payment_hash_1, *payment_hash);
3698                         assert_eq!(*payment_secret, None);
3699                         assert_eq!(amt, 1000000);
3700                 },
3701                 _ => panic!("Unexpected event"),
3702         }
3703
3704         nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3705         check_added_monitors!(nodes[1], 1);
3706
3707         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3708         assert_eq!(events_3.len(), 1);
3709         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3710                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3711                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3712                         assert!(updates.update_add_htlcs.is_empty());
3713                         assert!(updates.update_fail_htlcs.is_empty());
3714                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3715                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3716                         assert!(updates.update_fee.is_none());
3717                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3718                 },
3719                 _ => panic!("Unexpected event"),
3720         };
3721
3722         if messages_delivered >= 1 {
3723                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3724
3725                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3726                 assert_eq!(events_4.len(), 1);
3727                 match events_4[0] {
3728                         Event::PaymentSent { ref payment_preimage } => {
3729                                 assert_eq!(payment_preimage_1, *payment_preimage);
3730                         },
3731                         _ => panic!("Unexpected event"),
3732                 }
3733
3734                 if messages_delivered >= 2 {
3735                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3736                         check_added_monitors!(nodes[0], 1);
3737                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3738
3739                         if messages_delivered >= 3 {
3740                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3741                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3742                                 check_added_monitors!(nodes[1], 1);
3743
3744                                 if messages_delivered >= 4 {
3745                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3746                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3747                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3748                                         check_added_monitors!(nodes[1], 1);
3749
3750                                         if messages_delivered >= 5 {
3751                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3752                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3753                                                 check_added_monitors!(nodes[0], 1);
3754                                         }
3755                                 }
3756                         }
3757                 }
3758         }
3759
3760         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3761         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3762         if messages_delivered < 2 {
3763                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3764                 //TODO: Deduplicate PaymentSent events, then enable this if:
3765                 //if messages_delivered < 1 {
3766                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3767                         assert_eq!(events_4.len(), 1);
3768                         match events_4[0] {
3769                                 Event::PaymentSent { ref payment_preimage } => {
3770                                         assert_eq!(payment_preimage_1, *payment_preimage);
3771                                 },
3772                                 _ => panic!("Unexpected event"),
3773                         }
3774                 //}
3775         } else if messages_delivered == 2 {
3776                 // nodes[0] still wants its RAA + commitment_signed
3777                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3778         } else if messages_delivered == 3 {
3779                 // nodes[0] still wants its commitment_signed
3780                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3781         } else if messages_delivered == 4 {
3782                 // nodes[1] still wants its final RAA
3783                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3784         } else if messages_delivered == 5 {
3785                 // Everything was delivered...
3786                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3787         }
3788
3789         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3790         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3791         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3792
3793         // Channel should still work fine...
3794         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3795         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3796                 &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3797                 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3798         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3799         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3800 }
3801
3802 #[test]
3803 fn test_drop_messages_peer_disconnect_a() {
3804         do_test_drop_messages_peer_disconnect(0);
3805         do_test_drop_messages_peer_disconnect(1);
3806         do_test_drop_messages_peer_disconnect(2);
3807         do_test_drop_messages_peer_disconnect(3);
3808 }
3809
3810 #[test]
3811 fn test_drop_messages_peer_disconnect_b() {
3812         do_test_drop_messages_peer_disconnect(4);
3813         do_test_drop_messages_peer_disconnect(5);
3814         do_test_drop_messages_peer_disconnect(6);
3815 }
3816
3817 #[test]
3818 fn test_funding_peer_disconnect() {
3819         // Test that we can lock in our funding tx while disconnected
3820         let chanmon_cfgs = create_chanmon_cfgs(2);
3821         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3822         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3823         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3824         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3825
3826         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3827         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3828
3829         confirm_transaction(&nodes[0], &tx);
3830         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3831         assert_eq!(events_1.len(), 1);
3832         match events_1[0] {
3833                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3834                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3835                 },
3836                 _ => panic!("Unexpected event"),
3837         }
3838
3839         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3840
3841         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3842         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3843
3844         confirm_transaction(&nodes[1], &tx);
3845         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3846         assert_eq!(events_2.len(), 2);
3847         let funding_locked = match events_2[0] {
3848                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3849                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3850                         msg.clone()
3851                 },
3852                 _ => panic!("Unexpected event"),
3853         };
3854         let bs_announcement_sigs = match events_2[1] {
3855                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3856                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3857                         msg.clone()
3858                 },
3859                 _ => panic!("Unexpected event"),
3860         };
3861
3862         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3863
3864         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3865         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3866         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3867         assert_eq!(events_3.len(), 2);
3868         let as_announcement_sigs = match events_3[0] {
3869                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3870                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3871                         msg.clone()
3872                 },
3873                 _ => panic!("Unexpected event"),
3874         };
3875         let (as_announcement, as_update) = match events_3[1] {
3876                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3877                         (msg.clone(), update_msg.clone())
3878                 },
3879                 _ => panic!("Unexpected event"),
3880         };
3881
3882         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3883         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3884         assert_eq!(events_4.len(), 1);
3885         let (_, bs_update) = match events_4[0] {
3886                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3887                         (msg.clone(), update_msg.clone())
3888                 },
3889                 _ => panic!("Unexpected event"),
3890         };
3891
3892         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3893         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3894         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3895
3896         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3897         let logger = test_utils::TestLogger::new();
3898         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();
3899         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3900         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3901 }
3902
3903 #[test]
3904 fn test_drop_messages_peer_disconnect_dual_htlc() {
3905         // Test that we can handle reconnecting when both sides of a channel have pending
3906         // commitment_updates when we disconnect.
3907         let chanmon_cfgs = create_chanmon_cfgs(2);
3908         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3909         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3910         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3911         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3912         let logger = test_utils::TestLogger::new();
3913
3914         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3915
3916         // Now try to send a second payment which will fail to send
3917         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3918         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3919         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();
3920         nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3921         check_added_monitors!(nodes[0], 1);
3922
3923         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3924         assert_eq!(events_1.len(), 1);
3925         match events_1[0] {
3926                 MessageSendEvent::UpdateHTLCs { .. } => {},
3927                 _ => panic!("Unexpected event"),
3928         }
3929
3930         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3931         check_added_monitors!(nodes[1], 1);
3932
3933         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3934         assert_eq!(events_2.len(), 1);
3935         match events_2[0] {
3936                 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 } } => {
3937                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3938                         assert!(update_add_htlcs.is_empty());
3939                         assert_eq!(update_fulfill_htlcs.len(), 1);
3940                         assert!(update_fail_htlcs.is_empty());
3941                         assert!(update_fail_malformed_htlcs.is_empty());
3942                         assert!(update_fee.is_none());
3943
3944                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3945                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3946                         assert_eq!(events_3.len(), 1);
3947                         match events_3[0] {
3948                                 Event::PaymentSent { ref payment_preimage } => {
3949                                         assert_eq!(*payment_preimage, payment_preimage_1);
3950                                 },
3951                                 _ => panic!("Unexpected event"),
3952                         }
3953
3954                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3955                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3956                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3957                         check_added_monitors!(nodes[0], 1);
3958                 },
3959                 _ => panic!("Unexpected event"),
3960         }
3961
3962         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3963         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3964
3965         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3966         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3967         assert_eq!(reestablish_1.len(), 1);
3968         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3969         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3970         assert_eq!(reestablish_2.len(), 1);
3971
3972         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3973         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3974         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3975         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3976
3977         assert!(as_resp.0.is_none());
3978         assert!(bs_resp.0.is_none());
3979
3980         assert!(bs_resp.1.is_none());
3981         assert!(bs_resp.2.is_none());
3982
3983         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3984
3985         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3986         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3987         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3988         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3989         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3990         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3991         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3992         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3993         // No commitment_signed so get_event_msg's assert(len == 1) passes
3994         check_added_monitors!(nodes[1], 1);
3995
3996         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3997         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3998         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3999         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4000         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4001         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4002         assert!(bs_second_commitment_signed.update_fee.is_none());
4003         check_added_monitors!(nodes[1], 1);
4004
4005         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4006         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4007         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4008         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4009         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4010         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4011         assert!(as_commitment_signed.update_fee.is_none());
4012         check_added_monitors!(nodes[0], 1);
4013
4014         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4015         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4016         // No commitment_signed so get_event_msg's assert(len == 1) passes
4017         check_added_monitors!(nodes[0], 1);
4018
4019         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4020         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4021         // No commitment_signed so get_event_msg's assert(len == 1) passes
4022         check_added_monitors!(nodes[1], 1);
4023
4024         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4025         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4026         check_added_monitors!(nodes[1], 1);
4027
4028         expect_pending_htlcs_forwardable!(nodes[1]);
4029
4030         let events_5 = nodes[1].node.get_and_clear_pending_events();
4031         assert_eq!(events_5.len(), 1);
4032         match events_5[0] {
4033                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4034                         assert_eq!(payment_hash_2, *payment_hash);
4035                         assert_eq!(*payment_secret, None);
4036                 },
4037                 _ => panic!("Unexpected event"),
4038         }
4039
4040         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4041         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4042         check_added_monitors!(nodes[0], 1);
4043
4044         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4045 }
4046
4047 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4048         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4049         // to avoid our counterparty failing the channel.
4050         let chanmon_cfgs = create_chanmon_cfgs(2);
4051         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4052         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4053         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4054
4055         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4056         let logger = test_utils::TestLogger::new();
4057
4058         let our_payment_hash = if send_partial_mpp {
4059                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4060                 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();
4061                 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4062                 let payment_secret = PaymentSecret([0xdb; 32]);
4063                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4064                 // indicates there are more HTLCs coming.
4065                 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.
4066                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height).unwrap();
4067                 check_added_monitors!(nodes[0], 1);
4068                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4069                 assert_eq!(events.len(), 1);
4070                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4071                 // hop should *not* yet generate any PaymentReceived event(s).
4072                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4073                 our_payment_hash
4074         } else {
4075                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4076         };
4077
4078         let mut block = Block {
4079                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4080                 txdata: vec![],
4081         };
4082         connect_block(&nodes[0], &block);
4083         connect_block(&nodes[1], &block);
4084         for _ in CHAN_CONFIRM_DEPTH + 2 ..TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4085                 block.header.prev_blockhash = block.block_hash();
4086                 connect_block(&nodes[0], &block);
4087                 connect_block(&nodes[1], &block);
4088         }
4089
4090         expect_pending_htlcs_forwardable!(nodes[1]);
4091
4092         check_added_monitors!(nodes[1], 1);
4093         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4094         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4095         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4096         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4097         assert!(htlc_timeout_updates.update_fee.is_none());
4098
4099         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4100         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4101         // 100_000 msat as u64, followed by a height of TEST_FINAL_CLTV + 2 as u32
4102         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4103         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(TEST_FINAL_CLTV + 2));
4104         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4105 }
4106
4107 #[test]
4108 fn test_htlc_timeout() {
4109         do_test_htlc_timeout(true);
4110         do_test_htlc_timeout(false);
4111 }
4112
4113 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4114         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4115         let chanmon_cfgs = create_chanmon_cfgs(3);
4116         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4117         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4118         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4119         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4120         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4121
4122         // Make sure all nodes are at the same starting height
4123         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4124         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4125         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4126
4127         let logger = test_utils::TestLogger::new();
4128
4129         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4130         let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4131         {
4132                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4133                 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();
4134                 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4135         }
4136         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4137         check_added_monitors!(nodes[1], 1);
4138
4139         // Now attempt to route a second payment, which should be placed in the holding cell
4140         let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4141         if forwarded_htlc {
4142                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4143                 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();
4144                 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4145                 check_added_monitors!(nodes[0], 1);
4146                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4147                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4148                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4149                 expect_pending_htlcs_forwardable!(nodes[1]);
4150                 check_added_monitors!(nodes[1], 0);
4151         } else {
4152                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4153                 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();
4154                 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4155                 check_added_monitors!(nodes[1], 0);
4156         }
4157
4158         connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4159         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4160         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4161         connect_blocks(&nodes[1], 1);
4162
4163         if forwarded_htlc {
4164                 expect_pending_htlcs_forwardable!(nodes[1]);
4165                 check_added_monitors!(nodes[1], 1);
4166                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4167                 assert_eq!(fail_commit.len(), 1);
4168                 match fail_commit[0] {
4169                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4170                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4171                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4172                         },
4173                         _ => unreachable!(),
4174                 }
4175                 expect_payment_failed!(nodes[0], second_payment_hash, false);
4176                 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4177                         match update {
4178                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4179                                 _ => panic!("Unexpected event"),
4180                         }
4181                 } else {
4182                         panic!("Unexpected event");
4183                 }
4184         } else {
4185                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4186         }
4187 }
4188
4189 #[test]
4190 fn test_holding_cell_htlc_add_timeouts() {
4191         do_test_holding_cell_htlc_add_timeouts(false);
4192         do_test_holding_cell_htlc_add_timeouts(true);
4193 }
4194
4195 #[test]
4196 fn test_invalid_channel_announcement() {
4197         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4198         let secp_ctx = Secp256k1::new();
4199         let chanmon_cfgs = create_chanmon_cfgs(2);
4200         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4201         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4202         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4203
4204         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4205
4206         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4207         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4208         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4209         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4210
4211         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 } );
4212
4213         let as_bitcoin_key = as_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4214         let bs_bitcoin_key = bs_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4215
4216         let as_network_key = nodes[0].node.get_our_node_id();
4217         let bs_network_key = nodes[1].node.get_our_node_id();
4218
4219         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4220
4221         let mut chan_announcement;
4222
4223         macro_rules! dummy_unsigned_msg {
4224                 () => {
4225                         msgs::UnsignedChannelAnnouncement {
4226                                 features: ChannelFeatures::known(),
4227                                 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4228                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4229                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4230                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4231                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4232                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4233                                 excess_data: Vec::new(),
4234                         };
4235                 }
4236         }
4237
4238         macro_rules! sign_msg {
4239                 ($unsigned_msg: expr) => {
4240                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4241                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_signer().inner.funding_key);
4242                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_signer().inner.funding_key);
4243                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4244                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4245                         chan_announcement = msgs::ChannelAnnouncement {
4246                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4247                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4248                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4249                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4250                                 contents: $unsigned_msg
4251                         }
4252                 }
4253         }
4254
4255         let unsigned_msg = dummy_unsigned_msg!();
4256         sign_msg!(unsigned_msg);
4257         assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4258         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 } );
4259
4260         // Configured with Network::Testnet
4261         let mut unsigned_msg = dummy_unsigned_msg!();
4262         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4263         sign_msg!(unsigned_msg);
4264         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4265
4266         let mut unsigned_msg = dummy_unsigned_msg!();
4267         unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4268         sign_msg!(unsigned_msg);
4269         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4270 }
4271
4272 #[test]
4273 fn test_no_txn_manager_serialize_deserialize() {
4274         let chanmon_cfgs = create_chanmon_cfgs(2);
4275         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4276         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4277         let logger: test_utils::TestLogger;
4278         let fee_estimator: test_utils::TestFeeEstimator;
4279         let persister: test_utils::TestPersister;
4280         let new_chain_monitor: test_utils::TestChainMonitor;
4281         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4282         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4283
4284         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4285
4286         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4287
4288         let nodes_0_serialized = nodes[0].node.encode();
4289         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4290         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4291
4292         logger = test_utils::TestLogger::new();
4293         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4294         persister = test_utils::TestPersister::new();
4295         let keys_manager = &chanmon_cfgs[0].keys_manager;
4296         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4297         nodes[0].chain_monitor = &new_chain_monitor;
4298         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4299         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4300                 &mut chan_0_monitor_read, keys_manager).unwrap();
4301         assert!(chan_0_monitor_read.is_empty());
4302
4303         let mut nodes_0_read = &nodes_0_serialized[..];
4304         let config = UserConfig::default();
4305         let (_, nodes_0_deserialized_tmp) = {
4306                 let mut channel_monitors = HashMap::new();
4307                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4308                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4309                         default_config: config,
4310                         keys_manager,
4311                         fee_estimator: &fee_estimator,
4312                         chain_monitor: nodes[0].chain_monitor,
4313                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4314                         logger: &logger,
4315                         channel_monitors,
4316                 }).unwrap()
4317         };
4318         nodes_0_deserialized = nodes_0_deserialized_tmp;
4319         assert!(nodes_0_read.is_empty());
4320
4321         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4322         nodes[0].node = &nodes_0_deserialized;
4323         assert_eq!(nodes[0].node.list_channels().len(), 1);
4324         check_added_monitors!(nodes[0], 1);
4325
4326         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4327         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4328         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4329         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4330
4331         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4332         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4333         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4334         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4335
4336         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4337         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4338         for node in nodes.iter() {
4339                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4340                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4341                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4342         }
4343
4344         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4345 }
4346
4347 #[test]
4348 fn test_manager_serialize_deserialize_events() {
4349         // This test makes sure the events field in ChannelManager survives de/serialization
4350         let chanmon_cfgs = create_chanmon_cfgs(2);
4351         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4352         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4353         let fee_estimator: test_utils::TestFeeEstimator;
4354         let persister: test_utils::TestPersister;
4355         let logger: test_utils::TestLogger;
4356         let new_chain_monitor: test_utils::TestChainMonitor;
4357         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4358         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4359
4360         // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4361         let channel_value = 100000;
4362         let push_msat = 10001;
4363         let a_flags = InitFeatures::known();
4364         let b_flags = InitFeatures::known();
4365         let node_a = nodes.remove(0);
4366         let node_b = nodes.remove(0);
4367         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4368         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()));
4369         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()));
4370
4371         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4372
4373         node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4374         check_added_monitors!(node_a, 0);
4375
4376         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()));
4377         {
4378                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4379                 assert_eq!(added_monitors.len(), 1);
4380                 assert_eq!(added_monitors[0].0, funding_output);
4381                 added_monitors.clear();
4382         }
4383
4384         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()));
4385         {
4386                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4387                 assert_eq!(added_monitors.len(), 1);
4388                 assert_eq!(added_monitors[0].0, funding_output);
4389                 added_monitors.clear();
4390         }
4391         // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4392
4393         nodes.push(node_a);
4394         nodes.push(node_b);
4395
4396         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4397         let nodes_0_serialized = nodes[0].node.encode();
4398         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4399         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4400
4401         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4402         logger = test_utils::TestLogger::new();
4403         persister = test_utils::TestPersister::new();
4404         let keys_manager = &chanmon_cfgs[0].keys_manager;
4405         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4406         nodes[0].chain_monitor = &new_chain_monitor;
4407         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4408         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4409                 &mut chan_0_monitor_read, keys_manager).unwrap();
4410         assert!(chan_0_monitor_read.is_empty());
4411
4412         let mut nodes_0_read = &nodes_0_serialized[..];
4413         let config = UserConfig::default();
4414         let (_, nodes_0_deserialized_tmp) = {
4415                 let mut channel_monitors = HashMap::new();
4416                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4417                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4418                         default_config: config,
4419                         keys_manager,
4420                         fee_estimator: &fee_estimator,
4421                         chain_monitor: nodes[0].chain_monitor,
4422                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4423                         logger: &logger,
4424                         channel_monitors,
4425                 }).unwrap()
4426         };
4427         nodes_0_deserialized = nodes_0_deserialized_tmp;
4428         assert!(nodes_0_read.is_empty());
4429
4430         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4431
4432         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4433         nodes[0].node = &nodes_0_deserialized;
4434
4435         // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4436         let events_4 = nodes[0].node.get_and_clear_pending_events();
4437         assert_eq!(events_4.len(), 1);
4438         match events_4[0] {
4439                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4440                         assert_eq!(user_channel_id, 42);
4441                         assert_eq!(*funding_txo, funding_output);
4442                 },
4443                 _ => panic!("Unexpected event"),
4444         };
4445
4446         // Make sure the channel is functioning as though the de/serialization never happened
4447         assert_eq!(nodes[0].node.list_channels().len(), 1);
4448         check_added_monitors!(nodes[0], 1);
4449
4450         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4451         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4452         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4453         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4454
4455         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4456         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4457         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4458         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4459
4460         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4461         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4462         for node in nodes.iter() {
4463                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4464                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4465                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4466         }
4467
4468         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4469 }
4470
4471 #[test]
4472 fn test_simple_manager_serialize_deserialize() {
4473         let chanmon_cfgs = create_chanmon_cfgs(2);
4474         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4475         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4476         let logger: test_utils::TestLogger;
4477         let fee_estimator: test_utils::TestFeeEstimator;
4478         let persister: test_utils::TestPersister;
4479         let new_chain_monitor: test_utils::TestChainMonitor;
4480         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4481         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4482         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4483
4484         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4485         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4486
4487         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4488
4489         let nodes_0_serialized = nodes[0].node.encode();
4490         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4491         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4492
4493         logger = test_utils::TestLogger::new();
4494         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4495         persister = test_utils::TestPersister::new();
4496         let keys_manager = &chanmon_cfgs[0].keys_manager;
4497         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4498         nodes[0].chain_monitor = &new_chain_monitor;
4499         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4500         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4501                 &mut chan_0_monitor_read, keys_manager).unwrap();
4502         assert!(chan_0_monitor_read.is_empty());
4503
4504         let mut nodes_0_read = &nodes_0_serialized[..];
4505         let (_, nodes_0_deserialized_tmp) = {
4506                 let mut channel_monitors = HashMap::new();
4507                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4508                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4509                         default_config: UserConfig::default(),
4510                         keys_manager,
4511                         fee_estimator: &fee_estimator,
4512                         chain_monitor: nodes[0].chain_monitor,
4513                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4514                         logger: &logger,
4515                         channel_monitors,
4516                 }).unwrap()
4517         };
4518         nodes_0_deserialized = nodes_0_deserialized_tmp;
4519         assert!(nodes_0_read.is_empty());
4520
4521         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4522         nodes[0].node = &nodes_0_deserialized;
4523         check_added_monitors!(nodes[0], 1);
4524
4525         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4526
4527         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4528         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4529 }
4530
4531 #[test]
4532 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4533         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4534         let chanmon_cfgs = create_chanmon_cfgs(4);
4535         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4536         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4537         let logger: test_utils::TestLogger;
4538         let fee_estimator: test_utils::TestFeeEstimator;
4539         let persister: test_utils::TestPersister;
4540         let new_chain_monitor: test_utils::TestChainMonitor;
4541         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4542         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4543         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4544         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4545         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4546
4547         let mut node_0_stale_monitors_serialized = Vec::new();
4548         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4549                 let mut writer = test_utils::TestVecWriter(Vec::new());
4550                 monitor.1.write(&mut writer).unwrap();
4551                 node_0_stale_monitors_serialized.push(writer.0);
4552         }
4553
4554         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4555
4556         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4557         let nodes_0_serialized = nodes[0].node.encode();
4558
4559         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4560         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4561         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4562         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4563
4564         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4565         // nodes[3])
4566         let mut node_0_monitors_serialized = Vec::new();
4567         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4568                 let mut writer = test_utils::TestVecWriter(Vec::new());
4569                 monitor.1.write(&mut writer).unwrap();
4570                 node_0_monitors_serialized.push(writer.0);
4571         }
4572
4573         logger = test_utils::TestLogger::new();
4574         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4575         persister = test_utils::TestPersister::new();
4576         let keys_manager = &chanmon_cfgs[0].keys_manager;
4577         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4578         nodes[0].chain_monitor = &new_chain_monitor;
4579
4580
4581         let mut node_0_stale_monitors = Vec::new();
4582         for serialized in node_0_stale_monitors_serialized.iter() {
4583                 let mut read = &serialized[..];
4584                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4585                 assert!(read.is_empty());
4586                 node_0_stale_monitors.push(monitor);
4587         }
4588
4589         let mut node_0_monitors = Vec::new();
4590         for serialized in node_0_monitors_serialized.iter() {
4591                 let mut read = &serialized[..];
4592                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4593                 assert!(read.is_empty());
4594                 node_0_monitors.push(monitor);
4595         }
4596
4597         let mut nodes_0_read = &nodes_0_serialized[..];
4598         if let Err(msgs::DecodeError::InvalidValue) =
4599                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4600                 default_config: UserConfig::default(),
4601                 keys_manager,
4602                 fee_estimator: &fee_estimator,
4603                 chain_monitor: nodes[0].chain_monitor,
4604                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4605                 logger: &logger,
4606                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4607         }) { } else {
4608                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4609         };
4610
4611         let mut nodes_0_read = &nodes_0_serialized[..];
4612         let (_, nodes_0_deserialized_tmp) =
4613                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4614                 default_config: UserConfig::default(),
4615                 keys_manager,
4616                 fee_estimator: &fee_estimator,
4617                 chain_monitor: nodes[0].chain_monitor,
4618                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4619                 logger: &logger,
4620                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4621         }).unwrap();
4622         nodes_0_deserialized = nodes_0_deserialized_tmp;
4623         assert!(nodes_0_read.is_empty());
4624
4625         { // Channel close should result in a commitment tx and an HTLC tx
4626                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4627                 assert_eq!(txn.len(), 2);
4628                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4629                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4630         }
4631
4632         for monitor in node_0_monitors.drain(..) {
4633                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4634                 check_added_monitors!(nodes[0], 1);
4635         }
4636         nodes[0].node = &nodes_0_deserialized;
4637
4638         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4639         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4640         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4641         //... and we can even still claim the payment!
4642         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4643
4644         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4645         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4646         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4647         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4648         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4649         assert_eq!(msg_events.len(), 1);
4650         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4651                 match action {
4652                         &ErrorAction::SendErrorMessage { ref msg } => {
4653                                 assert_eq!(msg.channel_id, channel_id);
4654                         },
4655                         _ => panic!("Unexpected event!"),
4656                 }
4657         }
4658 }
4659
4660 macro_rules! check_spendable_outputs {
4661         ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4662                 {
4663                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4664                         let mut txn = Vec::new();
4665                         let mut all_outputs = Vec::new();
4666                         let secp_ctx = Secp256k1::new();
4667                         for event in events.drain(..) {
4668                                 match event {
4669                                         Event::SpendableOutputs { mut outputs } => {
4670                                                 for outp in outputs.drain(..) {
4671                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4672                                                         all_outputs.push(outp);
4673                                                 }
4674                                         },
4675                                         _ => panic!("Unexpected event"),
4676                                 };
4677                         }
4678                         if all_outputs.len() > 1 {
4679                                 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) {
4680                                         txn.push(tx);
4681                                 }
4682                         }
4683                         txn
4684                 }
4685         }
4686 }
4687
4688 #[test]
4689 fn test_claim_sizeable_push_msat() {
4690         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4691         let chanmon_cfgs = create_chanmon_cfgs(2);
4692         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4693         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4694         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4695
4696         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4697         nodes[1].node.force_close_channel(&chan.2).unwrap();
4698         check_closed_broadcast!(nodes[1], true);
4699         check_added_monitors!(nodes[1], 1);
4700         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4701         assert_eq!(node_txn.len(), 1);
4702         check_spends!(node_txn[0], chan.3);
4703         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
4704
4705         mine_transaction(&nodes[1], &node_txn[0]);
4706         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4707
4708         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4709         assert_eq!(spend_txn.len(), 1);
4710         check_spends!(spend_txn[0], node_txn[0]);
4711 }
4712
4713 #[test]
4714 fn test_claim_on_remote_sizeable_push_msat() {
4715         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4716         // to_remote output is encumbered by a P2WPKH
4717         let chanmon_cfgs = create_chanmon_cfgs(2);
4718         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4719         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4720         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4721
4722         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4723         nodes[0].node.force_close_channel(&chan.2).unwrap();
4724         check_closed_broadcast!(nodes[0], true);
4725         check_added_monitors!(nodes[0], 1);
4726
4727         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4728         assert_eq!(node_txn.len(), 1);
4729         check_spends!(node_txn[0], chan.3);
4730         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
4731
4732         mine_transaction(&nodes[1], &node_txn[0]);
4733         check_closed_broadcast!(nodes[1], true);
4734         check_added_monitors!(nodes[1], 1);
4735         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4736
4737         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4738         assert_eq!(spend_txn.len(), 1);
4739         check_spends!(spend_txn[0], node_txn[0]);
4740 }
4741
4742 #[test]
4743 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4744         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4745         // to_remote output is encumbered by a P2WPKH
4746
4747         let chanmon_cfgs = create_chanmon_cfgs(2);
4748         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4749         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4750         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4751
4752         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4753         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4754         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4755         assert_eq!(revoked_local_txn[0].input.len(), 1);
4756         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4757
4758         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4759         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4760         check_closed_broadcast!(nodes[1], true);
4761         check_added_monitors!(nodes[1], 1);
4762
4763         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4764         mine_transaction(&nodes[1], &node_txn[0]);
4765         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4766
4767         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4768         assert_eq!(spend_txn.len(), 3);
4769         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4770         check_spends!(spend_txn[1], node_txn[0]);
4771         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4772 }
4773
4774 #[test]
4775 fn test_static_spendable_outputs_preimage_tx() {
4776         let chanmon_cfgs = create_chanmon_cfgs(2);
4777         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4778         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4779         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4780
4781         // Create some initial channels
4782         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4783
4784         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4785
4786         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4787         assert_eq!(commitment_tx[0].input.len(), 1);
4788         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4789
4790         // Settle A's commitment tx on B's chain
4791         assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4792         check_added_monitors!(nodes[1], 1);
4793         mine_transaction(&nodes[1], &commitment_tx[0]);
4794         check_added_monitors!(nodes[1], 1);
4795         let events = nodes[1].node.get_and_clear_pending_msg_events();
4796         match events[0] {
4797                 MessageSendEvent::UpdateHTLCs { .. } => {},
4798                 _ => panic!("Unexpected event"),
4799         }
4800         match events[1] {
4801                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4802                 _ => panic!("Unexepected event"),
4803         }
4804
4805         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4806         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4807         assert_eq!(node_txn.len(), 3);
4808         check_spends!(node_txn[0], commitment_tx[0]);
4809         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4810         check_spends!(node_txn[1], chan_1.3);
4811         check_spends!(node_txn[2], node_txn[1]);
4812
4813         mine_transaction(&nodes[1], &node_txn[0]);
4814         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4815
4816         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4817         assert_eq!(spend_txn.len(), 1);
4818         check_spends!(spend_txn[0], node_txn[0]);
4819 }
4820
4821 #[test]
4822 fn test_static_spendable_outputs_timeout_tx() {
4823         let chanmon_cfgs = create_chanmon_cfgs(2);
4824         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4825         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4826         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4827
4828         // Create some initial channels
4829         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4830
4831         // Rebalance the network a bit by relaying one payment through all the channels ...
4832         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4833
4834         let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4835
4836         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4837         assert_eq!(commitment_tx[0].input.len(), 1);
4838         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4839
4840         // Settle A's commitment tx on B' chain
4841         mine_transaction(&nodes[1], &commitment_tx[0]);
4842         check_added_monitors!(nodes[1], 1);
4843         let events = nodes[1].node.get_and_clear_pending_msg_events();
4844         match events[0] {
4845                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4846                 _ => panic!("Unexpected event"),
4847         }
4848
4849         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4850         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4851         assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4852         check_spends!(node_txn[0],  commitment_tx[0].clone());
4853         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4854         check_spends!(node_txn[1], chan_1.3.clone());
4855         check_spends!(node_txn[2], node_txn[1]);
4856
4857         mine_transaction(&nodes[1], &node_txn[0]);
4858         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4859         expect_payment_failed!(nodes[1], our_payment_hash, true);
4860
4861         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4862         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4863         check_spends!(spend_txn[0], commitment_tx[0]);
4864         check_spends!(spend_txn[1], node_txn[0]);
4865         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4866 }
4867
4868 #[test]
4869 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4870         let chanmon_cfgs = create_chanmon_cfgs(2);
4871         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4872         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4873         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4874
4875         // Create some initial channels
4876         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4877
4878         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4879         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4880         assert_eq!(revoked_local_txn[0].input.len(), 1);
4881         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4882
4883         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4884
4885         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4886         check_closed_broadcast!(nodes[1], true);
4887         check_added_monitors!(nodes[1], 1);
4888
4889         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4890         assert_eq!(node_txn.len(), 2);
4891         assert_eq!(node_txn[0].input.len(), 2);
4892         check_spends!(node_txn[0], revoked_local_txn[0]);
4893
4894         mine_transaction(&nodes[1], &node_txn[0]);
4895         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4896
4897         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4898         assert_eq!(spend_txn.len(), 1);
4899         check_spends!(spend_txn[0], node_txn[0]);
4900 }
4901
4902 #[test]
4903 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4904         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4905         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4906         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4907         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4908         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4909
4910         // Create some initial channels
4911         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4912
4913         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4914         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4915         assert_eq!(revoked_local_txn[0].input.len(), 1);
4916         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4917
4918         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4919
4920         // A will generate HTLC-Timeout from revoked commitment tx
4921         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4922         check_closed_broadcast!(nodes[0], true);
4923         check_added_monitors!(nodes[0], 1);
4924
4925         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4926         assert_eq!(revoked_htlc_txn.len(), 2);
4927         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4928         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4929         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4930         check_spends!(revoked_htlc_txn[1], chan_1.3);
4931
4932         // B will generate justice tx from A's revoked commitment/HTLC tx
4933         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4934         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4935         check_closed_broadcast!(nodes[1], true);
4936         check_added_monitors!(nodes[1], 1);
4937
4938         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4939         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4940         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4941         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4942         // transactions next...
4943         assert_eq!(node_txn[0].input.len(), 3);
4944         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4945
4946         assert_eq!(node_txn[1].input.len(), 2);
4947         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4948         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4949                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4950         } else {
4951                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4952                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4953         }
4954
4955         assert_eq!(node_txn[2].input.len(), 1);
4956         check_spends!(node_txn[2], chan_1.3);
4957
4958         mine_transaction(&nodes[1], &node_txn[1]);
4959         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4960
4961         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4962         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4963         assert_eq!(spend_txn.len(), 1);
4964         assert_eq!(spend_txn[0].input.len(), 1);
4965         check_spends!(spend_txn[0], node_txn[1]);
4966 }
4967
4968 #[test]
4969 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4970         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4971         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4972         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4973         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4974         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4975
4976         // Create some initial channels
4977         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4978
4979         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4980         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4981         assert_eq!(revoked_local_txn[0].input.len(), 1);
4982         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4983
4984         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4985         assert_eq!(revoked_local_txn[0].output.len(), 2);
4986
4987         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4988
4989         // B will generate HTLC-Success from revoked commitment tx
4990         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4991         check_closed_broadcast!(nodes[1], true);
4992         check_added_monitors!(nodes[1], 1);
4993         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4994
4995         assert_eq!(revoked_htlc_txn.len(), 2);
4996         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4997         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4998         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4999
5000         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5001         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5002         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5003
5004         // A will generate justice tx from B's revoked commitment/HTLC tx
5005         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5006         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5007         check_closed_broadcast!(nodes[0], true);
5008         check_added_monitors!(nodes[0], 1);
5009
5010         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5011         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5012
5013         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5014         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5015         // transactions next...
5016         assert_eq!(node_txn[0].input.len(), 2);
5017         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5018         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5019                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5020         } else {
5021                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5022                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5023         }
5024
5025         assert_eq!(node_txn[1].input.len(), 1);
5026         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5027
5028         check_spends!(node_txn[2], chan_1.3);
5029
5030         mine_transaction(&nodes[0], &node_txn[1]);
5031         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5032
5033         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5034         // didn't try to generate any new transactions.
5035
5036         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5037         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5038         assert_eq!(spend_txn.len(), 3);
5039         assert_eq!(spend_txn[0].input.len(), 1);
5040         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5041         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5042         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5043         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5044 }
5045
5046 #[test]
5047 fn test_onchain_to_onchain_claim() {
5048         // Test that in case of channel closure, we detect the state of output and claim HTLC
5049         // on downstream peer's remote commitment tx.
5050         // First, have C claim an HTLC against its own latest commitment transaction.
5051         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5052         // channel.
5053         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5054         // gets broadcast.
5055
5056         let chanmon_cfgs = create_chanmon_cfgs(3);
5057         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5058         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5059         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5060
5061         // Create some initial channels
5062         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5063         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5064
5065         // Rebalance the network a bit by relaying one payment through all the channels ...
5066         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5067         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5068
5069         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5070         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5071         check_spends!(commitment_tx[0], chan_2.3);
5072         nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5073         check_added_monitors!(nodes[2], 1);
5074         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5075         assert!(updates.update_add_htlcs.is_empty());
5076         assert!(updates.update_fail_htlcs.is_empty());
5077         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5078         assert!(updates.update_fail_malformed_htlcs.is_empty());
5079
5080         mine_transaction(&nodes[2], &commitment_tx[0]);
5081         check_closed_broadcast!(nodes[2], true);
5082         check_added_monitors!(nodes[2], 1);
5083
5084         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5085         assert_eq!(c_txn.len(), 3);
5086         assert_eq!(c_txn[0], c_txn[2]);
5087         assert_eq!(commitment_tx[0], c_txn[1]);
5088         check_spends!(c_txn[1], chan_2.3);
5089         check_spends!(c_txn[2], c_txn[1]);
5090         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5091         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5092         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5093         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5094
5095         // 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
5096         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5097         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5098         {
5099                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5100                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5101                 assert_eq!(b_txn.len(), 3);
5102                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5103                 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5104                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5105                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5106                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5107                 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5108                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5109                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5110                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5111                 b_txn.clear();
5112         }
5113         check_added_monitors!(nodes[1], 1);
5114         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5115         assert_eq!(msg_events.len(), 3);
5116         check_added_monitors!(nodes[1], 1);
5117         match msg_events[0] {
5118                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5119                 _ => panic!("Unexpected event"),
5120         }
5121         match msg_events[1] {
5122                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5123                 _ => panic!("Unexpected event"),
5124         }
5125         match msg_events[2] {
5126                 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, .. } } => {
5127                         assert!(update_add_htlcs.is_empty());
5128                         assert!(update_fail_htlcs.is_empty());
5129                         assert_eq!(update_fulfill_htlcs.len(), 1);
5130                         assert!(update_fail_malformed_htlcs.is_empty());
5131                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5132                 },
5133                 _ => panic!("Unexpected event"),
5134         };
5135         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5136         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5137         mine_transaction(&nodes[1], &commitment_tx[0]);
5138         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5139         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5140         assert_eq!(b_txn.len(), 3);
5141         check_spends!(b_txn[1], chan_1.3);
5142         check_spends!(b_txn[2], b_txn[1]);
5143         check_spends!(b_txn[0], commitment_tx[0]);
5144         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5145         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5146         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5147
5148         check_closed_broadcast!(nodes[1], true);
5149         check_added_monitors!(nodes[1], 1);
5150 }
5151
5152 #[test]
5153 fn test_duplicate_payment_hash_one_failure_one_success() {
5154         // Topology : A --> B --> C
5155         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5156         let chanmon_cfgs = create_chanmon_cfgs(3);
5157         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5158         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5159         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5160
5161         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5162         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5163
5164         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5165         *nodes[0].network_payment_count.borrow_mut() -= 1;
5166         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5167
5168         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5169         assert_eq!(commitment_txn[0].input.len(), 1);
5170         check_spends!(commitment_txn[0], chan_2.3);
5171
5172         mine_transaction(&nodes[1], &commitment_txn[0]);
5173         check_closed_broadcast!(nodes[1], true);
5174         check_added_monitors!(nodes[1], 1);
5175
5176         let htlc_timeout_tx;
5177         { // Extract one of the two HTLC-Timeout transaction
5178                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5179                 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5180                 assert_eq!(node_txn.len(), 5);
5181                 check_spends!(node_txn[0], commitment_txn[0]);
5182                 assert_eq!(node_txn[0].input.len(), 1);
5183                 check_spends!(node_txn[1], commitment_txn[0]);
5184                 assert_eq!(node_txn[1].input.len(), 1);
5185                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5186                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5187                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5188                 check_spends!(node_txn[2], chan_2.3);
5189                 check_spends!(node_txn[3], node_txn[2]);
5190                 check_spends!(node_txn[4], node_txn[2]);
5191                 htlc_timeout_tx = node_txn[1].clone();
5192         }
5193
5194         nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5195         mine_transaction(&nodes[2], &commitment_txn[0]);
5196         check_added_monitors!(nodes[2], 3);
5197         let events = nodes[2].node.get_and_clear_pending_msg_events();
5198         match events[0] {
5199                 MessageSendEvent::UpdateHTLCs { .. } => {},
5200                 _ => panic!("Unexpected event"),
5201         }
5202         match events[1] {
5203                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5204                 _ => panic!("Unexepected event"),
5205         }
5206         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5207         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)
5208         check_spends!(htlc_success_txn[2], chan_2.3);
5209         check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5210         check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5211         assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5212         assert_eq!(htlc_success_txn[0].input.len(), 1);
5213         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5214         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5215         assert_eq!(htlc_success_txn[1].input.len(), 1);
5216         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5217         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5218         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5219         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5220
5221         mine_transaction(&nodes[1], &htlc_timeout_tx);
5222         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5223         expect_pending_htlcs_forwardable!(nodes[1]);
5224         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5225         assert!(htlc_updates.update_add_htlcs.is_empty());
5226         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5227         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5228         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5229         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5230         check_added_monitors!(nodes[1], 1);
5231
5232         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5233         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5234         {
5235                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5236                 let events = nodes[0].node.get_and_clear_pending_msg_events();
5237                 assert_eq!(events.len(), 1);
5238                 match events[0] {
5239                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
5240                         },
5241                         _ => { panic!("Unexpected event"); }
5242                 }
5243         }
5244         expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5245
5246         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5247         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5248         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5249         assert!(updates.update_add_htlcs.is_empty());
5250         assert!(updates.update_fail_htlcs.is_empty());
5251         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5252         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5253         assert!(updates.update_fail_malformed_htlcs.is_empty());
5254         check_added_monitors!(nodes[1], 1);
5255
5256         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5257         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5258
5259         let events = nodes[0].node.get_and_clear_pending_events();
5260         match events[0] {
5261                 Event::PaymentSent { ref payment_preimage } => {
5262                         assert_eq!(*payment_preimage, our_payment_preimage);
5263                 }
5264                 _ => panic!("Unexpected event"),
5265         }
5266 }
5267
5268 #[test]
5269 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5270         let chanmon_cfgs = create_chanmon_cfgs(2);
5271         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5272         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5273         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5274
5275         // Create some initial channels
5276         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5277
5278         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5279         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5280         assert_eq!(local_txn.len(), 1);
5281         assert_eq!(local_txn[0].input.len(), 1);
5282         check_spends!(local_txn[0], chan_1.3);
5283
5284         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5285         nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5286         check_added_monitors!(nodes[1], 1);
5287         mine_transaction(&nodes[1], &local_txn[0]);
5288         check_added_monitors!(nodes[1], 1);
5289         let events = nodes[1].node.get_and_clear_pending_msg_events();
5290         match events[0] {
5291                 MessageSendEvent::UpdateHTLCs { .. } => {},
5292                 _ => panic!("Unexpected event"),
5293         }
5294         match events[1] {
5295                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5296                 _ => panic!("Unexepected event"),
5297         }
5298         let node_tx = {
5299                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5300                 assert_eq!(node_txn.len(), 3);
5301                 assert_eq!(node_txn[0], node_txn[2]);
5302                 assert_eq!(node_txn[1], local_txn[0]);
5303                 assert_eq!(node_txn[0].input.len(), 1);
5304                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5305                 check_spends!(node_txn[0], local_txn[0]);
5306                 node_txn[0].clone()
5307         };
5308
5309         mine_transaction(&nodes[1], &node_tx);
5310         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5311
5312         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5313         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5314         assert_eq!(spend_txn.len(), 1);
5315         check_spends!(spend_txn[0], node_tx);
5316 }
5317
5318 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5319         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5320         // unrevoked commitment transaction.
5321         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5322         // a remote RAA before they could be failed backwards (and combinations thereof).
5323         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5324         // use the same payment hashes.
5325         // Thus, we use a six-node network:
5326         //
5327         // A \         / E
5328         //    - C - D -
5329         // B /         \ F
5330         // And test where C fails back to A/B when D announces its latest commitment transaction
5331         let chanmon_cfgs = create_chanmon_cfgs(6);
5332         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5333         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5334         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5335         let logger = test_utils::TestLogger::new();
5336
5337         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5338         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5339         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5340         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5341         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5342
5343         // Rebalance and check output sanity...
5344         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5345         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5346         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5347
5348         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5349         // 0th HTLC:
5350         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
5351         // 1st HTLC:
5352         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
5353         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5354         let our_node_id = &nodes[1].node.get_our_node_id();
5355         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();
5356         // 2nd HTLC:
5357         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
5358         // 3rd HTLC:
5359         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
5360         // 4th HTLC:
5361         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5362         // 5th HTLC:
5363         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5364         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();
5365         // 6th HTLC:
5366         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5367         // 7th HTLC:
5368         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5369
5370         // 8th HTLC:
5371         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5372         // 9th 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(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5374         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
5375
5376         // 10th HTLC:
5377         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
5378         // 11th HTLC:
5379         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();
5380         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5381
5382         // Double-check that six of the new HTLC were added
5383         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5384         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5385         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5386         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5387
5388         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5389         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5390         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5391         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5392         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5393         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5394         check_added_monitors!(nodes[4], 0);
5395         expect_pending_htlcs_forwardable!(nodes[4]);
5396         check_added_monitors!(nodes[4], 1);
5397
5398         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5399         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5400         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5401         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5402         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5403         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5404
5405         // Fail 3rd below-dust and 7th above-dust HTLCs
5406         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5407         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5408         check_added_monitors!(nodes[5], 0);
5409         expect_pending_htlcs_forwardable!(nodes[5]);
5410         check_added_monitors!(nodes[5], 1);
5411
5412         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5413         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5414         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5415         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5416
5417         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5418
5419         expect_pending_htlcs_forwardable!(nodes[3]);
5420         check_added_monitors!(nodes[3], 1);
5421         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5422         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5423         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5424         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5425         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5426         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5427         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5428         if deliver_last_raa {
5429                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5430         } else {
5431                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5432         }
5433
5434         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5435         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5436         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5437         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5438         //
5439         // We now broadcast the latest commitment transaction, which *should* result in failures for
5440         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5441         // the non-broadcast above-dust HTLCs.
5442         //
5443         // Alternatively, we may broadcast the previous commitment transaction, which should only
5444         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5445         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5446
5447         if announce_latest {
5448                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5449         } else {
5450                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5451         }
5452         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5453         check_closed_broadcast!(nodes[2], true);
5454         expect_pending_htlcs_forwardable!(nodes[2]);
5455         check_added_monitors!(nodes[2], 3);
5456
5457         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5458         assert_eq!(cs_msgs.len(), 2);
5459         let mut a_done = false;
5460         for msg in cs_msgs {
5461                 match msg {
5462                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5463                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5464                                 // should be failed-backwards here.
5465                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5466                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5467                                         for htlc in &updates.update_fail_htlcs {
5468                                                 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 });
5469                                         }
5470                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5471                                         assert!(!a_done);
5472                                         a_done = true;
5473                                         &nodes[0]
5474                                 } else {
5475                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5476                                         for htlc in &updates.update_fail_htlcs {
5477                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5478                                         }
5479                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5480                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5481                                         &nodes[1]
5482                                 };
5483                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5484                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5485                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5486                                 if announce_latest {
5487                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5488                                         if *node_id == nodes[0].node.get_our_node_id() {
5489                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5490                                         }
5491                                 }
5492                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5493                         },
5494                         _ => panic!("Unexpected event"),
5495                 }
5496         }
5497
5498         let as_events = nodes[0].node.get_and_clear_pending_events();
5499         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5500         let mut as_failds = HashSet::new();
5501         for event in as_events.iter() {
5502                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5503                         assert!(as_failds.insert(*payment_hash));
5504                         if *payment_hash != payment_hash_2 {
5505                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5506                         } else {
5507                                 assert!(!rejected_by_dest);
5508                         }
5509                 } else { panic!("Unexpected event"); }
5510         }
5511         assert!(as_failds.contains(&payment_hash_1));
5512         assert!(as_failds.contains(&payment_hash_2));
5513         if announce_latest {
5514                 assert!(as_failds.contains(&payment_hash_3));
5515                 assert!(as_failds.contains(&payment_hash_5));
5516         }
5517         assert!(as_failds.contains(&payment_hash_6));
5518
5519         let bs_events = nodes[1].node.get_and_clear_pending_events();
5520         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5521         let mut bs_failds = HashSet::new();
5522         for event in bs_events.iter() {
5523                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5524                         assert!(bs_failds.insert(*payment_hash));
5525                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5526                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5527                         } else {
5528                                 assert!(!rejected_by_dest);
5529                         }
5530                 } else { panic!("Unexpected event"); }
5531         }
5532         assert!(bs_failds.contains(&payment_hash_1));
5533         assert!(bs_failds.contains(&payment_hash_2));
5534         if announce_latest {
5535                 assert!(bs_failds.contains(&payment_hash_4));
5536         }
5537         assert!(bs_failds.contains(&payment_hash_5));
5538
5539         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5540         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5541         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5542         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5543         // PaymentFailureNetworkUpdates.
5544         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5545         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5546         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5547         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5548         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5549                 match event {
5550                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5551                         _ => panic!("Unexpected event"),
5552                 }
5553         }
5554 }
5555
5556 #[test]
5557 fn test_fail_backwards_latest_remote_announce_a() {
5558         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5559 }
5560
5561 #[test]
5562 fn test_fail_backwards_latest_remote_announce_b() {
5563         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5564 }
5565
5566 #[test]
5567 fn test_fail_backwards_previous_remote_announce() {
5568         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5569         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5570         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5571 }
5572
5573 #[test]
5574 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5575         let chanmon_cfgs = create_chanmon_cfgs(2);
5576         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5577         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5578         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5579
5580         // Create some initial channels
5581         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5582
5583         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5584         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5585         assert_eq!(local_txn[0].input.len(), 1);
5586         check_spends!(local_txn[0], chan_1.3);
5587
5588         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5589         mine_transaction(&nodes[0], &local_txn[0]);
5590         check_closed_broadcast!(nodes[0], true);
5591         check_added_monitors!(nodes[0], 1);
5592
5593         let htlc_timeout = {
5594                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5595                 assert_eq!(node_txn[0].input.len(), 1);
5596                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5597                 check_spends!(node_txn[0], local_txn[0]);
5598                 node_txn[0].clone()
5599         };
5600
5601         mine_transaction(&nodes[0], &htlc_timeout);
5602         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5603         expect_payment_failed!(nodes[0], our_payment_hash, true);
5604
5605         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5606         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5607         assert_eq!(spend_txn.len(), 3);
5608         check_spends!(spend_txn[0], local_txn[0]);
5609         check_spends!(spend_txn[1], htlc_timeout);
5610         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5611 }
5612
5613 #[test]
5614 fn test_key_derivation_params() {
5615         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5616         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5617         // let us re-derive the channel key set to then derive a delayed_payment_key.
5618
5619         let chanmon_cfgs = create_chanmon_cfgs(3);
5620
5621         // We manually create the node configuration to backup the seed.
5622         let seed = [42; 32];
5623         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5624         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);
5625         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 };
5626         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5627         node_cfgs.remove(0);
5628         node_cfgs.insert(0, node);
5629
5630         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5631         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5632
5633         // Create some initial channels
5634         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5635         // for node 0
5636         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5637         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5638         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5639
5640         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5641         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5642         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5643         assert_eq!(local_txn_1[0].input.len(), 1);
5644         check_spends!(local_txn_1[0], chan_1.3);
5645
5646         // We check funding pubkey are unique
5647         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]));
5648         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]));
5649         if from_0_funding_key_0 == from_1_funding_key_0
5650             || from_0_funding_key_0 == from_1_funding_key_1
5651             || from_0_funding_key_1 == from_1_funding_key_0
5652             || from_0_funding_key_1 == from_1_funding_key_1 {
5653                 panic!("Funding pubkeys aren't unique");
5654         }
5655
5656         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5657         mine_transaction(&nodes[0], &local_txn_1[0]);
5658         check_closed_broadcast!(nodes[0], true);
5659         check_added_monitors!(nodes[0], 1);
5660
5661         let htlc_timeout = {
5662                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5663                 assert_eq!(node_txn[0].input.len(), 1);
5664                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5665                 check_spends!(node_txn[0], local_txn_1[0]);
5666                 node_txn[0].clone()
5667         };
5668
5669         mine_transaction(&nodes[0], &htlc_timeout);
5670         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5671         expect_payment_failed!(nodes[0], our_payment_hash, true);
5672
5673         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5674         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5675         let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5676         assert_eq!(spend_txn.len(), 3);
5677         check_spends!(spend_txn[0], local_txn_1[0]);
5678         check_spends!(spend_txn[1], htlc_timeout);
5679         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5680 }
5681
5682 #[test]
5683 fn test_static_output_closing_tx() {
5684         let chanmon_cfgs = create_chanmon_cfgs(2);
5685         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5686         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5687         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5688
5689         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5690
5691         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5692         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5693
5694         mine_transaction(&nodes[0], &closing_tx);
5695         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5696
5697         let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5698         assert_eq!(spend_txn.len(), 1);
5699         check_spends!(spend_txn[0], closing_tx);
5700
5701         mine_transaction(&nodes[1], &closing_tx);
5702         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5703
5704         let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5705         assert_eq!(spend_txn.len(), 1);
5706         check_spends!(spend_txn[0], closing_tx);
5707 }
5708
5709 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5710         let chanmon_cfgs = create_chanmon_cfgs(2);
5711         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5712         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5713         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5714         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5715
5716         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5717
5718         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5719         // present in B's local commitment transaction, but none of A's commitment transactions.
5720         assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5721         check_added_monitors!(nodes[1], 1);
5722
5723         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5724         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5725         let events = nodes[0].node.get_and_clear_pending_events();
5726         assert_eq!(events.len(), 1);
5727         match events[0] {
5728                 Event::PaymentSent { payment_preimage } => {
5729                         assert_eq!(payment_preimage, our_payment_preimage);
5730                 },
5731                 _ => panic!("Unexpected event"),
5732         }
5733
5734         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5735         check_added_monitors!(nodes[0], 1);
5736         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5737         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5738         check_added_monitors!(nodes[1], 1);
5739
5740         let starting_block = nodes[1].best_block_info();
5741         let mut block = Block {
5742                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5743                 txdata: vec![],
5744         };
5745         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5746                 connect_block(&nodes[1], &block);
5747                 block.header.prev_blockhash = block.block_hash();
5748         }
5749         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5750         check_closed_broadcast!(nodes[1], true);
5751         check_added_monitors!(nodes[1], 1);
5752 }
5753
5754 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5755         let chanmon_cfgs = create_chanmon_cfgs(2);
5756         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5757         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5758         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5759         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5760         let logger = test_utils::TestLogger::new();
5761
5762         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5763         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5764         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();
5765         nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5766         check_added_monitors!(nodes[0], 1);
5767
5768         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5769
5770         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5771         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5772         // to "time out" the HTLC.
5773
5774         let starting_block = nodes[1].best_block_info();
5775         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5776
5777         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5778                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5779                 header.prev_blockhash = header.block_hash();
5780         }
5781         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5782         check_closed_broadcast!(nodes[0], true);
5783         check_added_monitors!(nodes[0], 1);
5784 }
5785
5786 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5787         let chanmon_cfgs = create_chanmon_cfgs(3);
5788         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5789         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5790         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5791         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5792
5793         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5794         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5795         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5796         // actually revoked.
5797         let htlc_value = if use_dust { 50000 } else { 3000000 };
5798         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5799         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5800         expect_pending_htlcs_forwardable!(nodes[1]);
5801         check_added_monitors!(nodes[1], 1);
5802
5803         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5804         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5805         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5806         check_added_monitors!(nodes[0], 1);
5807         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5808         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5809         check_added_monitors!(nodes[1], 1);
5810         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5811         check_added_monitors!(nodes[1], 1);
5812         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5813
5814         if check_revoke_no_close {
5815                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5816                 check_added_monitors!(nodes[0], 1);
5817         }
5818
5819         let starting_block = nodes[1].best_block_info();
5820         let mut block = Block {
5821                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5822                 txdata: vec![],
5823         };
5824         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5825                 connect_block(&nodes[0], &block);
5826                 block.header.prev_blockhash = block.block_hash();
5827         }
5828         if !check_revoke_no_close {
5829                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5830                 check_closed_broadcast!(nodes[0], true);
5831                 check_added_monitors!(nodes[0], 1);
5832         } else {
5833                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5834         }
5835 }
5836
5837 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5838 // There are only a few cases to test here:
5839 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5840 //    broadcastable commitment transactions result in channel closure,
5841 //  * its included in an unrevoked-but-previous remote commitment transaction,
5842 //  * its included in the latest remote or local commitment transactions.
5843 // We test each of the three possible commitment transactions individually and use both dust and
5844 // non-dust HTLCs.
5845 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5846 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5847 // tested for at least one of the cases in other tests.
5848 #[test]
5849 fn htlc_claim_single_commitment_only_a() {
5850         do_htlc_claim_local_commitment_only(true);
5851         do_htlc_claim_local_commitment_only(false);
5852
5853         do_htlc_claim_current_remote_commitment_only(true);
5854         do_htlc_claim_current_remote_commitment_only(false);
5855 }
5856
5857 #[test]
5858 fn htlc_claim_single_commitment_only_b() {
5859         do_htlc_claim_previous_remote_commitment_only(true, false);
5860         do_htlc_claim_previous_remote_commitment_only(false, false);
5861         do_htlc_claim_previous_remote_commitment_only(true, true);
5862         do_htlc_claim_previous_remote_commitment_only(false, true);
5863 }
5864
5865 #[test]
5866 #[should_panic]
5867 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5868         let chanmon_cfgs = create_chanmon_cfgs(2);
5869         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5870         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5871         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5872         //Force duplicate channel ids
5873         for node in nodes.iter() {
5874                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5875         }
5876
5877         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5878         let channel_value_satoshis=10000;
5879         let push_msat=10001;
5880         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5881         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5882         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5883
5884         //Create a second channel with a channel_id collision
5885         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5886 }
5887
5888 #[test]
5889 fn bolt2_open_channel_sending_node_checks_part2() {
5890         let chanmon_cfgs = create_chanmon_cfgs(2);
5891         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5892         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5893         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5894
5895         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5896         let channel_value_satoshis=2^24;
5897         let push_msat=10001;
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 push_msat to equal or less than 1000 * funding_satoshis
5901         let channel_value_satoshis=10000;
5902         // Test when push_msat is equal to 1000 * funding_satoshis.
5903         let push_msat=1000*channel_value_satoshis+1;
5904         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5905
5906         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5907         let channel_value_satoshis=10000;
5908         let push_msat=10001;
5909         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
5910         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5911         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5912
5913         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5914         // 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
5915         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5916
5917         // 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.
5918         assert!(BREAKDOWN_TIMEOUT>0);
5919         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5920
5921         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5922         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5923         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5924
5925         // 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.
5926         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5927         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5928         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5929         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5930         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5931 }
5932
5933 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5934 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5935 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5936 // is no longer affordable once it's freed.
5937 #[test]
5938 fn test_fail_holding_cell_htlc_upon_free() {
5939         let chanmon_cfgs = create_chanmon_cfgs(2);
5940         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5941         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5942         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5943         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5944         let logger = test_utils::TestLogger::new();
5945
5946         // First nodes[0] generates an update_fee, setting the channel's
5947         // pending_update_fee.
5948         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
5949         check_added_monitors!(nodes[0], 1);
5950
5951         let events = nodes[0].node.get_and_clear_pending_msg_events();
5952         assert_eq!(events.len(), 1);
5953         let (update_msg, commitment_signed) = match events[0] {
5954                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5955                         (update_fee.as_ref(), commitment_signed)
5956                 },
5957                 _ => panic!("Unexpected event"),
5958         };
5959
5960         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5961
5962         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5963         let channel_reserve = chan_stat.channel_reserve_msat;
5964         let feerate = get_feerate!(nodes[0], chan.2);
5965
5966         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5967         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5968         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5969         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5970         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();
5971
5972         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5973         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5974         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5975         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5976
5977         // Flush the pending fee update.
5978         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5979         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5980         check_added_monitors!(nodes[1], 1);
5981         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5982         check_added_monitors!(nodes[0], 1);
5983
5984         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5985         // HTLC, but now that the fee has been raised the payment will now fail, causing
5986         // us to surface its failure to the user.
5987         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5988         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5989         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
5990         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);
5991         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5992
5993         // Check that the payment failed to be sent out.
5994         let events = nodes[0].node.get_and_clear_pending_events();
5995         assert_eq!(events.len(), 1);
5996         match &events[0] {
5997                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
5998                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5999                         assert_eq!(*rejected_by_dest, false);
6000                         assert_eq!(*error_code, None);
6001                         assert_eq!(*error_data, None);
6002                 },
6003                 _ => panic!("Unexpected event"),
6004         }
6005 }
6006
6007 // Test that if multiple HTLCs are released from the holding cell and one is
6008 // valid but the other is no longer valid upon release, the valid HTLC can be
6009 // successfully completed while the other one fails as expected.
6010 #[test]
6011 fn test_free_and_fail_holding_cell_htlcs() {
6012         let chanmon_cfgs = create_chanmon_cfgs(2);
6013         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6014         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6015         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6016         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6017         let logger = test_utils::TestLogger::new();
6018
6019         // First nodes[0] generates an update_fee, setting the channel's
6020         // pending_update_fee.
6021         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6022         check_added_monitors!(nodes[0], 1);
6023
6024         let events = nodes[0].node.get_and_clear_pending_msg_events();
6025         assert_eq!(events.len(), 1);
6026         let (update_msg, commitment_signed) = match events[0] {
6027                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6028                         (update_fee.as_ref(), commitment_signed)
6029                 },
6030                 _ => panic!("Unexpected event"),
6031         };
6032
6033         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6034
6035         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6036         let channel_reserve = chan_stat.channel_reserve_msat;
6037         let feerate = get_feerate!(nodes[0], chan.2);
6038
6039         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6040         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6041         let amt_1 = 20000;
6042         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6043         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6044         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6045         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();
6046         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();
6047
6048         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6049         nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6050         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6051         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6052         nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6053         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6054         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6055
6056         // Flush the pending fee update.
6057         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6058         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6059         check_added_monitors!(nodes[1], 1);
6060         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6061         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6062         check_added_monitors!(nodes[0], 2);
6063
6064         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6065         // but now that the fee has been raised the second payment will now fail, causing us
6066         // to surface its failure to the user. The first payment should succeed.
6067         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6068         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6069         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6070         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);
6071         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6072
6073         // Check that the second payment failed to be sent out.
6074         let events = nodes[0].node.get_and_clear_pending_events();
6075         assert_eq!(events.len(), 1);
6076         match &events[0] {
6077                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6078                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6079                         assert_eq!(*rejected_by_dest, false);
6080                         assert_eq!(*error_code, None);
6081                         assert_eq!(*error_data, None);
6082                 },
6083                 _ => panic!("Unexpected event"),
6084         }
6085
6086         // Complete the first payment and the RAA from the fee update.
6087         let (payment_event, send_raa_event) = {
6088                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6089                 assert_eq!(msgs.len(), 2);
6090                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6091         };
6092         let raa = match send_raa_event {
6093                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6094                 _ => panic!("Unexpected event"),
6095         };
6096         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6097         check_added_monitors!(nodes[1], 1);
6098         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6099         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6100         let events = nodes[1].node.get_and_clear_pending_events();
6101         assert_eq!(events.len(), 1);
6102         match events[0] {
6103                 Event::PendingHTLCsForwardable { .. } => {},
6104                 _ => panic!("Unexpected event"),
6105         }
6106         nodes[1].node.process_pending_htlc_forwards();
6107         let events = nodes[1].node.get_and_clear_pending_events();
6108         assert_eq!(events.len(), 1);
6109         match events[0] {
6110                 Event::PaymentReceived { .. } => {},
6111                 _ => panic!("Unexpected event"),
6112         }
6113         nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6114         check_added_monitors!(nodes[1], 1);
6115         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6116         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6117         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6118         let events = nodes[0].node.get_and_clear_pending_events();
6119         assert_eq!(events.len(), 1);
6120         match events[0] {
6121                 Event::PaymentSent { ref payment_preimage } => {
6122                         assert_eq!(*payment_preimage, payment_preimage_1);
6123                 }
6124                 _ => panic!("Unexpected event"),
6125         }
6126 }
6127
6128 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6129 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6130 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6131 // once it's freed.
6132 #[test]
6133 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6134         let chanmon_cfgs = create_chanmon_cfgs(3);
6135         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6136         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6137         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6138         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6139         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6140         let logger = test_utils::TestLogger::new();
6141
6142         // First nodes[1] generates an update_fee, setting the channel's
6143         // pending_update_fee.
6144         nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6145         check_added_monitors!(nodes[1], 1);
6146
6147         let events = nodes[1].node.get_and_clear_pending_msg_events();
6148         assert_eq!(events.len(), 1);
6149         let (update_msg, commitment_signed) = match events[0] {
6150                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6151                         (update_fee.as_ref(), commitment_signed)
6152                 },
6153                 _ => panic!("Unexpected event"),
6154         };
6155
6156         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6157
6158         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6159         let channel_reserve = chan_stat.channel_reserve_msat;
6160         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6161
6162         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6163         let feemsat = 239;
6164         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6165         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6166         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6167         let payment_event = {
6168                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6169                 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();
6170                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6171                 check_added_monitors!(nodes[0], 1);
6172
6173                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6174                 assert_eq!(events.len(), 1);
6175
6176                 SendEvent::from_event(events.remove(0))
6177         };
6178         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6179         check_added_monitors!(nodes[1], 0);
6180         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6181         expect_pending_htlcs_forwardable!(nodes[1]);
6182
6183         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6184         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6185
6186         // Flush the pending fee update.
6187         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6188         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6189         check_added_monitors!(nodes[2], 1);
6190         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6191         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6192         check_added_monitors!(nodes[1], 2);
6193
6194         // A final RAA message is generated to finalize the fee update.
6195         let events = nodes[1].node.get_and_clear_pending_msg_events();
6196         assert_eq!(events.len(), 1);
6197
6198         let raa_msg = match &events[0] {
6199                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6200                         msg.clone()
6201                 },
6202                 _ => panic!("Unexpected event"),
6203         };
6204
6205         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6206         check_added_monitors!(nodes[2], 1);
6207         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6208
6209         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6210         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6211         assert_eq!(process_htlc_forwards_event.len(), 1);
6212         match &process_htlc_forwards_event[0] {
6213                 &Event::PendingHTLCsForwardable { .. } => {},
6214                 _ => panic!("Unexpected event"),
6215         }
6216
6217         // In response, we call ChannelManager's process_pending_htlc_forwards
6218         nodes[1].node.process_pending_htlc_forwards();
6219         check_added_monitors!(nodes[1], 1);
6220
6221         // This causes the HTLC to be failed backwards.
6222         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6223         assert_eq!(fail_event.len(), 1);
6224         let (fail_msg, commitment_signed) = match &fail_event[0] {
6225                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6226                         assert_eq!(updates.update_add_htlcs.len(), 0);
6227                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6228                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6229                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6230                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6231                 },
6232                 _ => panic!("Unexpected event"),
6233         };
6234
6235         // Pass the failure messages back to nodes[0].
6236         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6237         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6238
6239         // Complete the HTLC failure+removal process.
6240         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6241         check_added_monitors!(nodes[0], 1);
6242         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6243         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6244         check_added_monitors!(nodes[1], 2);
6245         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6246         assert_eq!(final_raa_event.len(), 1);
6247         let raa = match &final_raa_event[0] {
6248                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6249                 _ => panic!("Unexpected event"),
6250         };
6251         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6252         let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6253         assert_eq!(fail_msg_event.len(), 1);
6254         match &fail_msg_event[0] {
6255                 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6256                 _ => panic!("Unexpected event"),
6257         }
6258         let failure_event = nodes[0].node.get_and_clear_pending_events();
6259         assert_eq!(failure_event.len(), 1);
6260         match &failure_event[0] {
6261                 &Event::PaymentFailed { rejected_by_dest, .. } => {
6262                         assert!(!rejected_by_dest);
6263                 },
6264                 _ => panic!("Unexpected event"),
6265         }
6266         check_added_monitors!(nodes[0], 1);
6267 }
6268
6269 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6270 // 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.
6271 //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.
6272
6273 #[test]
6274 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6275         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6276         let chanmon_cfgs = create_chanmon_cfgs(2);
6277         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6278         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6279         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6280         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6281
6282         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6283         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6284         let logger = test_utils::TestLogger::new();
6285         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();
6286         route.paths[0][0].fee_msat = 100;
6287
6288         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6289                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6290         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6291         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6292 }
6293
6294 #[test]
6295 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6296         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6297         let chanmon_cfgs = create_chanmon_cfgs(2);
6298         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6299         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6300         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6301         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6302         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6303
6304         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6305         let logger = test_utils::TestLogger::new();
6306         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();
6307         route.paths[0][0].fee_msat = 0;
6308         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6309                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6310
6311         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6312         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6313 }
6314
6315 #[test]
6316 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6317         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6318         let chanmon_cfgs = create_chanmon_cfgs(2);
6319         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6320         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6321         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6322         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6323
6324         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6325         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6326         let logger = test_utils::TestLogger::new();
6327         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();
6328         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6329         check_added_monitors!(nodes[0], 1);
6330         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6331         updates.update_add_htlcs[0].amount_msat = 0;
6332
6333         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6334         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6335         check_closed_broadcast!(nodes[1], true).unwrap();
6336         check_added_monitors!(nodes[1], 1);
6337 }
6338
6339 #[test]
6340 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6341         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6342         //It is enforced when constructing a route.
6343         let chanmon_cfgs = create_chanmon_cfgs(2);
6344         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6345         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6346         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6347         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6348         let logger = test_utils::TestLogger::new();
6349
6350         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6351
6352         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6353         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();
6354         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6355                 assert_eq!(err, &"Channel CLTV overflowed?"));
6356 }
6357
6358 #[test]
6359 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6360         //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.
6361         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6362         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6363         let chanmon_cfgs = create_chanmon_cfgs(2);
6364         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6365         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6366         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6367         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6368         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6369
6370         let logger = test_utils::TestLogger::new();
6371         for i in 0..max_accepted_htlcs {
6372                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6373                 let payment_event = {
6374                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6375                         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();
6376                         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6377                         check_added_monitors!(nodes[0], 1);
6378
6379                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6380                         assert_eq!(events.len(), 1);
6381                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6382                                 assert_eq!(htlcs[0].htlc_id, i);
6383                         } else {
6384                                 assert!(false);
6385                         }
6386                         SendEvent::from_event(events.remove(0))
6387                 };
6388                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6389                 check_added_monitors!(nodes[1], 0);
6390                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6391
6392                 expect_pending_htlcs_forwardable!(nodes[1]);
6393                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6394         }
6395         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6396         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6397         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();
6398         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6399                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6400
6401         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6402         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6403 }
6404
6405 #[test]
6406 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6407         //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.
6408         let chanmon_cfgs = create_chanmon_cfgs(2);
6409         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6410         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6411         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6412         let channel_value = 100000;
6413         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6414         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6415
6416         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6417
6418         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6419         // Manually create a route over our max in flight (which our router normally automatically
6420         // limits us to.
6421         let route = Route { paths: vec![vec![RouteHop {
6422            pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6423            short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6424            fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6425         }]] };
6426         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6427                 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)));
6428
6429         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6430         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);
6431
6432         send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6433 }
6434
6435 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6436 #[test]
6437 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6438         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6439         let chanmon_cfgs = create_chanmon_cfgs(2);
6440         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6441         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6442         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6443         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6444         let htlc_minimum_msat: u64;
6445         {
6446                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6447                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6448                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6449         }
6450
6451         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6452         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6453         let logger = test_utils::TestLogger::new();
6454         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();
6455         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6456         check_added_monitors!(nodes[0], 1);
6457         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6458         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6459         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6460         assert!(nodes[1].node.list_channels().is_empty());
6461         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6462         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()));
6463         check_added_monitors!(nodes[1], 1);
6464 }
6465
6466 #[test]
6467 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6468         //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
6469         let chanmon_cfgs = create_chanmon_cfgs(2);
6470         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6471         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6472         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6473         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6474         let logger = test_utils::TestLogger::new();
6475
6476         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6477         let channel_reserve = chan_stat.channel_reserve_msat;
6478         let feerate = get_feerate!(nodes[0], chan.2);
6479         // The 2* and +1 are for the fee spike reserve.
6480         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6481
6482         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6483         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6484         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6485         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();
6486         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6487         check_added_monitors!(nodes[0], 1);
6488         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6489
6490         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6491         // at this time channel-initiatee receivers are not required to enforce that senders
6492         // respect the fee_spike_reserve.
6493         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6494         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6495
6496         assert!(nodes[1].node.list_channels().is_empty());
6497         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6498         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6499         check_added_monitors!(nodes[1], 1);
6500 }
6501
6502 #[test]
6503 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6504         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6505         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6506         let chanmon_cfgs = create_chanmon_cfgs(2);
6507         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6508         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6509         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6510         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6511         let logger = test_utils::TestLogger::new();
6512
6513         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6514         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6515
6516         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6517         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();
6518
6519         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6520         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6521         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6522         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6523
6524         let mut msg = msgs::UpdateAddHTLC {
6525                 channel_id: chan.2,
6526                 htlc_id: 0,
6527                 amount_msat: 1000,
6528                 payment_hash: our_payment_hash,
6529                 cltv_expiry: htlc_cltv,
6530                 onion_routing_packet: onion_packet.clone(),
6531         };
6532
6533         for i in 0..super::channel::OUR_MAX_HTLCS {
6534                 msg.htlc_id = i as u64;
6535                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6536         }
6537         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6538         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6539
6540         assert!(nodes[1].node.list_channels().is_empty());
6541         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6542         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6543         check_added_monitors!(nodes[1], 1);
6544 }
6545
6546 #[test]
6547 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6548         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6549         let chanmon_cfgs = create_chanmon_cfgs(2);
6550         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6551         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6552         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6553         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6554         let logger = test_utils::TestLogger::new();
6555
6556         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6557         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6558         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();
6559         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6560         check_added_monitors!(nodes[0], 1);
6561         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6562         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6563         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6564
6565         assert!(nodes[1].node.list_channels().is_empty());
6566         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6567         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6568         check_added_monitors!(nodes[1], 1);
6569 }
6570
6571 #[test]
6572 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6573         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6574         let chanmon_cfgs = create_chanmon_cfgs(2);
6575         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6576         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6577         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6578         let logger = test_utils::TestLogger::new();
6579
6580         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6581         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6582         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6583         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();
6584         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6585         check_added_monitors!(nodes[0], 1);
6586         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6587         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6588         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6589
6590         assert!(nodes[1].node.list_channels().is_empty());
6591         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6592         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6593         check_added_monitors!(nodes[1], 1);
6594 }
6595
6596 #[test]
6597 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6598         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6599         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6600         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6601         let chanmon_cfgs = create_chanmon_cfgs(2);
6602         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6603         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6604         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6605         let logger = test_utils::TestLogger::new();
6606
6607         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6608         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6609         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6610         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();
6611         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6612         check_added_monitors!(nodes[0], 1);
6613         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6614         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6615
6616         //Disconnect and Reconnect
6617         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6618         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6619         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6620         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6621         assert_eq!(reestablish_1.len(), 1);
6622         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6623         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6624         assert_eq!(reestablish_2.len(), 1);
6625         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6626         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6627         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6628         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6629
6630         //Resend HTLC
6631         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6632         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6633         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6634         check_added_monitors!(nodes[1], 1);
6635         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6636
6637         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6638
6639         assert!(nodes[1].node.list_channels().is_empty());
6640         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6641         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6642         check_added_monitors!(nodes[1], 1);
6643 }
6644
6645 #[test]
6646 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6647         //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.
6648
6649         let chanmon_cfgs = create_chanmon_cfgs(2);
6650         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6651         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6652         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6653         let logger = test_utils::TestLogger::new();
6654         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6655         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6656         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6657         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();
6658         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6659
6660         check_added_monitors!(nodes[0], 1);
6661         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6662         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6663
6664         let update_msg = msgs::UpdateFulfillHTLC{
6665                 channel_id: chan.2,
6666                 htlc_id: 0,
6667                 payment_preimage: our_payment_preimage,
6668         };
6669
6670         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6671
6672         assert!(nodes[0].node.list_channels().is_empty());
6673         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6674         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()));
6675         check_added_monitors!(nodes[0], 1);
6676 }
6677
6678 #[test]
6679 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6680         //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.
6681
6682         let chanmon_cfgs = create_chanmon_cfgs(2);
6683         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6684         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6685         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6686         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6687         let logger = test_utils::TestLogger::new();
6688
6689         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6690         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6691         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();
6692         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6693         check_added_monitors!(nodes[0], 1);
6694         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6695         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6696
6697         let update_msg = msgs::UpdateFailHTLC{
6698                 channel_id: chan.2,
6699                 htlc_id: 0,
6700                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6701         };
6702
6703         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6704
6705         assert!(nodes[0].node.list_channels().is_empty());
6706         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6707         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()));
6708         check_added_monitors!(nodes[0], 1);
6709 }
6710
6711 #[test]
6712 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6713         //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.
6714
6715         let chanmon_cfgs = create_chanmon_cfgs(2);
6716         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6717         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6718         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6719         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6720         let logger = test_utils::TestLogger::new();
6721
6722         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6723         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6724         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();
6725         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6726         check_added_monitors!(nodes[0], 1);
6727         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6728         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6729         let update_msg = msgs::UpdateFailMalformedHTLC{
6730                 channel_id: chan.2,
6731                 htlc_id: 0,
6732                 sha256_of_onion: [1; 32],
6733                 failure_code: 0x8000,
6734         };
6735
6736         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6737
6738         assert!(nodes[0].node.list_channels().is_empty());
6739         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6740         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()));
6741         check_added_monitors!(nodes[0], 1);
6742 }
6743
6744 #[test]
6745 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6746         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6747
6748         let chanmon_cfgs = create_chanmon_cfgs(2);
6749         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6750         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6751         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6752         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6753
6754         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6755
6756         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6757         check_added_monitors!(nodes[1], 1);
6758
6759         let events = nodes[1].node.get_and_clear_pending_msg_events();
6760         assert_eq!(events.len(), 1);
6761         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6762                 match events[0] {
6763                         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, .. } } => {
6764                                 assert!(update_add_htlcs.is_empty());
6765                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6766                                 assert!(update_fail_htlcs.is_empty());
6767                                 assert!(update_fail_malformed_htlcs.is_empty());
6768                                 assert!(update_fee.is_none());
6769                                 update_fulfill_htlcs[0].clone()
6770                         },
6771                         _ => panic!("Unexpected event"),
6772                 }
6773         };
6774
6775         update_fulfill_msg.htlc_id = 1;
6776
6777         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6778
6779         assert!(nodes[0].node.list_channels().is_empty());
6780         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6781         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6782         check_added_monitors!(nodes[0], 1);
6783 }
6784
6785 #[test]
6786 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6787         //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.
6788
6789         let chanmon_cfgs = create_chanmon_cfgs(2);
6790         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6791         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6792         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6793         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6794
6795         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6796
6797         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6798         check_added_monitors!(nodes[1], 1);
6799
6800         let events = nodes[1].node.get_and_clear_pending_msg_events();
6801         assert_eq!(events.len(), 1);
6802         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6803                 match events[0] {
6804                         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, .. } } => {
6805                                 assert!(update_add_htlcs.is_empty());
6806                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6807                                 assert!(update_fail_htlcs.is_empty());
6808                                 assert!(update_fail_malformed_htlcs.is_empty());
6809                                 assert!(update_fee.is_none());
6810                                 update_fulfill_htlcs[0].clone()
6811                         },
6812                         _ => panic!("Unexpected event"),
6813                 }
6814         };
6815
6816         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6817
6818         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6819
6820         assert!(nodes[0].node.list_channels().is_empty());
6821         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6822         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6823         check_added_monitors!(nodes[0], 1);
6824 }
6825
6826 #[test]
6827 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6828         //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.
6829
6830         let chanmon_cfgs = create_chanmon_cfgs(2);
6831         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6832         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6833         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6834         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6835         let logger = test_utils::TestLogger::new();
6836
6837         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6838         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6839         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();
6840         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6841         check_added_monitors!(nodes[0], 1);
6842
6843         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6844         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6845
6846         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6847         check_added_monitors!(nodes[1], 0);
6848         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6849
6850         let events = nodes[1].node.get_and_clear_pending_msg_events();
6851
6852         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6853                 match events[0] {
6854                         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, .. } } => {
6855                                 assert!(update_add_htlcs.is_empty());
6856                                 assert!(update_fulfill_htlcs.is_empty());
6857                                 assert!(update_fail_htlcs.is_empty());
6858                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6859                                 assert!(update_fee.is_none());
6860                                 update_fail_malformed_htlcs[0].clone()
6861                         },
6862                         _ => panic!("Unexpected event"),
6863                 }
6864         };
6865         update_msg.failure_code &= !0x8000;
6866         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6867
6868         assert!(nodes[0].node.list_channels().is_empty());
6869         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6870         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6871         check_added_monitors!(nodes[0], 1);
6872 }
6873
6874 #[test]
6875 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6876         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6877         //    * 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.
6878
6879         let chanmon_cfgs = create_chanmon_cfgs(3);
6880         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6881         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6882         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6883         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6884         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6885         let logger = test_utils::TestLogger::new();
6886
6887         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6888
6889         //First hop
6890         let mut payment_event = {
6891                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6892                 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();
6893                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6894                 check_added_monitors!(nodes[0], 1);
6895                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6896                 assert_eq!(events.len(), 1);
6897                 SendEvent::from_event(events.remove(0))
6898         };
6899         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6900         check_added_monitors!(nodes[1], 0);
6901         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6902         expect_pending_htlcs_forwardable!(nodes[1]);
6903         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6904         assert_eq!(events_2.len(), 1);
6905         check_added_monitors!(nodes[1], 1);
6906         payment_event = SendEvent::from_event(events_2.remove(0));
6907         assert_eq!(payment_event.msgs.len(), 1);
6908
6909         //Second Hop
6910         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6911         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6912         check_added_monitors!(nodes[2], 0);
6913         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6914
6915         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6916         assert_eq!(events_3.len(), 1);
6917         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6918                 match events_3[0] {
6919                         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 } } => {
6920                                 assert!(update_add_htlcs.is_empty());
6921                                 assert!(update_fulfill_htlcs.is_empty());
6922                                 assert!(update_fail_htlcs.is_empty());
6923                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6924                                 assert!(update_fee.is_none());
6925                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6926                         },
6927                         _ => panic!("Unexpected event"),
6928                 }
6929         };
6930
6931         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6932
6933         check_added_monitors!(nodes[1], 0);
6934         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6935         expect_pending_htlcs_forwardable!(nodes[1]);
6936         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6937         assert_eq!(events_4.len(), 1);
6938
6939         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6940         match events_4[0] {
6941                 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, .. } } => {
6942                         assert!(update_add_htlcs.is_empty());
6943                         assert!(update_fulfill_htlcs.is_empty());
6944                         assert_eq!(update_fail_htlcs.len(), 1);
6945                         assert!(update_fail_malformed_htlcs.is_empty());
6946                         assert!(update_fee.is_none());
6947                 },
6948                 _ => panic!("Unexpected event"),
6949         };
6950
6951         check_added_monitors!(nodes[1], 1);
6952 }
6953
6954 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6955         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6956         // 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
6957         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6958
6959         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6960         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6961         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6962         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6963         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6964         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6965
6966         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6967
6968         // We route 2 dust-HTLCs between A and B
6969         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6970         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6971         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6972
6973         // Cache one local commitment tx as previous
6974         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6975
6976         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6977         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
6978         check_added_monitors!(nodes[1], 0);
6979         expect_pending_htlcs_forwardable!(nodes[1]);
6980         check_added_monitors!(nodes[1], 1);
6981
6982         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6983         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6984         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6985         check_added_monitors!(nodes[0], 1);
6986
6987         // Cache one local commitment tx as lastest
6988         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6989
6990         let events = nodes[0].node.get_and_clear_pending_msg_events();
6991         match events[0] {
6992                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6993                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6994                 },
6995                 _ => panic!("Unexpected event"),
6996         }
6997         match events[1] {
6998                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6999                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7000                 },
7001                 _ => panic!("Unexpected event"),
7002         }
7003
7004         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7005         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7006         if announce_latest {
7007                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7008         } else {
7009                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7010         }
7011
7012         check_closed_broadcast!(nodes[0], true);
7013         check_added_monitors!(nodes[0], 1);
7014
7015         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7016         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7017         let events = nodes[0].node.get_and_clear_pending_events();
7018         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7019         assert_eq!(events.len(), 2);
7020         let mut first_failed = false;
7021         for event in events {
7022                 match event {
7023                         Event::PaymentFailed { payment_hash, .. } => {
7024                                 if payment_hash == payment_hash_1 {
7025                                         assert!(!first_failed);
7026                                         first_failed = true;
7027                                 } else {
7028                                         assert_eq!(payment_hash, payment_hash_2);
7029                                 }
7030                         }
7031                         _ => panic!("Unexpected event"),
7032                 }
7033         }
7034 }
7035
7036 #[test]
7037 fn test_failure_delay_dust_htlc_local_commitment() {
7038         do_test_failure_delay_dust_htlc_local_commitment(true);
7039         do_test_failure_delay_dust_htlc_local_commitment(false);
7040 }
7041
7042 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7043         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7044         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7045         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7046         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7047         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7048         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7049
7050         let chanmon_cfgs = create_chanmon_cfgs(3);
7051         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7052         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7053         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7054         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7055
7056         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7057
7058         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7059         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7060
7061         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7062         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7063
7064         // We revoked bs_commitment_tx
7065         if revoked {
7066                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7067                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7068         }
7069
7070         let mut timeout_tx = Vec::new();
7071         if local {
7072                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7073                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7074                 check_closed_broadcast!(nodes[0], true);
7075                 check_added_monitors!(nodes[0], 1);
7076                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7077                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7078                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7079                 expect_payment_failed!(nodes[0], dust_hash, true);
7080                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7081                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7082                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7083                 mine_transaction(&nodes[0], &timeout_tx[0]);
7084                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7085                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7086         } else {
7087                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7088                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7089                 check_closed_broadcast!(nodes[0], true);
7090                 check_added_monitors!(nodes[0], 1);
7091                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7092                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7093                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7094                 if !revoked {
7095                         expect_payment_failed!(nodes[0], dust_hash, true);
7096                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7097                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7098                         mine_transaction(&nodes[0], &timeout_tx[0]);
7099                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7100                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7101                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7102                 } else {
7103                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7104                         // commitment tx
7105                         let events = nodes[0].node.get_and_clear_pending_events();
7106                         assert_eq!(events.len(), 2);
7107                         let first;
7108                         match events[0] {
7109                                 Event::PaymentFailed { payment_hash, .. } => {
7110                                         if payment_hash == dust_hash { first = true; }
7111                                         else { first = false; }
7112                                 },
7113                                 _ => panic!("Unexpected event"),
7114                         }
7115                         match events[1] {
7116                                 Event::PaymentFailed { payment_hash, .. } => {
7117                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7118                                         else { assert_eq!(payment_hash, dust_hash); }
7119                                 },
7120                                 _ => panic!("Unexpected event"),
7121                         }
7122                 }
7123         }
7124 }
7125
7126 #[test]
7127 fn test_sweep_outbound_htlc_failure_update() {
7128         do_test_sweep_outbound_htlc_failure_update(false, true);
7129         do_test_sweep_outbound_htlc_failure_update(false, false);
7130         do_test_sweep_outbound_htlc_failure_update(true, false);
7131 }
7132
7133 #[test]
7134 fn test_upfront_shutdown_script() {
7135         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7136         // enforce it at shutdown message
7137
7138         let mut config = UserConfig::default();
7139         config.channel_options.announced_channel = true;
7140         config.peer_channel_config_limits.force_announced_channel_preference = false;
7141         config.channel_options.commit_upfront_shutdown_pubkey = false;
7142         let user_cfgs = [None, Some(config), None];
7143         let chanmon_cfgs = create_chanmon_cfgs(3);
7144         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7145         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7146         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7147
7148         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7149         let flags = InitFeatures::known();
7150         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7151         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7152         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7153         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7154         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
7155         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7156     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()));
7157         check_added_monitors!(nodes[2], 1);
7158
7159         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7160         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7161         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7162         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7163         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7164         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7165         let events = nodes[2].node.get_and_clear_pending_msg_events();
7166         assert_eq!(events.len(), 1);
7167         match events[0] {
7168                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7169                 _ => panic!("Unexpected event"),
7170         }
7171
7172         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7173         let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7174         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7175         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7176         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7177         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7178         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
7179         let events = nodes[1].node.get_and_clear_pending_msg_events();
7180         assert_eq!(events.len(), 1);
7181         match events[0] {
7182                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7183                 _ => panic!("Unexpected event"),
7184         }
7185
7186         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7187         // channel smoothly, opt-out is from channel initiator here
7188         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7189         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7190         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7191         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7192         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7193         let events = nodes[0].node.get_and_clear_pending_msg_events();
7194         assert_eq!(events.len(), 1);
7195         match events[0] {
7196                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7197                 _ => panic!("Unexpected event"),
7198         }
7199
7200         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7201         //// channel smoothly
7202         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7203         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7204         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7205         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7206         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7207         let events = nodes[0].node.get_and_clear_pending_msg_events();
7208         assert_eq!(events.len(), 2);
7209         match events[0] {
7210                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7211                 _ => panic!("Unexpected event"),
7212         }
7213         match events[1] {
7214                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7215                 _ => panic!("Unexpected event"),
7216         }
7217 }
7218
7219 #[test]
7220 fn test_upfront_shutdown_script_unsupport_segwit() {
7221         // We test that channel is closed early
7222         // if a segwit program is passed as upfront shutdown script,
7223         // but the peer does not support segwit.
7224         let chanmon_cfgs = create_chanmon_cfgs(2);
7225         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7226         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7227         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7228
7229         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
7230
7231         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7232         open_channel.shutdown_scriptpubkey = Present(Builder::new().push_int(16)
7233                 .push_slice(&[0, 0])
7234                 .into_script());
7235
7236         let features = InitFeatures::known().clear_shutdown_anysegwit();
7237         nodes[0].node.handle_open_channel(&nodes[0].node.get_our_node_id(), features, &open_channel);
7238
7239         let events = nodes[0].node.get_and_clear_pending_msg_events();
7240         assert_eq!(events.len(), 1);
7241         match events[0] {
7242                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7243                         assert_eq!(node_id, nodes[0].node.get_our_node_id());
7244                         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));
7245                 },
7246                 _ => panic!("Unexpected event"),
7247         }
7248 }
7249
7250 #[test]
7251 fn test_shutdown_script_any_segwit_allowed() {
7252         let mut config = UserConfig::default();
7253         config.channel_options.announced_channel = true;
7254         config.peer_channel_config_limits.force_announced_channel_preference = false;
7255         config.channel_options.commit_upfront_shutdown_pubkey = false;
7256         let user_cfgs = [None, Some(config), None];
7257         let chanmon_cfgs = create_chanmon_cfgs(3);
7258         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7259         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7260         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7261
7262         //// We test if the remote peer accepts opt_shutdown_anysegwit, a witness program can be used on shutdown
7263         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7264         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7265         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7266         node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7267                 .push_slice(&[0, 0])
7268                 .into_script();
7269         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7270         let events = nodes[0].node.get_and_clear_pending_msg_events();
7271         assert_eq!(events.len(), 2);
7272         match events[0] {
7273                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7274                 _ => panic!("Unexpected event"),
7275         }
7276         match events[1] {
7277                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7278                 _ => panic!("Unexpected event"),
7279         }
7280 }
7281
7282 #[test]
7283 fn test_shutdown_script_any_segwit_not_allowed() {
7284         let mut config = UserConfig::default();
7285         config.channel_options.announced_channel = true;
7286         config.peer_channel_config_limits.force_announced_channel_preference = false;
7287         config.channel_options.commit_upfront_shutdown_pubkey = false;
7288         let user_cfgs = [None, Some(config), None];
7289         let chanmon_cfgs = create_chanmon_cfgs(3);
7290         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7291         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7292         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7293
7294         //// We test that if the remote peer does not accept opt_shutdown_anysegwit, the witness program cannot be used on shutdown
7295         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7296         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7297         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7298         // Make an any segwit version script
7299         node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7300                 .push_slice(&[0, 0])
7301                 .into_script();
7302         let flags_no = InitFeatures::known().clear_shutdown_anysegwit();
7303         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &flags_no, &node_0_shutdown);
7304         let events = nodes[0].node.get_and_clear_pending_msg_events();
7305         assert_eq!(events.len(), 2);
7306         match events[1] {
7307                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7308                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7309                         assert_eq!(msg.data, "Got a nonstandard scriptpubkey (60020000) from remote peer".to_owned())
7310                 },
7311                 _ => panic!("Unexpected event"),
7312         }
7313         check_added_monitors!(nodes[0], 1);
7314 }
7315
7316 #[test]
7317 fn test_shutdown_script_segwit_but_not_anysegwit() {
7318         let mut config = UserConfig::default();
7319         config.channel_options.announced_channel = true;
7320         config.peer_channel_config_limits.force_announced_channel_preference = false;
7321         config.channel_options.commit_upfront_shutdown_pubkey = false;
7322         let user_cfgs = [None, Some(config), None];
7323         let chanmon_cfgs = create_chanmon_cfgs(3);
7324         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7325         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7326         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7327
7328         //// We test that if shutdown any segwit is supported and we send a witness script with 0 version, this is not accepted
7329         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7330         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7331         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7332         // Make a segwit script that is not a valid as any segwit
7333         node_0_shutdown.scriptpubkey = Builder::new().push_int(0)
7334                 .push_slice(&[0, 0])
7335                 .into_script();
7336         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7337         let events = nodes[0].node.get_and_clear_pending_msg_events();
7338         assert_eq!(events.len(), 2);
7339         match events[1] {
7340                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7341                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7342                         assert_eq!(msg.data, "Got a nonstandard scriptpubkey (00020000) from remote peer".to_owned())
7343                 },
7344                 _ => panic!("Unexpected event"),
7345         }
7346         check_added_monitors!(nodes[0], 1);
7347 }
7348
7349 #[test]
7350 fn test_user_configurable_csv_delay() {
7351         // We test our channel constructors yield errors when we pass them absurd csv delay
7352
7353         let mut low_our_to_self_config = UserConfig::default();
7354         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7355         let mut high_their_to_self_config = UserConfig::default();
7356         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7357         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7358         let chanmon_cfgs = create_chanmon_cfgs(2);
7359         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7360         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7361         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7362
7363         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7364         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) {
7365                 match error {
7366                         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())); },
7367                         _ => panic!("Unexpected event"),
7368                 }
7369         } else { assert!(false) }
7370
7371         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7372         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7373         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7374         open_channel.to_self_delay = 200;
7375         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) {
7376                 match error {
7377                         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()));  },
7378                         _ => panic!("Unexpected event"),
7379                 }
7380         } else { assert!(false); }
7381
7382         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7383         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7384         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()));
7385         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7386         accept_channel.to_self_delay = 200;
7387         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7388         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7389                 match action {
7390                         &ErrorAction::SendErrorMessage { ref msg } => {
7391                                 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()));
7392                         },
7393                         _ => { assert!(false); }
7394                 }
7395         } else { assert!(false); }
7396
7397         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7398         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7399         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7400         open_channel.to_self_delay = 200;
7401         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) {
7402                 match error {
7403                         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())); },
7404                         _ => panic!("Unexpected event"),
7405                 }
7406         } else { assert!(false); }
7407 }
7408
7409 #[test]
7410 fn test_data_loss_protect() {
7411         // We want to be sure that :
7412         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7413         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7414         // * we close channel in case of detecting other being fallen behind
7415         // * we are able to claim our own outputs thanks to to_remote being static
7416         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7417         let persister;
7418         let logger;
7419         let fee_estimator;
7420         let tx_broadcaster;
7421         let chain_source;
7422         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7423         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7424         // during signing due to revoked tx
7425         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7426         let keys_manager = &chanmon_cfgs[0].keys_manager;
7427         let monitor;
7428         let node_state_0;
7429         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7430         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7431         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7432
7433         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7434
7435         // Cache node A state before any channel update
7436         let previous_node_state = nodes[0].node.encode();
7437         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7438         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7439
7440         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7441         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7442
7443         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7444         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7445
7446         // Restore node A from previous state
7447         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7448         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7449         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7450         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7451         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7452         persister = test_utils::TestPersister::new();
7453         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7454         node_state_0 = {
7455                 let mut channel_monitors = HashMap::new();
7456                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7457                 <(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 {
7458                         keys_manager: keys_manager,
7459                         fee_estimator: &fee_estimator,
7460                         chain_monitor: &monitor,
7461                         logger: &logger,
7462                         tx_broadcaster: &tx_broadcaster,
7463                         default_config: UserConfig::default(),
7464                         channel_monitors,
7465                 }).unwrap().1
7466         };
7467         nodes[0].node = &node_state_0;
7468         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7469         nodes[0].chain_monitor = &monitor;
7470         nodes[0].chain_source = &chain_source;
7471
7472         check_added_monitors!(nodes[0], 1);
7473
7474         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7475         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7476
7477         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7478
7479         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7480         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7481         check_added_monitors!(nodes[0], 1);
7482
7483         {
7484                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7485                 assert_eq!(node_txn.len(), 0);
7486         }
7487
7488         let mut reestablish_1 = Vec::with_capacity(1);
7489         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7490                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7491                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7492                         reestablish_1.push(msg.clone());
7493                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7494                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7495                         match action {
7496                                 &ErrorAction::SendErrorMessage { ref msg } => {
7497                                         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");
7498                                 },
7499                                 _ => panic!("Unexpected event!"),
7500                         }
7501                 } else {
7502                         panic!("Unexpected event")
7503                 }
7504         }
7505
7506         // Check we close channel detecting A is fallen-behind
7507         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7508         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7509         check_added_monitors!(nodes[1], 1);
7510
7511
7512         // Check A is able to claim to_remote output
7513         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7514         assert_eq!(node_txn.len(), 1);
7515         check_spends!(node_txn[0], chan.3);
7516         assert_eq!(node_txn[0].output.len(), 2);
7517         mine_transaction(&nodes[0], &node_txn[0]);
7518         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7519         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 1000000);
7520         assert_eq!(spend_txn.len(), 1);
7521         check_spends!(spend_txn[0], node_txn[0]);
7522 }
7523
7524 #[test]
7525 fn test_check_htlc_underpaying() {
7526         // Send payment through A -> B but A is maliciously
7527         // sending a probe payment (i.e less than expected value0
7528         // to B, B should refuse payment.
7529
7530         let chanmon_cfgs = create_chanmon_cfgs(2);
7531         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7532         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7533         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7534
7535         // Create some initial channels
7536         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7537
7538         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7539
7540         // Node 3 is expecting payment of 100_000 but receive 10_000,
7541         // fail htlc like we didn't know the preimage.
7542         nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7543         nodes[1].node.process_pending_htlc_forwards();
7544
7545         let events = nodes[1].node.get_and_clear_pending_msg_events();
7546         assert_eq!(events.len(), 1);
7547         let (update_fail_htlc, commitment_signed) = match events[0] {
7548                 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 } } => {
7549                         assert!(update_add_htlcs.is_empty());
7550                         assert!(update_fulfill_htlcs.is_empty());
7551                         assert_eq!(update_fail_htlcs.len(), 1);
7552                         assert!(update_fail_malformed_htlcs.is_empty());
7553                         assert!(update_fee.is_none());
7554                         (update_fail_htlcs[0].clone(), commitment_signed)
7555                 },
7556                 _ => panic!("Unexpected event"),
7557         };
7558         check_added_monitors!(nodes[1], 1);
7559
7560         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7561         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7562
7563         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7564         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7565         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7566         expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7567         nodes[1].node.get_and_clear_pending_events();
7568 }
7569
7570 #[test]
7571 fn test_announce_disable_channels() {
7572         // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7573         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7574
7575         let chanmon_cfgs = create_chanmon_cfgs(2);
7576         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7577         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7578         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7579
7580         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7581         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7582         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7583
7584         // Disconnect peers
7585         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7586         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7587
7588         nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7589         nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7590         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7591         assert_eq!(msg_events.len(), 3);
7592         for e in msg_events {
7593                 match e {
7594                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7595                                 let short_id = msg.contents.short_channel_id;
7596                                 // Check generated channel_update match list in PendingChannelUpdate
7597                                 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7598                                         panic!("Generated ChannelUpdate for wrong chan!");
7599                                 }
7600                         },
7601                         _ => panic!("Unexpected event"),
7602                 }
7603         }
7604         // Reconnect peers
7605         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7606         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7607         assert_eq!(reestablish_1.len(), 3);
7608         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7609         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7610         assert_eq!(reestablish_2.len(), 3);
7611
7612         // Reestablish chan_1
7613         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7614         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7615         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7616         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7617         // Reestablish chan_2
7618         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7619         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7620         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7621         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7622         // Reestablish chan_3
7623         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7624         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7625         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7626         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7627
7628         nodes[0].node.timer_chan_freshness_every_min();
7629         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7630 }
7631
7632 #[test]
7633 fn test_bump_penalty_txn_on_revoked_commitment() {
7634         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7635         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7636
7637         let chanmon_cfgs = create_chanmon_cfgs(2);
7638         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7639         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7640         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7641
7642         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7643         let logger = test_utils::TestLogger::new();
7644
7645         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7646         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7647         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();
7648         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7649
7650         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7651         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7652         assert_eq!(revoked_txn[0].output.len(), 4);
7653         assert_eq!(revoked_txn[0].input.len(), 1);
7654         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7655         let revoked_txid = revoked_txn[0].txid();
7656
7657         let mut penalty_sum = 0;
7658         for outp in revoked_txn[0].output.iter() {
7659                 if outp.script_pubkey.is_v0_p2wsh() {
7660                         penalty_sum += outp.value;
7661                 }
7662         }
7663
7664         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7665         let header_114 = connect_blocks(&nodes[1], 14);
7666
7667         // Actually revoke tx by claiming a HTLC
7668         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7669         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7670         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7671         check_added_monitors!(nodes[1], 1);
7672
7673         // One or more justice tx should have been broadcast, check it
7674         let penalty_1;
7675         let feerate_1;
7676         {
7677                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7678                 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7679                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7680                 assert_eq!(node_txn[0].output.len(), 1);
7681                 check_spends!(node_txn[0], revoked_txn[0]);
7682                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7683                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7684                 penalty_1 = node_txn[0].txid();
7685                 node_txn.clear();
7686         };
7687
7688         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7689         connect_blocks(&nodes[1], 15);
7690         let mut penalty_2 = penalty_1;
7691         let mut feerate_2 = 0;
7692         {
7693                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7694                 assert_eq!(node_txn.len(), 1);
7695                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7696                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7697                         assert_eq!(node_txn[0].output.len(), 1);
7698                         check_spends!(node_txn[0], revoked_txn[0]);
7699                         penalty_2 = node_txn[0].txid();
7700                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7701                         assert_ne!(penalty_2, penalty_1);
7702                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7703                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7704                         // Verify 25% bump heuristic
7705                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7706                         node_txn.clear();
7707                 }
7708         }
7709         assert_ne!(feerate_2, 0);
7710
7711         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7712         connect_blocks(&nodes[1], 1);
7713         let penalty_3;
7714         let mut feerate_3 = 0;
7715         {
7716                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7717                 assert_eq!(node_txn.len(), 1);
7718                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7719                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7720                         assert_eq!(node_txn[0].output.len(), 1);
7721                         check_spends!(node_txn[0], revoked_txn[0]);
7722                         penalty_3 = node_txn[0].txid();
7723                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7724                         assert_ne!(penalty_3, penalty_2);
7725                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7726                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7727                         // Verify 25% bump heuristic
7728                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7729                         node_txn.clear();
7730                 }
7731         }
7732         assert_ne!(feerate_3, 0);
7733
7734         nodes[1].node.get_and_clear_pending_events();
7735         nodes[1].node.get_and_clear_pending_msg_events();
7736 }
7737
7738 #[test]
7739 fn test_bump_penalty_txn_on_revoked_htlcs() {
7740         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7741         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7742
7743         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7744         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7745         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7746         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7747         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7748
7749         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7750         // Lock HTLC in both directions
7751         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7752         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7753
7754         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7755         assert_eq!(revoked_local_txn[0].input.len(), 1);
7756         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7757
7758         // Revoke local commitment tx
7759         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7760
7761         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7762         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7763         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7764         check_closed_broadcast!(nodes[1], true);
7765         check_added_monitors!(nodes[1], 1);
7766
7767         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7768         assert_eq!(revoked_htlc_txn.len(), 4);
7769         if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7770                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7771                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7772                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7773                 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7774                 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7775                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7776         } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7777                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7778                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7779                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7780                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7781                 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7782                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7783         }
7784
7785         // Broadcast set of revoked txn on A
7786         let hash_128 = connect_blocks(&nodes[0], 40);
7787         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7788         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7789         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7790         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7791         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7792         let first;
7793         let feerate_1;
7794         let penalty_txn;
7795         {
7796                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7797                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7798                 // Verify claim tx are spending revoked HTLC txn
7799
7800                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7801                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7802                 // which are included in the same block (they are broadcasted because we scan the
7803                 // transactions linearly and generate claims as we go, they likely should be removed in the
7804                 // future).
7805                 assert_eq!(node_txn[0].input.len(), 1);
7806                 check_spends!(node_txn[0], revoked_local_txn[0]);
7807                 assert_eq!(node_txn[1].input.len(), 1);
7808                 check_spends!(node_txn[1], revoked_local_txn[0]);
7809                 assert_eq!(node_txn[2].input.len(), 1);
7810                 check_spends!(node_txn[2], revoked_local_txn[0]);
7811
7812                 // Each of the three justice transactions claim a separate (single) output of the three
7813                 // available, which we check here:
7814                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7815                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7816                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7817
7818                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7819                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7820
7821                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7822                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7823                 // a remote commitment tx has already been confirmed).
7824                 check_spends!(node_txn[3], chan.3);
7825
7826                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7827                 // output, checked above).
7828                 assert_eq!(node_txn[4].input.len(), 2);
7829                 assert_eq!(node_txn[4].output.len(), 1);
7830                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7831
7832                 first = node_txn[4].txid();
7833                 // Store both feerates for later comparison
7834                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7835                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7836                 penalty_txn = vec![node_txn[2].clone()];
7837                 node_txn.clear();
7838         }
7839
7840         // Connect one more block to see if bumped penalty are issued for HTLC txn
7841         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7842         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7843         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7844         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7845         {
7846                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7847                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7848
7849                 check_spends!(node_txn[0], revoked_local_txn[0]);
7850                 check_spends!(node_txn[1], revoked_local_txn[0]);
7851                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7852                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7853                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7854                 } else {
7855                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7856                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7857                 }
7858
7859                 node_txn.clear();
7860         };
7861
7862         // Few more blocks to confirm penalty txn
7863         connect_blocks(&nodes[0], 4);
7864         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7865         let header_144 = connect_blocks(&nodes[0], 9);
7866         let node_txn = {
7867                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7868                 assert_eq!(node_txn.len(), 1);
7869
7870                 assert_eq!(node_txn[0].input.len(), 2);
7871                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7872                 // Verify bumped tx is different and 25% bump heuristic
7873                 assert_ne!(first, node_txn[0].txid());
7874                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7875                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7876                 assert!(feerate_2 * 100 > feerate_1 * 125);
7877                 let txn = vec![node_txn[0].clone()];
7878                 node_txn.clear();
7879                 txn
7880         };
7881         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7882         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7883         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7884         connect_blocks(&nodes[0], 20);
7885         {
7886                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7887                 // We verify than no new transaction has been broadcast because previously
7888                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7889                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7890                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7891                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7892                 // up bumped justice generation.
7893                 assert_eq!(node_txn.len(), 0);
7894                 node_txn.clear();
7895         }
7896         check_closed_broadcast!(nodes[0], true);
7897         check_added_monitors!(nodes[0], 1);
7898 }
7899
7900 #[test]
7901 fn test_bump_penalty_txn_on_remote_commitment() {
7902         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7903         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7904
7905         // Create 2 HTLCs
7906         // Provide preimage for one
7907         // Check aggregation
7908
7909         let chanmon_cfgs = create_chanmon_cfgs(2);
7910         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7911         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7912         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7913
7914         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7915         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7916         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7917
7918         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7919         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7920         assert_eq!(remote_txn[0].output.len(), 4);
7921         assert_eq!(remote_txn[0].input.len(), 1);
7922         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7923
7924         // Claim a HTLC without revocation (provide B monitor with preimage)
7925         nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7926         mine_transaction(&nodes[1], &remote_txn[0]);
7927         check_added_monitors!(nodes[1], 2);
7928
7929         // One or more claim tx should have been broadcast, check it
7930         let timeout;
7931         let preimage;
7932         let feerate_timeout;
7933         let feerate_preimage;
7934         {
7935                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7936                 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7937                 assert_eq!(node_txn[0].input.len(), 1);
7938                 assert_eq!(node_txn[1].input.len(), 1);
7939                 check_spends!(node_txn[0], remote_txn[0]);
7940                 check_spends!(node_txn[1], remote_txn[0]);
7941                 check_spends!(node_txn[2], chan.3);
7942                 check_spends!(node_txn[3], node_txn[2]);
7943                 check_spends!(node_txn[4], node_txn[2]);
7944                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7945                         timeout = node_txn[0].txid();
7946                         let index = node_txn[0].input[0].previous_output.vout;
7947                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7948                         feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7949
7950                         preimage = node_txn[1].txid();
7951                         let index = node_txn[1].input[0].previous_output.vout;
7952                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7953                         feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7954                 } else {
7955                         timeout = node_txn[1].txid();
7956                         let index = node_txn[1].input[0].previous_output.vout;
7957                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7958                         feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7959
7960                         preimage = node_txn[0].txid();
7961                         let index = node_txn[0].input[0].previous_output.vout;
7962                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7963                         feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7964                 }
7965                 node_txn.clear();
7966         };
7967         assert_ne!(feerate_timeout, 0);
7968         assert_ne!(feerate_preimage, 0);
7969
7970         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7971         connect_blocks(&nodes[1], 15);
7972         {
7973                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7974                 assert_eq!(node_txn.len(), 2);
7975                 assert_eq!(node_txn[0].input.len(), 1);
7976                 assert_eq!(node_txn[1].input.len(), 1);
7977                 check_spends!(node_txn[0], remote_txn[0]);
7978                 check_spends!(node_txn[1], remote_txn[0]);
7979                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7980                         let index = node_txn[0].input[0].previous_output.vout;
7981                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7982                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7983                         assert!(new_feerate * 100 > feerate_timeout * 125);
7984                         assert_ne!(timeout, node_txn[0].txid());
7985
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_preimage * 125);
7990                         assert_ne!(preimage, node_txn[1].txid());
7991                 } else {
7992                         let index = node_txn[1].input[0].previous_output.vout;
7993                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7994                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7995                         assert!(new_feerate * 100 > feerate_timeout * 125);
7996                         assert_ne!(timeout, node_txn[1].txid());
7997
7998                         let index = node_txn[0].input[0].previous_output.vout;
7999                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8000                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8001                         assert!(new_feerate * 100 > feerate_preimage * 125);
8002                         assert_ne!(preimage, node_txn[0].txid());
8003                 }
8004                 node_txn.clear();
8005         }
8006
8007         nodes[1].node.get_and_clear_pending_events();
8008         nodes[1].node.get_and_clear_pending_msg_events();
8009 }
8010
8011 #[test]
8012 fn test_counterparty_raa_skip_no_crash() {
8013         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8014         // commitment transaction, we would have happily carried on and provided them the next
8015         // commitment transaction based on one RAA forward. This would probably eventually have led to
8016         // channel closure, but it would not have resulted in funds loss. Still, our
8017         // EnforcingSigner would have paniced as it doesn't like jumps into the future. Here, we
8018         // check simply that the channel is closed in response to such an RAA, but don't check whether
8019         // we decide to punish our counterparty for revoking their funds (as we don't currently
8020         // implement that).
8021         let chanmon_cfgs = create_chanmon_cfgs(2);
8022         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8023         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8024         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8025         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8026
8027         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8028         let keys = &guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8029         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8030         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8031         // Must revoke without gaps
8032         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8033         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8034                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8035
8036         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8037                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8038         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8039         check_added_monitors!(nodes[1], 1);
8040 }
8041
8042 #[test]
8043 fn test_bump_txn_sanitize_tracking_maps() {
8044         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8045         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8046
8047         let chanmon_cfgs = create_chanmon_cfgs(2);
8048         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8049         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8050         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8051
8052         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8053         // Lock HTLC in both directions
8054         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8055         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8056
8057         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8058         assert_eq!(revoked_local_txn[0].input.len(), 1);
8059         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8060
8061         // Revoke local commitment tx
8062         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8063
8064         // Broadcast set of revoked txn on A
8065         connect_blocks(&nodes[0], 52 - CHAN_CONFIRM_DEPTH);
8066         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8067         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8068
8069         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8070         check_closed_broadcast!(nodes[0], true);
8071         check_added_monitors!(nodes[0], 1);
8072         let penalty_txn = {
8073                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8074                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8075                 check_spends!(node_txn[0], revoked_local_txn[0]);
8076                 check_spends!(node_txn[1], revoked_local_txn[0]);
8077                 check_spends!(node_txn[2], revoked_local_txn[0]);
8078                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8079                 node_txn.clear();
8080                 penalty_txn
8081         };
8082         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8083         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8084         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8085         {
8086                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8087                 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8088                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8089                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8090                 }
8091         }
8092 }
8093
8094 #[test]
8095 fn test_override_channel_config() {
8096         let chanmon_cfgs = create_chanmon_cfgs(2);
8097         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8098         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8099         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8100
8101         // Node0 initiates a channel to node1 using the override config.
8102         let mut override_config = UserConfig::default();
8103         override_config.own_channel_config.our_to_self_delay = 200;
8104
8105         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8106
8107         // Assert the channel created by node0 is using the override config.
8108         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8109         assert_eq!(res.channel_flags, 0);
8110         assert_eq!(res.to_self_delay, 200);
8111 }
8112
8113 #[test]
8114 fn test_override_0msat_htlc_minimum() {
8115         let mut zero_config = UserConfig::default();
8116         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8117         let chanmon_cfgs = create_chanmon_cfgs(2);
8118         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8119         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8120         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8121
8122         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8123         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8124         assert_eq!(res.htlc_minimum_msat, 1);
8125
8126         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8127         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8128         assert_eq!(res.htlc_minimum_msat, 1);
8129 }
8130
8131 #[test]
8132 fn test_simple_payment_secret() {
8133         // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8134         // features, however.
8135         let chanmon_cfgs = create_chanmon_cfgs(3);
8136         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8137         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8138         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8139
8140         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8141         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8142         let logger = test_utils::TestLogger::new();
8143
8144         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8145         let payment_secret = PaymentSecret([0xdb; 32]);
8146         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8147         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();
8148         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8149         // Claiming with all the correct values but the wrong secret should result in nothing...
8150         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8151         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8152         // ...but with the right secret we should be able to claim all the way back
8153         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8154 }
8155
8156 #[test]
8157 fn test_simple_mpp() {
8158         // Simple test of sending a multi-path payment.
8159         let chanmon_cfgs = create_chanmon_cfgs(4);
8160         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8161         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8162         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8163
8164         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8165         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8166         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8167         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8168         let logger = test_utils::TestLogger::new();
8169
8170         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8171         let payment_secret = PaymentSecret([0xdb; 32]);
8172         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8173         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();
8174         let path = route.paths[0].clone();
8175         route.paths.push(path);
8176         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8177         route.paths[0][0].short_channel_id = chan_1_id;
8178         route.paths[0][1].short_channel_id = chan_3_id;
8179         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8180         route.paths[1][0].short_channel_id = chan_2_id;
8181         route.paths[1][1].short_channel_id = chan_4_id;
8182         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8183         // Claiming with all the correct values but the wrong secret should result in nothing...
8184         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8185         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8186         // ...but with the right secret we should be able to claim all the way back
8187         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8188 }
8189
8190 #[test]
8191 fn test_update_err_monitor_lockdown() {
8192         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8193         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8194         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8195         //
8196         // This scenario may happen in a watchtower setup, where watchtower process a block height
8197         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8198         // commitment at same time.
8199
8200         let chanmon_cfgs = create_chanmon_cfgs(2);
8201         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8202         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8203         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8204
8205         // Create some initial channel
8206         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8207         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8208
8209         // Rebalance the network to generate htlc in the two directions
8210         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8211
8212         // Route a HTLC from node 0 to node 1 (but don't settle)
8213         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8214
8215         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8216         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8217         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8218         let persister = test_utils::TestPersister::new();
8219         let watchtower = {
8220                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8221                 let monitor = monitors.get(&outpoint).unwrap();
8222                 let mut w = test_utils::TestVecWriter(Vec::new());
8223                 monitor.write(&mut w).unwrap();
8224                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8225                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8226                 assert!(new_monitor == *monitor);
8227                 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);
8228                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8229                 watchtower
8230         };
8231         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8232         watchtower.chain_monitor.block_connected(&header, &[], 200);
8233
8234         // Try to update ChannelMonitor
8235         assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8236         check_added_monitors!(nodes[1], 1);
8237         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8238         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8239         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8240         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8241                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8242                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8243                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8244                 } else { assert!(false); }
8245         } else { assert!(false); };
8246         // Our local monitor is in-sync and hasn't processed yet timeout
8247         check_added_monitors!(nodes[0], 1);
8248         let events = nodes[0].node.get_and_clear_pending_events();
8249         assert_eq!(events.len(), 1);
8250 }
8251
8252 #[test]
8253 fn test_concurrent_monitor_claim() {
8254         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8255         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8256         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8257         // state N+1 confirms. Alice claims output from state N+1.
8258
8259         let chanmon_cfgs = create_chanmon_cfgs(2);
8260         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8261         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8262         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8263
8264         // Create some initial channel
8265         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8266         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8267
8268         // Rebalance the network to generate htlc in the two directions
8269         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8270
8271         // Route a HTLC from node 0 to node 1 (but don't settle)
8272         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8273
8274         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8275         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8276         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8277         let persister = test_utils::TestPersister::new();
8278         let watchtower_alice = {
8279                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8280                 let monitor = monitors.get(&outpoint).unwrap();
8281                 let mut w = test_utils::TestVecWriter(Vec::new());
8282                 monitor.write(&mut w).unwrap();
8283                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8284                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8285                 assert!(new_monitor == *monitor);
8286                 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);
8287                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8288                 watchtower
8289         };
8290         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8291         watchtower_alice.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8292
8293         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8294         {
8295                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8296                 assert_eq!(txn.len(), 2);
8297                 txn.clear();
8298         }
8299
8300         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8301         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8302         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8303         let persister = test_utils::TestPersister::new();
8304         let watchtower_bob = {
8305                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8306                 let monitor = monitors.get(&outpoint).unwrap();
8307                 let mut w = test_utils::TestVecWriter(Vec::new());
8308                 monitor.write(&mut w).unwrap();
8309                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8310                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8311                 assert!(new_monitor == *monitor);
8312                 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);
8313                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8314                 watchtower
8315         };
8316         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8317         watchtower_bob.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8318
8319         // Route another payment to generate another update with still previous HTLC pending
8320         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8321         {
8322                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8323                 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();
8324                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8325         }
8326         check_added_monitors!(nodes[1], 1);
8327
8328         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8329         assert_eq!(updates.update_add_htlcs.len(), 1);
8330         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8331         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8332                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8333                         // Watchtower Alice should already have seen the block and reject the update
8334                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8335                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8336                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8337                 } else { assert!(false); }
8338         } else { assert!(false); };
8339         // Our local monitor is in-sync and hasn't processed yet timeout
8340         check_added_monitors!(nodes[0], 1);
8341
8342         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8343         watchtower_bob.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8344
8345         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8346         let bob_state_y;
8347         {
8348                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8349                 assert_eq!(txn.len(), 2);
8350                 bob_state_y = txn[0].clone();
8351                 txn.clear();
8352         };
8353
8354         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8355         watchtower_alice.chain_monitor.block_connected(&header, &vec![(0, &bob_state_y)], CHAN_CONFIRM_DEPTH + 2 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8356         {
8357                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8358                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8359                 // the onchain detection of the HTLC output
8360                 assert_eq!(htlc_txn.len(), 2);
8361                 check_spends!(htlc_txn[0], bob_state_y);
8362                 check_spends!(htlc_txn[1], bob_state_y);
8363         }
8364 }
8365
8366 #[test]
8367 fn test_pre_lockin_no_chan_closed_update() {
8368         // Test that if a peer closes a channel in response to a funding_created message we don't
8369         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8370         // message).
8371         //
8372         // Doing so would imply a channel monitor update before the initial channel monitor
8373         // registration, violating our API guarantees.
8374         //
8375         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8376         // then opening a second channel with the same funding output as the first (which is not
8377         // rejected because the first channel does not exist in the ChannelManager) and closing it
8378         // before receiving funding_signed.
8379         let chanmon_cfgs = create_chanmon_cfgs(2);
8380         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8381         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8382         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8383
8384         // Create an initial channel
8385         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8386         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8387         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8388         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8389         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8390
8391         // Move the first channel through the funding flow...
8392         let (temporary_channel_id, _tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8393
8394         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8395         check_added_monitors!(nodes[0], 0);
8396
8397         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8398         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8399         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8400         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8401 }
8402
8403 #[test]
8404 fn test_htlc_no_detection() {
8405         // This test is a mutation to underscore the detection logic bug we had
8406         // before #653. HTLC value routed is above the remaining balance, thus
8407         // inverting HTLC and `to_remote` output. HTLC will come second and
8408         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8409         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8410         // outputs order detection for correct spending children filtring.
8411
8412         let chanmon_cfgs = create_chanmon_cfgs(2);
8413         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8414         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8415         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8416
8417         // Create some initial channels
8418         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8419
8420         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000, 1_000_000);
8421         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8422         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8423         assert_eq!(local_txn[0].input.len(), 1);
8424         assert_eq!(local_txn[0].output.len(), 3);
8425         check_spends!(local_txn[0], chan_1.3);
8426
8427         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8428         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8429         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8430         // We deliberately connect the local tx twice as this should provoke a failure calling
8431         // this test before #653 fix.
8432         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);
8433         check_closed_broadcast!(nodes[0], true);
8434         check_added_monitors!(nodes[0], 1);
8435
8436         let htlc_timeout = {
8437                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8438                 assert_eq!(node_txn[0].input.len(), 1);
8439                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8440                 check_spends!(node_txn[0], local_txn[0]);
8441                 node_txn[0].clone()
8442         };
8443
8444         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8445         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8446         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8447         expect_payment_failed!(nodes[0], our_payment_hash, true);
8448 }
8449
8450 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8451         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8452         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8453         // Carol, Alice would be the upstream node, and Carol the downstream.)
8454         //
8455         // Steps of the test:
8456         // 1) Alice sends a HTLC to Carol through Bob.
8457         // 2) Carol doesn't settle the HTLC.
8458         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8459         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8460         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8461         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8462         // 5) Carol release the preimage to Bob off-chain.
8463         // 6) Bob claims the offered output on the broadcasted commitment.
8464         let chanmon_cfgs = create_chanmon_cfgs(3);
8465         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8466         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8467         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8468
8469         // Create some initial channels
8470         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8471         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8472
8473         // Steps (1) and (2):
8474         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8475         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8476
8477         // Check that Alice's commitment transaction now contains an output for this HTLC.
8478         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8479         check_spends!(alice_txn[0], chan_ab.3);
8480         assert_eq!(alice_txn[0].output.len(), 2);
8481         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8482         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8483         assert_eq!(alice_txn.len(), 2);
8484
8485         // Steps (3) and (4):
8486         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8487         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8488         let mut force_closing_node = 0; // Alice force-closes
8489         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8490         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8491         check_closed_broadcast!(nodes[force_closing_node], true);
8492         check_added_monitors!(nodes[force_closing_node], 1);
8493         if go_onchain_before_fulfill {
8494                 let txn_to_broadcast = match broadcast_alice {
8495                         true => alice_txn.clone(),
8496                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8497                 };
8498                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8499                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8500                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8501                 if broadcast_alice {
8502                         check_closed_broadcast!(nodes[1], true);
8503                         check_added_monitors!(nodes[1], 1);
8504                 }
8505                 assert_eq!(bob_txn.len(), 1);
8506                 check_spends!(bob_txn[0], chan_ab.3);
8507         }
8508
8509         // Step (5):
8510         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8511         // process of removing the HTLC from their commitment transactions.
8512         assert!(nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000));
8513         check_added_monitors!(nodes[2], 1);
8514         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8515         assert!(carol_updates.update_add_htlcs.is_empty());
8516         assert!(carol_updates.update_fail_htlcs.is_empty());
8517         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8518         assert!(carol_updates.update_fee.is_none());
8519         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8520
8521         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8522         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8523         if !go_onchain_before_fulfill && broadcast_alice {
8524                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8525                 assert_eq!(events.len(), 1);
8526                 match events[0] {
8527                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8528                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8529                         },
8530                         _ => panic!("Unexpected event"),
8531                 };
8532         }
8533         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8534         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8535         // Carol<->Bob's updated commitment transaction info.
8536         check_added_monitors!(nodes[1], 2);
8537
8538         let events = nodes[1].node.get_and_clear_pending_msg_events();
8539         assert_eq!(events.len(), 2);
8540         let bob_revocation = match events[0] {
8541                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8542                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8543                         (*msg).clone()
8544                 },
8545                 _ => panic!("Unexpected event"),
8546         };
8547         let bob_updates = match events[1] {
8548                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8549                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8550                         (*updates).clone()
8551                 },
8552                 _ => panic!("Unexpected event"),
8553         };
8554
8555         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8556         check_added_monitors!(nodes[2], 1);
8557         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8558         check_added_monitors!(nodes[2], 1);
8559
8560         let events = nodes[2].node.get_and_clear_pending_msg_events();
8561         assert_eq!(events.len(), 1);
8562         let carol_revocation = match events[0] {
8563                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8564                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8565                         (*msg).clone()
8566                 },
8567                 _ => panic!("Unexpected event"),
8568         };
8569         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8570         check_added_monitors!(nodes[1], 1);
8571
8572         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8573         // here's where we put said channel's commitment tx on-chain.
8574         let mut txn_to_broadcast = alice_txn.clone();
8575         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8576         if !go_onchain_before_fulfill {
8577                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8578                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8579                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8580                 if broadcast_alice {
8581                         check_closed_broadcast!(nodes[1], true);
8582                         check_added_monitors!(nodes[1], 1);
8583                 }
8584                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8585                 if broadcast_alice {
8586                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8587                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8588                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8589                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8590                         // broadcasted.
8591                         assert_eq!(bob_txn.len(), 3);
8592                         check_spends!(bob_txn[1], chan_ab.3);
8593                 } else {
8594                         assert_eq!(bob_txn.len(), 2);
8595                         check_spends!(bob_txn[0], chan_ab.3);
8596                 }
8597         }
8598
8599         // Step (6):
8600         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8601         // broadcasted commitment transaction.
8602         {
8603                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8604                 if go_onchain_before_fulfill {
8605                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8606                         assert_eq!(bob_txn.len(), 2);
8607                 }
8608                 let script_weight = match broadcast_alice {
8609                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8610                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8611                 };
8612                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8613                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8614                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8615                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8616                 if broadcast_alice && !go_onchain_before_fulfill {
8617                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8618                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8619                 } else {
8620                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8621                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8622                 }
8623         }
8624 }
8625
8626 #[test]
8627 fn test_onchain_htlc_settlement_after_close() {
8628         do_test_onchain_htlc_settlement_after_close(true, true);
8629         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8630         do_test_onchain_htlc_settlement_after_close(true, false);
8631         do_test_onchain_htlc_settlement_after_close(false, false);
8632 }
8633
8634 #[test]
8635 fn test_duplicate_chan_id() {
8636         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8637         // already open we reject it and keep the old channel.
8638         //
8639         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8640         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8641         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8642         // updating logic for the existing channel.
8643         let chanmon_cfgs = create_chanmon_cfgs(2);
8644         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8645         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8646         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8647
8648         // Create an initial channel
8649         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8650         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8651         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8652         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()));
8653
8654         // Try to create a second channel with the same temporary_channel_id as the first and check
8655         // that it is rejected.
8656         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8657         {
8658                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8659                 assert_eq!(events.len(), 1);
8660                 match events[0] {
8661                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8662                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8663                                 // first (valid) and second (invalid) channels are closed, given they both have
8664                                 // the same non-temporary channel_id. However, currently we do not, so we just
8665                                 // move forward with it.
8666                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8667                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8668                         },
8669                         _ => panic!("Unexpected event"),
8670                 }
8671         }
8672
8673         // Move the first channel through the funding flow...
8674         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8675
8676         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8677         check_added_monitors!(nodes[0], 0);
8678
8679         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8680         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8681         {
8682                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8683                 assert_eq!(added_monitors.len(), 1);
8684                 assert_eq!(added_monitors[0].0, funding_output);
8685                 added_monitors.clear();
8686         }
8687         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8688
8689         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8690         let channel_id = funding_outpoint.to_channel_id();
8691
8692         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8693         // temporary one).
8694
8695         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8696         // Technically this is allowed by the spec, but we don't support it and there's little reason
8697         // to. Still, it shouldn't cause any other issues.
8698         open_chan_msg.temporary_channel_id = channel_id;
8699         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8700         {
8701                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8702                 assert_eq!(events.len(), 1);
8703                 match events[0] {
8704                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8705                                 // Technically, at this point, nodes[1] would be justified in thinking both
8706                                 // channels are closed, but currently we do not, so we just move forward with it.
8707                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8708                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8709                         },
8710                         _ => panic!("Unexpected event"),
8711                 }
8712         }
8713
8714         // Now try to create a second channel which has a duplicate funding output.
8715         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8716         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8717         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8718         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()));
8719         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8720
8721         let funding_created = {
8722                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8723                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8724                 let logger = test_utils::TestLogger::new();
8725                 as_chan.get_outbound_funding_created(funding_outpoint, &&logger).unwrap()
8726         };
8727         check_added_monitors!(nodes[0], 0);
8728         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8729         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8730         // still needs to be cleared here.
8731         check_added_monitors!(nodes[1], 1);
8732
8733         // ...still, nodes[1] will reject the duplicate channel.
8734         {
8735                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8736                 assert_eq!(events.len(), 1);
8737                 match events[0] {
8738                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8739                                 // Technically, at this point, nodes[1] would be justified in thinking both
8740                                 // channels are closed, but currently we do not, so we just move forward with it.
8741                                 assert_eq!(msg.channel_id, channel_id);
8742                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8743                         },
8744                         _ => panic!("Unexpected event"),
8745                 }
8746         }
8747
8748         // finally, finish creating the original channel and send a payment over it to make sure
8749         // everything is functional.
8750         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8751         {
8752                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8753                 assert_eq!(added_monitors.len(), 1);
8754                 assert_eq!(added_monitors[0].0, funding_output);
8755                 added_monitors.clear();
8756         }
8757
8758         let events_4 = nodes[0].node.get_and_clear_pending_events();
8759         assert_eq!(events_4.len(), 1);
8760         match events_4[0] {
8761                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
8762                         assert_eq!(user_channel_id, 42);
8763                         assert_eq!(*funding_txo, funding_output);
8764                 },
8765                 _ => panic!("Unexpected event"),
8766         };
8767
8768         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8769         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8770         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8771         send_payment(&nodes[0], &[&nodes[1]], 8000000, 8_000_000);
8772 }
8773
8774 #[test]
8775 fn test_error_chans_closed() {
8776         // Test that we properly handle error messages, closing appropriate channels.
8777         //
8778         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8779         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8780         // we can test various edge cases around it to ensure we don't regress.
8781         let chanmon_cfgs = create_chanmon_cfgs(3);
8782         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8783         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8784         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8785
8786         // Create some initial channels
8787         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8788         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8789         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8790
8791         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8792         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8793         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8794
8795         // Closing a channel from a different peer has no effect
8796         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8797         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8798
8799         // Closing one channel doesn't impact others
8800         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8801         check_added_monitors!(nodes[0], 1);
8802         check_closed_broadcast!(nodes[0], false);
8803         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8804         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);
8805         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);
8806
8807         // A null channel ID should close all channels
8808         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8809         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8810         check_added_monitors!(nodes[0], 2);
8811         let events = nodes[0].node.get_and_clear_pending_msg_events();
8812         assert_eq!(events.len(), 2);
8813         match events[0] {
8814                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8815                         assert_eq!(msg.contents.flags & 2, 2);
8816                 },
8817                 _ => panic!("Unexpected event"),
8818         }
8819         match events[1] {
8820                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8821                         assert_eq!(msg.contents.flags & 2, 2);
8822                 },
8823                 _ => panic!("Unexpected event"),
8824         }
8825         // Note that at this point users of a standard PeerHandler will end up calling
8826         // peer_disconnected with no_connection_possible set to false, duplicating the
8827         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8828         // users with their own peer handling logic. We duplicate the call here, however.
8829         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8830         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8831
8832         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8833         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8834         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8835 }