Take the full funding transaction from the user on generation
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use chain;
15 use chain::Watch;
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::{Sign, KeysInterface};
20 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
21 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
22 use ln::channel::{Channel, ChannelError};
23 use ln::{chan_utils, onion_utils};
24 use routing::router::{Route, RouteHop, get_route};
25 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
26 use ln::msgs;
27 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
28 use util::enforcing_trait_impls::EnforcingSigner;
29 use util::{byte_utils, test_utils};
30 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
31 use util::errors::APIError;
32 use util::ser::{Writeable, ReadableArgs};
33 use util::config::UserConfig;
34
35 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
36 use bitcoin::hash_types::{Txid, BlockHash};
37 use bitcoin::blockdata::block::{Block, BlockHeader};
38 use bitcoin::blockdata::script::Builder;
39 use bitcoin::blockdata::opcodes;
40 use bitcoin::blockdata::constants::genesis_block;
41 use bitcoin::network::constants::Network;
42
43 use bitcoin::hashes::sha256::Hash as Sha256;
44 use bitcoin::hashes::Hash;
45
46 use bitcoin::secp256k1::{Secp256k1, Message};
47 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
48
49 use regex;
50
51 use std::collections::{BTreeSet, HashMap, HashSet};
52 use std::default::Default;
53 use std::sync::Mutex;
54 use std::sync::atomic::Ordering;
55
56 use ln::functional_test_utils::*;
57 use ln::chan_utils::CommitmentTransaction;
58 use ln::msgs::OptionalField::Present;
59
60 #[test]
61 fn test_insane_channel_opens() {
62         // Stand up a network of 2 nodes
63         let chanmon_cfgs = create_chanmon_cfgs(2);
64         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
65         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
66         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
67
68         // Instantiate channel parameters where we push the maximum msats given our
69         // funding satoshis
70         let channel_value_sat = 31337; // same as funding satoshis
71         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
72         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
73
74         // Have node0 initiate a channel to node1 with aforementioned parameters
75         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
76
77         // Extract the channel open message from node0 to node1
78         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
79
80         // Test helper that asserts we get the correct error string given a mutator
81         // that supposedly makes the channel open message insane
82         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
83                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
84                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
85                 assert_eq!(msg_events.len(), 1);
86                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
87                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
88                         match action {
89                                 &ErrorAction::SendErrorMessage { .. } => {
90                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
91                                 },
92                                 _ => panic!("unexpected event!"),
93                         }
94                 } else { assert!(false); }
95         };
96
97         use ln::channel::MAX_FUNDING_SATOSHIS;
98         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
99
100         // Test all mutations that would make the channel open message insane
101         insane_open_helper(format!("Funding must be smaller than {}. It was {}", MAX_FUNDING_SATOSHIS, MAX_FUNDING_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
102
103         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
104
105         insane_open_helper(r"push_msat \d+ was larger than funding value \d+", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
106
107         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
108
109         insane_open_helper(r"Bogus; channel reserve \(\d+\) is less than dust limit \(\d+\)", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
110
111         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
112
113         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
114
115         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
116
117         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
118 }
119
120 #[test]
121 fn test_async_inbound_update_fee() {
122         let chanmon_cfgs = create_chanmon_cfgs(2);
123         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
124         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
125         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
126         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
127         let logger = test_utils::TestLogger::new();
128         let channel_id = chan.2;
129
130         // balancing
131         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
132
133         // A                                        B
134         // update_fee                            ->
135         // send (1) commitment_signed            -.
136         //                                       <- update_add_htlc/commitment_signed
137         // send (2) RAA (awaiting remote revoke) -.
138         // (1) commitment_signed is delivered    ->
139         //                                       .- send (3) RAA (awaiting remote revoke)
140         // (2) RAA is delivered                  ->
141         //                                       .- send (4) commitment_signed
142         //                                       <- (3) RAA is delivered
143         // send (5) commitment_signed            -.
144         //                                       <- (4) commitment_signed is delivered
145         // send (6) RAA                          -.
146         // (5) commitment_signed is delivered    ->
147         //                                       <- RAA
148         // (6) RAA is delivered                  ->
149
150         // First nodes[0] generates an update_fee
151         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
152         check_added_monitors!(nodes[0], 1);
153
154         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
155         assert_eq!(events_0.len(), 1);
156         let (update_msg, commitment_signed) = match events_0[0] { // (1)
157                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
158                         (update_fee.as_ref(), commitment_signed)
159                 },
160                 _ => panic!("Unexpected event"),
161         };
162
163         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
164
165         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
166         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
167         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
168         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
169         check_added_monitors!(nodes[1], 1);
170
171         let payment_event = {
172                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
173                 assert_eq!(events_1.len(), 1);
174                 SendEvent::from_event(events_1.remove(0))
175         };
176         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
177         assert_eq!(payment_event.msgs.len(), 1);
178
179         // ...now when the messages get delivered everyone should be happy
180         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
181         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
182         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
183         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
184         check_added_monitors!(nodes[0], 1);
185
186         // deliver(1), generate (3):
187         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
188         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
189         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
190         check_added_monitors!(nodes[1], 1);
191
192         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
193         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
194         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
195         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
196         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
197         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
198         assert!(bs_update.update_fee.is_none()); // (4)
199         check_added_monitors!(nodes[1], 1);
200
201         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
202         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
203         assert!(as_update.update_add_htlcs.is_empty()); // (5)
204         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
205         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
206         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
207         assert!(as_update.update_fee.is_none()); // (5)
208         check_added_monitors!(nodes[0], 1);
209
210         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
211         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
212         // only (6) so get_event_msg's assert(len == 1) passes
213         check_added_monitors!(nodes[0], 1);
214
215         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
216         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
217         check_added_monitors!(nodes[1], 1);
218
219         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
220         check_added_monitors!(nodes[0], 1);
221
222         let events_2 = nodes[0].node.get_and_clear_pending_events();
223         assert_eq!(events_2.len(), 1);
224         match events_2[0] {
225                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
226                 _ => panic!("Unexpected event"),
227         }
228
229         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
230         check_added_monitors!(nodes[1], 1);
231 }
232
233 #[test]
234 fn test_update_fee_unordered_raa() {
235         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
236         // crash in an earlier version of the update_fee patch)
237         let chanmon_cfgs = create_chanmon_cfgs(2);
238         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
239         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
240         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
241         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
242         let channel_id = chan.2;
243         let logger = test_utils::TestLogger::new();
244
245         // balancing
246         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
247
248         // First nodes[0] generates an update_fee
249         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
250         check_added_monitors!(nodes[0], 1);
251
252         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
253         assert_eq!(events_0.len(), 1);
254         let update_msg = match events_0[0] { // (1)
255                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
256                         update_fee.as_ref()
257                 },
258                 _ => panic!("Unexpected event"),
259         };
260
261         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
262
263         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
264         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
265         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
266         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
267         check_added_monitors!(nodes[1], 1);
268
269         let payment_event = {
270                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
271                 assert_eq!(events_1.len(), 1);
272                 SendEvent::from_event(events_1.remove(0))
273         };
274         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
275         assert_eq!(payment_event.msgs.len(), 1);
276
277         // ...now when the messages get delivered everyone should be happy
278         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
279         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
280         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
281         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
282         check_added_monitors!(nodes[0], 1);
283
284         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
285         check_added_monitors!(nodes[1], 1);
286
287         // We can't continue, sadly, because our (1) now has a bogus signature
288 }
289
290 #[test]
291 fn test_multi_flight_update_fee() {
292         let chanmon_cfgs = create_chanmon_cfgs(2);
293         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
294         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
295         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
296         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
297         let channel_id = chan.2;
298
299         // A                                        B
300         // update_fee/commitment_signed          ->
301         //                                       .- send (1) RAA and (2) commitment_signed
302         // update_fee (never committed)          ->
303         // (3) update_fee                        ->
304         // We have to manually generate the above update_fee, it is allowed by the protocol but we
305         // don't track which updates correspond to which revoke_and_ack responses so we're in
306         // AwaitingRAA mode and will not generate the update_fee yet.
307         //                                       <- (1) RAA delivered
308         // (3) is generated and send (4) CS      -.
309         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
310         // know the per_commitment_point to use for it.
311         //                                       <- (2) commitment_signed delivered
312         // revoke_and_ack                        ->
313         //                                          B should send no response here
314         // (4) commitment_signed delivered       ->
315         //                                       <- RAA/commitment_signed delivered
316         // revoke_and_ack                        ->
317
318         // First nodes[0] generates an update_fee
319         let initial_feerate = get_feerate!(nodes[0], channel_id);
320         nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
321         check_added_monitors!(nodes[0], 1);
322
323         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
324         assert_eq!(events_0.len(), 1);
325         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
326                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
327                         (update_fee.as_ref().unwrap(), commitment_signed)
328                 },
329                 _ => panic!("Unexpected event"),
330         };
331
332         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
333         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
334         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
335         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
336         check_added_monitors!(nodes[1], 1);
337
338         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
339         // transaction:
340         nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
341         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
342         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
343
344         // Create the (3) update_fee message that nodes[0] will generate before it does...
345         let mut update_msg_2 = msgs::UpdateFee {
346                 channel_id: update_msg_1.channel_id.clone(),
347                 feerate_per_kw: (initial_feerate + 30) as u32,
348         };
349
350         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
351
352         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
353         // Deliver (3)
354         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
355
356         // Deliver (1), generating (3) and (4)
357         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
358         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
359         check_added_monitors!(nodes[0], 1);
360         assert!(as_second_update.update_add_htlcs.is_empty());
361         assert!(as_second_update.update_fulfill_htlcs.is_empty());
362         assert!(as_second_update.update_fail_htlcs.is_empty());
363         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
364         // Check that the update_fee newly generated matches what we delivered:
365         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
366         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
367
368         // Deliver (2) commitment_signed
369         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
370         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
371         check_added_monitors!(nodes[0], 1);
372         // No commitment_signed so get_event_msg's assert(len == 1) passes
373
374         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
375         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
376         check_added_monitors!(nodes[1], 1);
377
378         // Delever (4)
379         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
380         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
381         check_added_monitors!(nodes[1], 1);
382
383         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
384         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
385         check_added_monitors!(nodes[0], 1);
386
387         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
388         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
389         // No commitment_signed so get_event_msg's assert(len == 1) passes
390         check_added_monitors!(nodes[0], 1);
391
392         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
393         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
394         check_added_monitors!(nodes[1], 1);
395 }
396
397 #[test]
398 fn test_1_conf_open() {
399         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
400         // tests that we properly send one in that case.
401         let mut alice_config = UserConfig::default();
402         alice_config.own_channel_config.minimum_depth = 1;
403         alice_config.channel_options.announced_channel = true;
404         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
405         let mut bob_config = UserConfig::default();
406         bob_config.own_channel_config.minimum_depth = 1;
407         bob_config.channel_options.announced_channel = true;
408         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
409         let chanmon_cfgs = create_chanmon_cfgs(2);
410         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
411         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
412         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
413
414         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
415         mine_transaction(&nodes[1], &tx);
416         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id()));
417
418         mine_transaction(&nodes[0], &tx);
419         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
420         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
421
422         for node in nodes {
423                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
424                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
425                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
426         }
427 }
428
429 fn do_test_sanity_on_in_flight_opens(steps: u8) {
430         // Previously, we had issues deserializing channels when we hadn't connected the first block
431         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
432         // serialization round-trips and simply do steps towards opening a channel and then drop the
433         // Node objects.
434
435         let chanmon_cfgs = create_chanmon_cfgs(2);
436         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
437         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
438         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
439
440         if steps & 0b1000_0000 != 0{
441                 let block = Block {
442                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
443                         txdata: vec![],
444                 };
445                 connect_block(&nodes[0], &block);
446                 connect_block(&nodes[1], &block);
447         }
448
449         if steps & 0x0f == 0 { return; }
450         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
451         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
452
453         if steps & 0x0f == 1 { return; }
454         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
455         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
456
457         if steps & 0x0f == 2 { return; }
458         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
459
460         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
461
462         if steps & 0x0f == 3 { return; }
463         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
464         check_added_monitors!(nodes[0], 0);
465         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
466
467         if steps & 0x0f == 4 { return; }
468         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
469         {
470                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
471                 assert_eq!(added_monitors.len(), 1);
472                 assert_eq!(added_monitors[0].0, funding_output);
473                 added_monitors.clear();
474         }
475         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
476
477         if steps & 0x0f == 5 { return; }
478         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
479         {
480                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
481                 assert_eq!(added_monitors.len(), 1);
482                 assert_eq!(added_monitors[0].0, funding_output);
483                 added_monitors.clear();
484         }
485
486         let events_4 = nodes[0].node.get_and_clear_pending_events();
487         assert_eq!(events_4.len(), 0);
488
489         if steps & 0x0f == 6 { return; }
490         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
491
492         if steps & 0x0f == 7 { return; }
493         confirm_transaction_at(&nodes[0], &tx, 2);
494         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
495         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
496 }
497
498 #[test]
499 fn test_sanity_on_in_flight_opens() {
500         do_test_sanity_on_in_flight_opens(0);
501         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
502         do_test_sanity_on_in_flight_opens(1);
503         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
504         do_test_sanity_on_in_flight_opens(2);
505         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
506         do_test_sanity_on_in_flight_opens(3);
507         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
508         do_test_sanity_on_in_flight_opens(4);
509         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
510         do_test_sanity_on_in_flight_opens(5);
511         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
512         do_test_sanity_on_in_flight_opens(6);
513         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
514         do_test_sanity_on_in_flight_opens(7);
515         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
516         do_test_sanity_on_in_flight_opens(8);
517         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
518 }
519
520 #[test]
521 fn test_update_fee_vanilla() {
522         let chanmon_cfgs = create_chanmon_cfgs(2);
523         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
524         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
525         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
526         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
527         let channel_id = chan.2;
528
529         let feerate = get_feerate!(nodes[0], channel_id);
530         nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
531         check_added_monitors!(nodes[0], 1);
532
533         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
534         assert_eq!(events_0.len(), 1);
535         let (update_msg, commitment_signed) = match events_0[0] {
536                         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 } } => {
537                         (update_fee.as_ref(), commitment_signed)
538                 },
539                 _ => panic!("Unexpected event"),
540         };
541         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
542
543         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
544         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
545         check_added_monitors!(nodes[1], 1);
546
547         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
548         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
549         check_added_monitors!(nodes[0], 1);
550
551         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
552         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
553         // No commitment_signed so get_event_msg's assert(len == 1) passes
554         check_added_monitors!(nodes[0], 1);
555
556         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
557         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
558         check_added_monitors!(nodes[1], 1);
559 }
560
561 #[test]
562 fn test_update_fee_that_funder_cannot_afford() {
563         let chanmon_cfgs = create_chanmon_cfgs(2);
564         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
565         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
566         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
567         let channel_value = 1888;
568         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
569         let channel_id = chan.2;
570
571         let feerate = 260;
572         nodes[0].node.update_fee(channel_id, feerate).unwrap();
573         check_added_monitors!(nodes[0], 1);
574         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
575
576         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
577
578         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
579
580         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
581         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
582         {
583                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
584
585                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
586                 let num_htlcs = commitment_tx.output.len() - 2;
587                 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
588                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
589                 actual_fee = channel_value - actual_fee;
590                 assert_eq!(total_fee, actual_fee);
591         }
592
593         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
594         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
595         nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
596         check_added_monitors!(nodes[0], 1);
597
598         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
599
600         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
601
602         //While producing the commitment_signed response after handling a received update_fee request the
603         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
604         //Should produce and error.
605         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
606         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
607         check_added_monitors!(nodes[1], 1);
608         check_closed_broadcast!(nodes[1], true);
609 }
610
611 #[test]
612 fn test_update_fee_with_fundee_update_add_htlc() {
613         let chanmon_cfgs = create_chanmon_cfgs(2);
614         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
615         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
616         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
617         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
618         let channel_id = chan.2;
619         let logger = test_utils::TestLogger::new();
620
621         // balancing
622         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
623
624         let feerate = get_feerate!(nodes[0], channel_id);
625         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
626         check_added_monitors!(nodes[0], 1);
627
628         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
629         assert_eq!(events_0.len(), 1);
630         let (update_msg, commitment_signed) = match events_0[0] {
631                         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 } } => {
632                         (update_fee.as_ref(), commitment_signed)
633                 },
634                 _ => panic!("Unexpected event"),
635         };
636         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
637         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
638         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
639         check_added_monitors!(nodes[1], 1);
640
641         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
642         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
643         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();
644
645         // nothing happens since node[1] is in AwaitingRemoteRevoke
646         nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
647         {
648                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
649                 assert_eq!(added_monitors.len(), 0);
650                 added_monitors.clear();
651         }
652         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
653         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
654         // node[1] has nothing to do
655
656         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
657         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
658         check_added_monitors!(nodes[0], 1);
659
660         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
661         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
662         // No commitment_signed so get_event_msg's assert(len == 1) passes
663         check_added_monitors!(nodes[0], 1);
664         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
665         check_added_monitors!(nodes[1], 1);
666         // AwaitingRemoteRevoke ends here
667
668         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
669         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
670         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
671         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
672         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
673         assert_eq!(commitment_update.update_fee.is_none(), true);
674
675         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
676         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
677         check_added_monitors!(nodes[0], 1);
678         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
679
680         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
681         check_added_monitors!(nodes[1], 1);
682         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
683
684         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
685         check_added_monitors!(nodes[1], 1);
686         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
687         // No commitment_signed so get_event_msg's assert(len == 1) passes
688
689         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
690         check_added_monitors!(nodes[0], 1);
691         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
692
693         expect_pending_htlcs_forwardable!(nodes[0]);
694
695         let events = nodes[0].node.get_and_clear_pending_events();
696         assert_eq!(events.len(), 1);
697         match events[0] {
698                 Event::PaymentReceived { .. } => { },
699                 _ => panic!("Unexpected event"),
700         };
701
702         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
703
704         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
705         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
706         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
707 }
708
709 #[test]
710 fn test_update_fee() {
711         let chanmon_cfgs = create_chanmon_cfgs(2);
712         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
713         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
714         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
715         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
716         let channel_id = chan.2;
717
718         // A                                        B
719         // (1) update_fee/commitment_signed      ->
720         //                                       <- (2) revoke_and_ack
721         //                                       .- send (3) commitment_signed
722         // (4) update_fee/commitment_signed      ->
723         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
724         //                                       <- (3) commitment_signed delivered
725         // send (6) revoke_and_ack               -.
726         //                                       <- (5) deliver revoke_and_ack
727         // (6) deliver revoke_and_ack            ->
728         //                                       .- send (7) commitment_signed in response to (4)
729         //                                       <- (7) deliver commitment_signed
730         // revoke_and_ack                        ->
731
732         // Create and deliver (1)...
733         let feerate = get_feerate!(nodes[0], channel_id);
734         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
735         check_added_monitors!(nodes[0], 1);
736
737         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
738         assert_eq!(events_0.len(), 1);
739         let (update_msg, commitment_signed) = match events_0[0] {
740                         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 } } => {
741                         (update_fee.as_ref(), commitment_signed)
742                 },
743                 _ => panic!("Unexpected event"),
744         };
745         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
746
747         // Generate (2) and (3):
748         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
749         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
750         check_added_monitors!(nodes[1], 1);
751
752         // Deliver (2):
753         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
754         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
755         check_added_monitors!(nodes[0], 1);
756
757         // Create and deliver (4)...
758         nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
759         check_added_monitors!(nodes[0], 1);
760         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
761         assert_eq!(events_0.len(), 1);
762         let (update_msg, commitment_signed) = match events_0[0] {
763                         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 } } => {
764                         (update_fee.as_ref(), commitment_signed)
765                 },
766                 _ => panic!("Unexpected event"),
767         };
768
769         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
770         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
771         check_added_monitors!(nodes[1], 1);
772         // ... creating (5)
773         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
774         // No commitment_signed so get_event_msg's assert(len == 1) passes
775
776         // Handle (3), creating (6):
777         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
778         check_added_monitors!(nodes[0], 1);
779         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
780         // No commitment_signed so get_event_msg's assert(len == 1) passes
781
782         // Deliver (5):
783         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
784         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
785         check_added_monitors!(nodes[0], 1);
786
787         // Deliver (6), creating (7):
788         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
789         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
790         assert!(commitment_update.update_add_htlcs.is_empty());
791         assert!(commitment_update.update_fulfill_htlcs.is_empty());
792         assert!(commitment_update.update_fail_htlcs.is_empty());
793         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
794         assert!(commitment_update.update_fee.is_none());
795         check_added_monitors!(nodes[1], 1);
796
797         // Deliver (7)
798         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
799         check_added_monitors!(nodes[0], 1);
800         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
801         // No commitment_signed so get_event_msg's assert(len == 1) passes
802
803         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
804         check_added_monitors!(nodes[1], 1);
805         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
806
807         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
808         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
809         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
810 }
811
812 #[test]
813 fn pre_funding_lock_shutdown_test() {
814         // Test sending a shutdown prior to funding_locked after funding generation
815         let chanmon_cfgs = create_chanmon_cfgs(2);
816         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
817         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
818         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
819         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
820         mine_transaction(&nodes[0], &tx);
821         mine_transaction(&nodes[1], &tx);
822
823         nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
824         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
825         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
826         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
827         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
828
829         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
830         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
831         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
832         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
833         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
834         assert!(node_0_none.is_none());
835
836         assert!(nodes[0].node.list_channels().is_empty());
837         assert!(nodes[1].node.list_channels().is_empty());
838 }
839
840 #[test]
841 fn updates_shutdown_wait() {
842         // Test sending a shutdown with outstanding updates pending
843         let chanmon_cfgs = create_chanmon_cfgs(3);
844         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
845         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
846         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
847         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
848         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
849         let logger = test_utils::TestLogger::new();
850
851         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
852
853         nodes[0].node.close_channel(&chan_1.2).unwrap();
854         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
855         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
856         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
857         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
858
859         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
860         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
861
862         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
863
864         let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
865         let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
866         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();
867         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();
868         unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
869         unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
870
871         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
872         check_added_monitors!(nodes[2], 1);
873         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
874         assert!(updates.update_add_htlcs.is_empty());
875         assert!(updates.update_fail_htlcs.is_empty());
876         assert!(updates.update_fail_malformed_htlcs.is_empty());
877         assert!(updates.update_fee.is_none());
878         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
879         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
880         check_added_monitors!(nodes[1], 1);
881         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
882         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
883
884         assert!(updates_2.update_add_htlcs.is_empty());
885         assert!(updates_2.update_fail_htlcs.is_empty());
886         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
887         assert!(updates_2.update_fee.is_none());
888         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
889         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
890         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
891
892         let events = nodes[0].node.get_and_clear_pending_events();
893         assert_eq!(events.len(), 1);
894         match events[0] {
895                 Event::PaymentSent { ref payment_preimage } => {
896                         assert_eq!(our_payment_preimage, *payment_preimage);
897                 },
898                 _ => panic!("Unexpected event"),
899         }
900
901         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
902         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
903         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
904         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
905         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
906         assert!(node_0_none.is_none());
907
908         assert!(nodes[0].node.list_channels().is_empty());
909
910         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
911         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
912         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
913         assert!(nodes[1].node.list_channels().is_empty());
914         assert!(nodes[2].node.list_channels().is_empty());
915 }
916
917 #[test]
918 fn htlc_fail_async_shutdown() {
919         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
920         let chanmon_cfgs = create_chanmon_cfgs(3);
921         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
922         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
923         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
924         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
925         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
926         let logger = test_utils::TestLogger::new();
927
928         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
929         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
930         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();
931         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
932         check_added_monitors!(nodes[0], 1);
933         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
934         assert_eq!(updates.update_add_htlcs.len(), 1);
935         assert!(updates.update_fulfill_htlcs.is_empty());
936         assert!(updates.update_fail_htlcs.is_empty());
937         assert!(updates.update_fail_malformed_htlcs.is_empty());
938         assert!(updates.update_fee.is_none());
939
940         nodes[1].node.close_channel(&chan_1.2).unwrap();
941         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
942         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
943         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
944
945         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
946         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
947         check_added_monitors!(nodes[1], 1);
948         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
949         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
950
951         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
952         assert!(updates_2.update_add_htlcs.is_empty());
953         assert!(updates_2.update_fulfill_htlcs.is_empty());
954         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
955         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
956         assert!(updates_2.update_fee.is_none());
957
958         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
959         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
960
961         expect_payment_failed!(nodes[0], our_payment_hash, false);
962
963         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
964         assert_eq!(msg_events.len(), 2);
965         let node_0_closing_signed = match msg_events[0] {
966                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
967                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
968                         (*msg).clone()
969                 },
970                 _ => panic!("Unexpected event"),
971         };
972         match msg_events[1] {
973                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
974                         assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
975                 },
976                 _ => panic!("Unexpected event"),
977         }
978
979         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
980         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
981         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
982         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
983         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
984         assert!(node_0_none.is_none());
985
986         assert!(nodes[0].node.list_channels().is_empty());
987
988         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
989         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
990         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
991         assert!(nodes[1].node.list_channels().is_empty());
992         assert!(nodes[2].node.list_channels().is_empty());
993 }
994
995 fn do_test_shutdown_rebroadcast(recv_count: u8) {
996         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
997         // messages delivered prior to disconnect
998         let chanmon_cfgs = create_chanmon_cfgs(3);
999         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1000         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1001         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1002         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1003         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1004
1005         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1006
1007         nodes[1].node.close_channel(&chan_1.2).unwrap();
1008         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1009         if recv_count > 0 {
1010                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
1011                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1012                 if recv_count > 1 {
1013                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
1014                 }
1015         }
1016
1017         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1018         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1019
1020         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1021         let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1022         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1023         let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1024
1025         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1026         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1027         assert!(node_1_shutdown == node_1_2nd_shutdown);
1028
1029         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1030         let node_0_2nd_shutdown = if recv_count > 0 {
1031                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1032                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1033                 node_0_2nd_shutdown
1034         } else {
1035                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1036                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1037                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1038         };
1039         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_2nd_shutdown);
1040
1041         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1042         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1043
1044         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1045         check_added_monitors!(nodes[2], 1);
1046         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1047         assert!(updates.update_add_htlcs.is_empty());
1048         assert!(updates.update_fail_htlcs.is_empty());
1049         assert!(updates.update_fail_malformed_htlcs.is_empty());
1050         assert!(updates.update_fee.is_none());
1051         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1052         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1053         check_added_monitors!(nodes[1], 1);
1054         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1055         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1056
1057         assert!(updates_2.update_add_htlcs.is_empty());
1058         assert!(updates_2.update_fail_htlcs.is_empty());
1059         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1060         assert!(updates_2.update_fee.is_none());
1061         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1062         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1063         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1064
1065         let events = nodes[0].node.get_and_clear_pending_events();
1066         assert_eq!(events.len(), 1);
1067         match events[0] {
1068                 Event::PaymentSent { ref payment_preimage } => {
1069                         assert_eq!(our_payment_preimage, *payment_preimage);
1070                 },
1071                 _ => panic!("Unexpected event"),
1072         }
1073
1074         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1075         if recv_count > 0 {
1076                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1077                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1078                 assert!(node_1_closing_signed.is_some());
1079         }
1080
1081         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1082         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1083
1084         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1085         let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1086         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1087         if recv_count == 0 {
1088                 // If all closing_signeds weren't delivered we can just resume where we left off...
1089                 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1090
1091                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1092                 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1093                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1094
1095                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1096                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1097                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1098
1099                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_3rd_shutdown);
1100                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1101
1102                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_3rd_shutdown);
1103                 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1104                 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1105
1106                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1107                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1108                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1109                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1110                 assert!(node_0_none.is_none());
1111         } else {
1112                 // If one node, however, received + responded with an identical closing_signed we end
1113                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1114                 // There isn't really anything better we can do simply, but in the future we might
1115                 // explore storing a set of recently-closed channels that got disconnected during
1116                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1117                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1118                 // transaction.
1119                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1120
1121                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1122                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1123                 assert_eq!(msg_events.len(), 1);
1124                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1125                         match action {
1126                                 &ErrorAction::SendErrorMessage { ref msg } => {
1127                                         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1128                                         assert_eq!(msg.channel_id, chan_1.2);
1129                                 },
1130                                 _ => panic!("Unexpected event!"),
1131                         }
1132                 } else { panic!("Needed SendErrorMessage close"); }
1133
1134                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1135                 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1136                 // closing_signed so we do it ourselves
1137                 check_closed_broadcast!(nodes[0], false);
1138                 check_added_monitors!(nodes[0], 1);
1139         }
1140
1141         assert!(nodes[0].node.list_channels().is_empty());
1142
1143         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1144         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1145         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1146         assert!(nodes[1].node.list_channels().is_empty());
1147         assert!(nodes[2].node.list_channels().is_empty());
1148 }
1149
1150 #[test]
1151 fn test_shutdown_rebroadcast() {
1152         do_test_shutdown_rebroadcast(0);
1153         do_test_shutdown_rebroadcast(1);
1154         do_test_shutdown_rebroadcast(2);
1155 }
1156
1157 #[test]
1158 fn fake_network_test() {
1159         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1160         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1161         let chanmon_cfgs = create_chanmon_cfgs(4);
1162         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1163         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1164         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1165
1166         // Create some initial channels
1167         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1168         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1169         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1170
1171         // Rebalance the network a bit by relaying one payment through all the channels...
1172         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1173         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1174         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1175         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1176
1177         // Send some more payments
1178         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1179         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1180         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1181
1182         // Test failure packets
1183         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1184         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1185
1186         // Add a new channel that skips 3
1187         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1188
1189         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1190         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1191         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1192         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1193         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1194         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1195         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1196
1197         // Do some rebalance loop payments, simultaneously
1198         let mut hops = Vec::with_capacity(3);
1199         hops.push(RouteHop {
1200                 pubkey: nodes[2].node.get_our_node_id(),
1201                 node_features: NodeFeatures::empty(),
1202                 short_channel_id: chan_2.0.contents.short_channel_id,
1203                 channel_features: ChannelFeatures::empty(),
1204                 fee_msat: 0,
1205                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1206         });
1207         hops.push(RouteHop {
1208                 pubkey: nodes[3].node.get_our_node_id(),
1209                 node_features: NodeFeatures::empty(),
1210                 short_channel_id: chan_3.0.contents.short_channel_id,
1211                 channel_features: ChannelFeatures::empty(),
1212                 fee_msat: 0,
1213                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1214         });
1215         hops.push(RouteHop {
1216                 pubkey: nodes[1].node.get_our_node_id(),
1217                 node_features: NodeFeatures::empty(),
1218                 short_channel_id: chan_4.0.contents.short_channel_id,
1219                 channel_features: ChannelFeatures::empty(),
1220                 fee_msat: 1000000,
1221                 cltv_expiry_delta: TEST_FINAL_CLTV,
1222         });
1223         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;
1224         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;
1225         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1226
1227         let mut hops = Vec::with_capacity(3);
1228         hops.push(RouteHop {
1229                 pubkey: nodes[3].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: 0,
1234                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1235         });
1236         hops.push(RouteHop {
1237                 pubkey: nodes[2].node.get_our_node_id(),
1238                 node_features: NodeFeatures::empty(),
1239                 short_channel_id: chan_3.0.contents.short_channel_id,
1240                 channel_features: ChannelFeatures::empty(),
1241                 fee_msat: 0,
1242                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1243         });
1244         hops.push(RouteHop {
1245                 pubkey: nodes[1].node.get_our_node_id(),
1246                 node_features: NodeFeatures::empty(),
1247                 short_channel_id: chan_2.0.contents.short_channel_id,
1248                 channel_features: ChannelFeatures::empty(),
1249                 fee_msat: 1000000,
1250                 cltv_expiry_delta: TEST_FINAL_CLTV,
1251         });
1252         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;
1253         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;
1254         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1255
1256         // Claim the rebalances...
1257         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1258         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1259
1260         // Add a duplicate new channel from 2 to 4
1261         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1262
1263         // Send some payments across both channels
1264         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1265         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1266         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1267
1268
1269         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1270         let events = nodes[0].node.get_and_clear_pending_msg_events();
1271         assert_eq!(events.len(), 0);
1272         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);
1273
1274         //TODO: Test that routes work again here as we've been notified that the channel is full
1275
1276         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1277         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1278         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1279
1280         // Close down the channels...
1281         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1282         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1283         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1284         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1285         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1286 }
1287
1288 #[test]
1289 fn holding_cell_htlc_counting() {
1290         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1291         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1292         // commitment dance rounds.
1293         let chanmon_cfgs = create_chanmon_cfgs(3);
1294         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1295         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1296         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1297         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1298         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1299         let logger = test_utils::TestLogger::new();
1300
1301         let mut payments = Vec::new();
1302         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1303                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1304                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1305                 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();
1306                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1307                 payments.push((payment_preimage, payment_hash));
1308         }
1309         check_added_monitors!(nodes[1], 1);
1310
1311         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1312         assert_eq!(events.len(), 1);
1313         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1314         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1315
1316         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1317         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1318         // another HTLC.
1319         let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1320         {
1321                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1322                 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();
1323                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1324                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1325                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1326                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1327         }
1328
1329         // This should also be true if we try to forward a payment.
1330         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1331         {
1332                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1333                 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();
1334                 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1335                 check_added_monitors!(nodes[0], 1);
1336         }
1337
1338         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1339         assert_eq!(events.len(), 1);
1340         let payment_event = SendEvent::from_event(events.pop().unwrap());
1341         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1342
1343         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1344         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1345         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1346         // fails), the second will process the resulting failure and fail the HTLC backward.
1347         expect_pending_htlcs_forwardable!(nodes[1]);
1348         expect_pending_htlcs_forwardable!(nodes[1]);
1349         check_added_monitors!(nodes[1], 1);
1350
1351         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1352         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1353         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1354
1355         let events = nodes[0].node.get_and_clear_pending_msg_events();
1356         assert_eq!(events.len(), 1);
1357         match events[0] {
1358                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1359                         assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1360                 },
1361                 _ => panic!("Unexpected event"),
1362         }
1363
1364         expect_payment_failed!(nodes[0], payment_hash_2, false);
1365
1366         // Now forward all the pending HTLCs and claim them back
1367         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1368         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1369         check_added_monitors!(nodes[2], 1);
1370
1371         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1372         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1373         check_added_monitors!(nodes[1], 1);
1374         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1375
1376         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1377         check_added_monitors!(nodes[1], 1);
1378         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1379
1380         for ref update in as_updates.update_add_htlcs.iter() {
1381                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1382         }
1383         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1384         check_added_monitors!(nodes[2], 1);
1385         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1386         check_added_monitors!(nodes[2], 1);
1387         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1388
1389         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1390         check_added_monitors!(nodes[1], 1);
1391         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1392         check_added_monitors!(nodes[1], 1);
1393         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1394
1395         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1396         check_added_monitors!(nodes[2], 1);
1397
1398         expect_pending_htlcs_forwardable!(nodes[2]);
1399
1400         let events = nodes[2].node.get_and_clear_pending_events();
1401         assert_eq!(events.len(), payments.len());
1402         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1403                 match event {
1404                         &Event::PaymentReceived { ref payment_hash, .. } => {
1405                                 assert_eq!(*payment_hash, *hash);
1406                         },
1407                         _ => panic!("Unexpected event"),
1408                 };
1409         }
1410
1411         for (preimage, _) in payments.drain(..) {
1412                 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1413         }
1414
1415         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1416 }
1417
1418 #[test]
1419 fn duplicate_htlc_test() {
1420         // Test that we accept duplicate payment_hash HTLCs across the network and that
1421         // claiming/failing them are all separate and don't affect each other
1422         let chanmon_cfgs = create_chanmon_cfgs(6);
1423         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1424         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1425         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1426
1427         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1428         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1429         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1430         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1431         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1432         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1433
1434         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1435
1436         *nodes[0].network_payment_count.borrow_mut() -= 1;
1437         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1438
1439         *nodes[0].network_payment_count.borrow_mut() -= 1;
1440         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1441
1442         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1443         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1444         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1445 }
1446
1447 #[test]
1448 fn test_duplicate_htlc_different_direction_onchain() {
1449         // Test that ChannelMonitor doesn't generate 2 preimage txn
1450         // when we have 2 HTLCs with same preimage that go across a node
1451         // in opposite directions.
1452         let chanmon_cfgs = create_chanmon_cfgs(2);
1453         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1454         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1455         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1456
1457         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1458         let logger = test_utils::TestLogger::new();
1459
1460         // balancing
1461         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1462
1463         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1464
1465         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1466         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();
1467         send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1468
1469         // Provide preimage to node 0 by claiming payment
1470         nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1471         check_added_monitors!(nodes[0], 1);
1472
1473         // Broadcast node 1 commitment txn
1474         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1475
1476         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1477         let mut has_both_htlcs = 0; // check htlcs match ones committed
1478         for outp in remote_txn[0].output.iter() {
1479                 if outp.value == 800_000 / 1000 {
1480                         has_both_htlcs += 1;
1481                 } else if outp.value == 900_000 / 1000 {
1482                         has_both_htlcs += 1;
1483                 }
1484         }
1485         assert_eq!(has_both_htlcs, 2);
1486
1487         mine_transaction(&nodes[0], &remote_txn[0]);
1488         check_added_monitors!(nodes[0], 1);
1489
1490         // Check we only broadcast 1 timeout tx
1491         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1492         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()) };
1493         assert_eq!(claim_txn.len(), 5);
1494         check_spends!(claim_txn[2], chan_1.3);
1495         check_spends!(claim_txn[3], claim_txn[2]);
1496         assert_eq!(htlc_pair.0.input.len(), 1);
1497         assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1498         check_spends!(htlc_pair.0, remote_txn[0]);
1499         assert_eq!(htlc_pair.1.input.len(), 1);
1500         assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1501         check_spends!(htlc_pair.1, remote_txn[0]);
1502
1503         let events = nodes[0].node.get_and_clear_pending_msg_events();
1504         assert_eq!(events.len(), 2);
1505         for e in events {
1506                 match e {
1507                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1508                         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, .. } } => {
1509                                 assert!(update_add_htlcs.is_empty());
1510                                 assert!(update_fail_htlcs.is_empty());
1511                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1512                                 assert!(update_fail_malformed_htlcs.is_empty());
1513                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1514                         },
1515                         _ => panic!("Unexpected event"),
1516                 }
1517         }
1518 }
1519
1520 #[test]
1521 fn test_basic_channel_reserve() {
1522         let chanmon_cfgs = create_chanmon_cfgs(2);
1523         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1524         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1525         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1526         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1527         let logger = test_utils::TestLogger::new();
1528
1529         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1530         let channel_reserve = chan_stat.channel_reserve_msat;
1531
1532         // The 2* and +1 are for the fee spike reserve.
1533         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1534         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1535         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1536         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1537         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();
1538         let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1539         match err {
1540                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1541                         match &fails[0] {
1542                                 &APIError::ChannelUnavailable{ref err} =>
1543                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1544                                 _ => panic!("Unexpected error variant"),
1545                         }
1546                 },
1547                 _ => panic!("Unexpected error variant"),
1548         }
1549         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1550         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);
1551
1552         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1553 }
1554
1555 #[test]
1556 fn test_fee_spike_violation_fails_htlc() {
1557         let chanmon_cfgs = create_chanmon_cfgs(2);
1558         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1559         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1560         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1561         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1562         let logger = test_utils::TestLogger::new();
1563
1564         macro_rules! get_route_and_payment_hash {
1565                 ($recv_value: expr) => {{
1566                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1567                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1568                         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();
1569                         (route, payment_hash, payment_preimage)
1570                 }}
1571         }
1572
1573         let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1574         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1575         let secp_ctx = Secp256k1::new();
1576         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1577
1578         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1579
1580         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1581         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1582         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1583         let msg = msgs::UpdateAddHTLC {
1584                 channel_id: chan.2,
1585                 htlc_id: 0,
1586                 amount_msat: htlc_msat,
1587                 payment_hash: payment_hash,
1588                 cltv_expiry: htlc_cltv,
1589                 onion_routing_packet: onion_packet,
1590         };
1591
1592         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1593
1594         // Now manually create the commitment_signed message corresponding to the update_add
1595         // nodes[0] just sent. In the code for construction of this message, "local" refers
1596         // to the sender of the message, and "remote" refers to the receiver.
1597
1598         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1599
1600         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1601
1602         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1603         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1604         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point) = {
1605                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1606                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1607                 let chan_signer = local_chan.get_signer();
1608                 let pubkeys = chan_signer.pubkeys();
1609                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1610                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1611                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
1612         };
1613         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point) = {
1614                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1615                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1616                 let chan_signer = remote_chan.get_signer();
1617                 let pubkeys = chan_signer.pubkeys();
1618                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1619                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
1620         };
1621
1622         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1623         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1624                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1625
1626         // Build the remote commitment transaction so we can sign it, and then later use the
1627         // signature for the commitment_signed message.
1628         let local_chan_balance = 1313;
1629
1630         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1631                 offered: false,
1632                 amount_msat: 3460001,
1633                 cltv_expiry: htlc_cltv,
1634                 payment_hash,
1635                 transaction_output_index: Some(1),
1636         };
1637
1638         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1639
1640         let res = {
1641                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1642                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1643                 let local_chan_signer = local_chan.get_signer();
1644                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1645                         commitment_number,
1646                         95000,
1647                         local_chan_balance,
1648                         commit_tx_keys.clone(),
1649                         feerate_per_kw,
1650                         &mut vec![(accepted_htlc_info, ())],
1651                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1652                 );
1653                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1654         };
1655
1656         let commit_signed_msg = msgs::CommitmentSigned {
1657                 channel_id: chan.2,
1658                 signature: res.0,
1659                 htlc_signatures: res.1
1660         };
1661
1662         // Send the commitment_signed message to the nodes[1].
1663         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1664         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1665
1666         // Send the RAA to nodes[1].
1667         let raa_msg = msgs::RevokeAndACK {
1668                 channel_id: chan.2,
1669                 per_commitment_secret: local_secret,
1670                 next_per_commitment_point: next_local_point
1671         };
1672         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1673
1674         let events = nodes[1].node.get_and_clear_pending_msg_events();
1675         assert_eq!(events.len(), 1);
1676         // Make sure the HTLC failed in the way we expect.
1677         match events[0] {
1678                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1679                         assert_eq!(update_fail_htlcs.len(), 1);
1680                         update_fail_htlcs[0].clone()
1681                 },
1682                 _ => panic!("Unexpected event"),
1683         };
1684         nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1685
1686         check_added_monitors!(nodes[1], 2);
1687 }
1688
1689 #[test]
1690 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1691         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1692         // Set the fee rate for the channel very high, to the point where the fundee
1693         // sending any above-dust amount would result in a channel reserve violation.
1694         // In this test we check that we would be prevented from sending an HTLC in
1695         // this situation.
1696         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1697         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1698         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1699         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1700         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1701         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1702         let logger = test_utils::TestLogger::new();
1703
1704         macro_rules! get_route_and_payment_hash {
1705                 ($recv_value: expr) => {{
1706                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1707                         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1708                         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();
1709                         (route, payment_hash, payment_preimage)
1710                 }}
1711         }
1712
1713         let (route, our_payment_hash, _) = get_route_and_payment_hash!(4843000);
1714         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1715                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1716         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1717         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);
1718 }
1719
1720 #[test]
1721 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1722         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1723         // Set the fee rate for the channel very high, to the point where the funder
1724         // receiving 1 update_add_htlc would result in them closing the channel due
1725         // to channel reserve violation. This close could also happen if the fee went
1726         // up a more realistic amount, but many HTLCs were outstanding at the time of
1727         // the update_add_htlc.
1728         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1729         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1730         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1731         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1732         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1733         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1734         let logger = test_utils::TestLogger::new();
1735
1736         macro_rules! get_route_and_payment_hash {
1737                 ($recv_value: expr) => {{
1738                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1739                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1740                         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();
1741                         (route, payment_hash, payment_preimage)
1742                 }}
1743         }
1744
1745         let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1746         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1747         let secp_ctx = Secp256k1::new();
1748         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1749         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1750         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1751         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1752         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1753         let msg = msgs::UpdateAddHTLC {
1754                 channel_id: chan.2,
1755                 htlc_id: 1,
1756                 amount_msat: htlc_msat + 1,
1757                 payment_hash: payment_hash,
1758                 cltv_expiry: htlc_cltv,
1759                 onion_routing_packet: onion_packet,
1760         };
1761
1762         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1763         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1764         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);
1765         assert_eq!(nodes[0].node.list_channels().len(), 0);
1766         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1767         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1768         check_added_monitors!(nodes[0], 1);
1769 }
1770
1771 #[test]
1772 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1773         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1774         // calculating our commitment transaction fee (this was previously broken).
1775         let chanmon_cfgs = create_chanmon_cfgs(2);
1776         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1777         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1778         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1779
1780         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1781         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1782         // transaction fee with 0 HTLCs (183 sats)).
1783         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98817000, InitFeatures::known(), InitFeatures::known());
1784
1785         let dust_amt = 546000; // Dust amount
1786         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1787         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1788         // commitment transaction fee.
1789         let (_, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1790 }
1791
1792 #[test]
1793 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1794         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1795         // calculating our counterparty's commitment transaction fee (this was previously broken).
1796         let chanmon_cfgs = create_chanmon_cfgs(2);
1797         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1798         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1799         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1800         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1801
1802         let payment_amt = 46000; // Dust amount
1803         // In the previous code, these first four payments would succeed.
1804         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1805         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1806         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1807         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1808
1809         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1810         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1811         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1812         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1813         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1814         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1815
1816         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1817         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1818         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1819         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1820 }
1821
1822 #[test]
1823 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1824         let chanmon_cfgs = create_chanmon_cfgs(3);
1825         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1826         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1827         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1828         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1829         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1830         let logger = test_utils::TestLogger::new();
1831
1832         macro_rules! get_route_and_payment_hash {
1833                 ($recv_value: expr) => {{
1834                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1835                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1836                         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();
1837                         (route, payment_hash, payment_preimage)
1838                 }}
1839         }
1840
1841         let feemsat = 239;
1842         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1843         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1844         let feerate = get_feerate!(nodes[0], chan.2);
1845
1846         // Add a 2* and +1 for the fee spike reserve.
1847         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1848         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;
1849         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1850
1851         // Add a pending HTLC.
1852         let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1853         let payment_event_1 = {
1854                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1855                 check_added_monitors!(nodes[0], 1);
1856
1857                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1858                 assert_eq!(events.len(), 1);
1859                 SendEvent::from_event(events.remove(0))
1860         };
1861         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1862
1863         // Attempt to trigger a channel reserve violation --> payment failure.
1864         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1865         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;
1866         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1867         let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1868
1869         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1870         let secp_ctx = Secp256k1::new();
1871         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1872         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1873         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1874         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1875         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1876         let msg = msgs::UpdateAddHTLC {
1877                 channel_id: chan.2,
1878                 htlc_id: 1,
1879                 amount_msat: htlc_msat + 1,
1880                 payment_hash: our_payment_hash_1,
1881                 cltv_expiry: htlc_cltv,
1882                 onion_routing_packet: onion_packet,
1883         };
1884
1885         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1886         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1887         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1888         assert_eq!(nodes[1].node.list_channels().len(), 1);
1889         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1890         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1891         check_added_monitors!(nodes[1], 1);
1892 }
1893
1894 #[test]
1895 fn test_inbound_outbound_capacity_is_not_zero() {
1896         let chanmon_cfgs = create_chanmon_cfgs(2);
1897         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1898         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1899         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1900         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1901         let channels0 = node_chanmgrs[0].list_channels();
1902         let channels1 = node_chanmgrs[1].list_channels();
1903         assert_eq!(channels0.len(), 1);
1904         assert_eq!(channels1.len(), 1);
1905
1906         assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1907         assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1908
1909         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1910         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1911 }
1912
1913 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1914         (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1915 }
1916
1917 #[test]
1918 fn test_channel_reserve_holding_cell_htlcs() {
1919         let chanmon_cfgs = create_chanmon_cfgs(3);
1920         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1921         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1922         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1923         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1924         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1925         let logger = test_utils::TestLogger::new();
1926
1927         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1928         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1929
1930         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1931         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1932
1933         macro_rules! get_route_and_payment_hash {
1934                 ($recv_value: expr) => {{
1935                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1936                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1937                         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();
1938                         (route, payment_hash, payment_preimage)
1939                 }}
1940         }
1941
1942         macro_rules! expect_forward {
1943                 ($node: expr) => {{
1944                         let mut events = $node.node.get_and_clear_pending_msg_events();
1945                         assert_eq!(events.len(), 1);
1946                         check_added_monitors!($node, 1);
1947                         let payment_event = SendEvent::from_event(events.remove(0));
1948                         payment_event
1949                 }}
1950         }
1951
1952         let feemsat = 239; // somehow we know?
1953         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1954         let feerate = get_feerate!(nodes[0], chan_1.2);
1955
1956         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1957
1958         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1959         {
1960                 let (mut route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0);
1961                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1962                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1963                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1964                         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)));
1965                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1966                 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);
1967         }
1968
1969         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1970         // nodes[0]'s wealth
1971         loop {
1972                 let amt_msat = recv_value_0 + total_fee_msat;
1973                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1974                 // Also, ensure that each payment has enough to be over the dust limit to
1975                 // ensure it'll be included in each commit tx fee calculation.
1976                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1977                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1978                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1979                         break;
1980                 }
1981                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1982
1983                 let (stat01_, stat11_, stat12_, stat22_) = (
1984                         get_channel_value_stat!(nodes[0], chan_1.2),
1985                         get_channel_value_stat!(nodes[1], chan_1.2),
1986                         get_channel_value_stat!(nodes[1], chan_2.2),
1987                         get_channel_value_stat!(nodes[2], chan_2.2),
1988                 );
1989
1990                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1991                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1992                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1993                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1994                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1995         }
1996
1997         // adding pending output.
1998         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1999         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2000         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2001         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2002         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2003         // cases where 1 msat over X amount will cause a payment failure, but anything less than
2004         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2005         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2006         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2007         // policy.
2008         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2009         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2010         let amt_msat_1 = recv_value_1 + total_fee_msat;
2011
2012         let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2013         let payment_event_1 = {
2014                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
2015                 check_added_monitors!(nodes[0], 1);
2016
2017                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2018                 assert_eq!(events.len(), 1);
2019                 SendEvent::from_event(events.remove(0))
2020         };
2021         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2022
2023         // channel reserve test with htlc pending output > 0
2024         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2025         {
2026                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2027                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2028                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2029                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2030         }
2031
2032         // split the rest to test holding cell
2033         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2034         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2035         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2036         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2037         {
2038                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2039                 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);
2040         }
2041
2042         // now see if they go through on both sides
2043         let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2044         // but this will stuck in the holding cell
2045         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2046         check_added_monitors!(nodes[0], 0);
2047         let events = nodes[0].node.get_and_clear_pending_events();
2048         assert_eq!(events.len(), 0);
2049
2050         // test with outbound holding cell amount > 0
2051         {
2052                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2053                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2054                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2055                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2056                 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);
2057         }
2058
2059         let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2060         // this will also stuck in the holding cell
2061         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2062         check_added_monitors!(nodes[0], 0);
2063         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2064         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2065
2066         // flush the pending htlc
2067         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2068         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2069         check_added_monitors!(nodes[1], 1);
2070
2071         // the pending htlc should be promoted to committed
2072         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2073         check_added_monitors!(nodes[0], 1);
2074         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2075
2076         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2077         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2078         // No commitment_signed so get_event_msg's assert(len == 1) passes
2079         check_added_monitors!(nodes[0], 1);
2080
2081         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2082         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2083         check_added_monitors!(nodes[1], 1);
2084
2085         expect_pending_htlcs_forwardable!(nodes[1]);
2086
2087         let ref payment_event_11 = expect_forward!(nodes[1]);
2088         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2089         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2090
2091         expect_pending_htlcs_forwardable!(nodes[2]);
2092         expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2093
2094         // flush the htlcs in the holding cell
2095         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2096         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2097         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2098         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2099         expect_pending_htlcs_forwardable!(nodes[1]);
2100
2101         let ref payment_event_3 = expect_forward!(nodes[1]);
2102         assert_eq!(payment_event_3.msgs.len(), 2);
2103         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2104         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2105
2106         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2107         expect_pending_htlcs_forwardable!(nodes[2]);
2108
2109         let events = nodes[2].node.get_and_clear_pending_events();
2110         assert_eq!(events.len(), 2);
2111         match events[0] {
2112                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2113                         assert_eq!(our_payment_hash_21, *payment_hash);
2114                         assert_eq!(*payment_secret, None);
2115                         assert_eq!(recv_value_21, amt);
2116                 },
2117                 _ => panic!("Unexpected event"),
2118         }
2119         match events[1] {
2120                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2121                         assert_eq!(our_payment_hash_22, *payment_hash);
2122                         assert_eq!(None, *payment_secret);
2123                         assert_eq!(recv_value_22, amt);
2124                 },
2125                 _ => panic!("Unexpected event"),
2126         }
2127
2128         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2129         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2130         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2131
2132         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2133         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2134         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2135
2136         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2137         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);
2138         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2139         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2140         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2141
2142         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2143         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2144 }
2145
2146 #[test]
2147 fn channel_reserve_in_flight_removes() {
2148         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2149         // can send to its counterparty, but due to update ordering, the other side may not yet have
2150         // considered those HTLCs fully removed.
2151         // This tests that we don't count HTLCs which will not be included in the next remote
2152         // commitment transaction towards the reserve value (as it implies no commitment transaction
2153         // will be generated which violates the remote reserve value).
2154         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2155         // To test this we:
2156         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2157         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2158         //    you only consider the value of the first HTLC, it may not),
2159         //  * start routing a third HTLC from A to B,
2160         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2161         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2162         //  * deliver the first fulfill from B
2163         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2164         //    claim,
2165         //  * deliver A's response CS and RAA.
2166         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2167         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2168         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2169         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2170         let chanmon_cfgs = create_chanmon_cfgs(2);
2171         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2172         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2173         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2174         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2175         let logger = test_utils::TestLogger::new();
2176
2177         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2178         // Route the first two HTLCs.
2179         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2180         let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2181
2182         // Start routing the third HTLC (this is just used to get everyone in the right state).
2183         let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2184         let send_1 = {
2185                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2186                 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();
2187                 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2188                 check_added_monitors!(nodes[0], 1);
2189                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2190                 assert_eq!(events.len(), 1);
2191                 SendEvent::from_event(events.remove(0))
2192         };
2193
2194         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2195         // initial fulfill/CS.
2196         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2197         check_added_monitors!(nodes[1], 1);
2198         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2199
2200         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2201         // remove the second HTLC when we send the HTLC back from B to A.
2202         assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2203         check_added_monitors!(nodes[1], 1);
2204         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2205
2206         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2207         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2208         check_added_monitors!(nodes[0], 1);
2209         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2210         expect_payment_sent!(nodes[0], payment_preimage_1);
2211
2212         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2213         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2214         check_added_monitors!(nodes[1], 1);
2215         // B is already AwaitingRAA, so cant generate a CS here
2216         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2217
2218         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2219         check_added_monitors!(nodes[1], 1);
2220         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2221
2222         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2223         check_added_monitors!(nodes[0], 1);
2224         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2225
2226         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2227         check_added_monitors!(nodes[1], 1);
2228         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2229
2230         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2231         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2232         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2233         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2234         // on-chain as necessary).
2235         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2236         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2237         check_added_monitors!(nodes[0], 1);
2238         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2239         expect_payment_sent!(nodes[0], payment_preimage_2);
2240
2241         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2242         check_added_monitors!(nodes[1], 1);
2243         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2244
2245         expect_pending_htlcs_forwardable!(nodes[1]);
2246         expect_payment_received!(nodes[1], payment_hash_3, 100000);
2247
2248         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2249         // resolve the second HTLC from A's point of view.
2250         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2251         check_added_monitors!(nodes[0], 1);
2252         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2253
2254         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2255         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2256         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2257         let send_2 = {
2258                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2259                 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();
2260                 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2261                 check_added_monitors!(nodes[1], 1);
2262                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2263                 assert_eq!(events.len(), 1);
2264                 SendEvent::from_event(events.remove(0))
2265         };
2266
2267         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2268         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2269         check_added_monitors!(nodes[0], 1);
2270         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2271
2272         // Now just resolve all the outstanding messages/HTLCs for completeness...
2273
2274         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2275         check_added_monitors!(nodes[1], 1);
2276         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2277
2278         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2279         check_added_monitors!(nodes[1], 1);
2280
2281         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2282         check_added_monitors!(nodes[0], 1);
2283         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2284
2285         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2286         check_added_monitors!(nodes[1], 1);
2287         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2288
2289         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2290         check_added_monitors!(nodes[0], 1);
2291
2292         expect_pending_htlcs_forwardable!(nodes[0]);
2293         expect_payment_received!(nodes[0], payment_hash_4, 10000);
2294
2295         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2296         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2297 }
2298
2299 #[test]
2300 fn channel_monitor_network_test() {
2301         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2302         // tests that ChannelMonitor is able to recover from various states.
2303         let chanmon_cfgs = create_chanmon_cfgs(5);
2304         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2305         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2306         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2307
2308         // Create some initial channels
2309         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2310         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2311         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2312         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2313
2314         // Make sure all nodes are at the same starting height
2315         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2316         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2317         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2318         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2319         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2320
2321         // Rebalance the network a bit by relaying one payment through all the channels...
2322         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2323         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2324         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2325         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2326
2327         // Simple case with no pending HTLCs:
2328         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2329         check_added_monitors!(nodes[1], 1);
2330         {
2331                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2332                 assert_eq!(node_txn.len(), 1);
2333                 mine_transaction(&nodes[0], &node_txn[0]);
2334                 check_added_monitors!(nodes[0], 1);
2335                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2336         }
2337         get_announce_close_broadcast_events(&nodes, 0, 1);
2338         assert_eq!(nodes[0].node.list_channels().len(), 0);
2339         assert_eq!(nodes[1].node.list_channels().len(), 1);
2340
2341         // One pending HTLC is discarded by the force-close:
2342         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2343
2344         // Simple case of one pending HTLC to HTLC-Timeout
2345         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2346         check_added_monitors!(nodes[1], 1);
2347         {
2348                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2349                 mine_transaction(&nodes[2], &node_txn[0]);
2350                 check_added_monitors!(nodes[2], 1);
2351                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2352         }
2353         get_announce_close_broadcast_events(&nodes, 1, 2);
2354         assert_eq!(nodes[1].node.list_channels().len(), 0);
2355         assert_eq!(nodes[2].node.list_channels().len(), 1);
2356
2357         macro_rules! claim_funds {
2358                 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2359                         {
2360                                 assert!($node.node.claim_funds($preimage, &None, $amount));
2361                                 check_added_monitors!($node, 1);
2362
2363                                 let events = $node.node.get_and_clear_pending_msg_events();
2364                                 assert_eq!(events.len(), 1);
2365                                 match events[0] {
2366                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2367                                                 assert!(update_add_htlcs.is_empty());
2368                                                 assert!(update_fail_htlcs.is_empty());
2369                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2370                                         },
2371                                         _ => panic!("Unexpected event"),
2372                                 };
2373                         }
2374                 }
2375         }
2376
2377         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2378         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2379         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2380         check_added_monitors!(nodes[2], 1);
2381         let node2_commitment_txid;
2382         {
2383                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2384                 node2_commitment_txid = node_txn[0].txid();
2385
2386                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2387                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2388                 mine_transaction(&nodes[3], &node_txn[0]);
2389                 check_added_monitors!(nodes[3], 1);
2390                 check_preimage_claim(&nodes[3], &node_txn);
2391         }
2392         get_announce_close_broadcast_events(&nodes, 2, 3);
2393         assert_eq!(nodes[2].node.list_channels().len(), 0);
2394         assert_eq!(nodes[3].node.list_channels().len(), 1);
2395
2396         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2397         // confusing us in the following tests.
2398         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().remove(&OutPoint { txid: chan_3.3.txid(), index: 0 }).unwrap();
2399
2400         // One pending HTLC to time out:
2401         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2402         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2403         // buffer space).
2404
2405         let (close_chan_update_1, close_chan_update_2) = {
2406                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2407                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2408                 assert_eq!(events.len(), 1);
2409                 let close_chan_update_1 = match events[0] {
2410                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2411                                 msg.clone()
2412                         },
2413                         _ => panic!("Unexpected event"),
2414                 };
2415                 check_added_monitors!(nodes[3], 1);
2416
2417                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2418                 {
2419                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2420                         node_txn.retain(|tx| {
2421                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2422                                         false
2423                                 } else { true }
2424                         });
2425                 }
2426
2427                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2428
2429                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2430                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2431
2432                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2433                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2434                 assert_eq!(events.len(), 1);
2435                 let close_chan_update_2 = match events[0] {
2436                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2437                                 msg.clone()
2438                         },
2439                         _ => panic!("Unexpected event"),
2440                 };
2441                 check_added_monitors!(nodes[4], 1);
2442                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2443
2444                 mine_transaction(&nodes[4], &node_txn[0]);
2445                 check_preimage_claim(&nodes[4], &node_txn);
2446                 (close_chan_update_1, close_chan_update_2)
2447         };
2448         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2449         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2450         assert_eq!(nodes[3].node.list_channels().len(), 0);
2451         assert_eq!(nodes[4].node.list_channels().len(), 0);
2452
2453         nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().insert(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon);
2454 }
2455
2456 #[test]
2457 fn test_justice_tx() {
2458         // Test justice txn built on revoked HTLC-Success tx, against both sides
2459         let mut alice_config = UserConfig::default();
2460         alice_config.channel_options.announced_channel = true;
2461         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2462         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2463         let mut bob_config = UserConfig::default();
2464         bob_config.channel_options.announced_channel = true;
2465         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2466         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2467         let user_cfgs = [Some(alice_config), Some(bob_config)];
2468         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2469         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2470         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2471         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2472         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2473         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2474         // Create some new channels:
2475         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2476
2477         // A pending HTLC which will be revoked:
2478         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2479         // Get the will-be-revoked local txn from nodes[0]
2480         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2481         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2482         assert_eq!(revoked_local_txn[0].input.len(), 1);
2483         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2484         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2485         assert_eq!(revoked_local_txn[1].input.len(), 1);
2486         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2487         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2488         // Revoke the old state
2489         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2490
2491         {
2492                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2493                 {
2494                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2495                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2496                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2497
2498                         check_spends!(node_txn[0], revoked_local_txn[0]);
2499                         node_txn.swap_remove(0);
2500                         node_txn.truncate(1);
2501                 }
2502                 check_added_monitors!(nodes[1], 1);
2503                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2504
2505                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2506                 // Verify broadcast of revoked HTLC-timeout
2507                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2508                 check_added_monitors!(nodes[0], 1);
2509                 // Broadcast revoked HTLC-timeout on node 1
2510                 mine_transaction(&nodes[1], &node_txn[1]);
2511                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2512         }
2513         get_announce_close_broadcast_events(&nodes, 0, 1);
2514
2515         assert_eq!(nodes[0].node.list_channels().len(), 0);
2516         assert_eq!(nodes[1].node.list_channels().len(), 0);
2517
2518         // We test justice_tx build by A on B's revoked HTLC-Success tx
2519         // Create some new channels:
2520         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2521         {
2522                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2523                 node_txn.clear();
2524         }
2525
2526         // A pending HTLC which will be revoked:
2527         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2528         // Get the will-be-revoked local txn from B
2529         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2530         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2531         assert_eq!(revoked_local_txn[0].input.len(), 1);
2532         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2533         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2534         // Revoke the old state
2535         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2536         {
2537                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2538                 {
2539                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2540                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2541                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2542
2543                         check_spends!(node_txn[0], revoked_local_txn[0]);
2544                         node_txn.swap_remove(0);
2545                 }
2546                 check_added_monitors!(nodes[0], 1);
2547                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2548
2549                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2550                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2551                 check_added_monitors!(nodes[1], 1);
2552                 mine_transaction(&nodes[0], &node_txn[1]);
2553                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2554         }
2555         get_announce_close_broadcast_events(&nodes, 0, 1);
2556         assert_eq!(nodes[0].node.list_channels().len(), 0);
2557         assert_eq!(nodes[1].node.list_channels().len(), 0);
2558 }
2559
2560 #[test]
2561 fn revoked_output_claim() {
2562         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2563         // transaction is broadcast by its counterparty
2564         let chanmon_cfgs = create_chanmon_cfgs(2);
2565         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2566         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2567         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2568         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2569         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2570         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2571         assert_eq!(revoked_local_txn.len(), 1);
2572         // Only output is the full channel value back to nodes[0]:
2573         assert_eq!(revoked_local_txn[0].output.len(), 1);
2574         // Send a payment through, updating everyone's latest commitment txn
2575         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2576
2577         // Inform nodes[1] that nodes[0] broadcast a stale tx
2578         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2579         check_added_monitors!(nodes[1], 1);
2580         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2581         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2582
2583         check_spends!(node_txn[0], revoked_local_txn[0]);
2584         check_spends!(node_txn[1], chan_1.3);
2585
2586         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2587         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2588         get_announce_close_broadcast_events(&nodes, 0, 1);
2589         check_added_monitors!(nodes[0], 1)
2590 }
2591
2592 #[test]
2593 fn claim_htlc_outputs_shared_tx() {
2594         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2595         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2596         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
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
2601         // Create some new channel:
2602         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2603
2604         // Rebalance the network to generate htlc in the two directions
2605         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2606         // 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
2607         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2608         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2609
2610         // Get the will-be-revoked local txn from node[0]
2611         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2612         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2613         assert_eq!(revoked_local_txn[0].input.len(), 1);
2614         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2615         assert_eq!(revoked_local_txn[1].input.len(), 1);
2616         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2617         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2618         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2619
2620         //Revoke the old state
2621         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2622
2623         {
2624                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2625                 check_added_monitors!(nodes[0], 1);
2626                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2627                 check_added_monitors!(nodes[1], 1);
2628                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2629                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2630
2631                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2632                 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2633
2634                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2635                 check_spends!(node_txn[0], revoked_local_txn[0]);
2636
2637                 let mut witness_lens = BTreeSet::new();
2638                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2639                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2640                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2641                 assert_eq!(witness_lens.len(), 3);
2642                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2643                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2644                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2645
2646                 // Next nodes[1] broadcasts its current local tx state:
2647                 assert_eq!(node_txn[1].input.len(), 1);
2648                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2649
2650                 assert_eq!(node_txn[2].input.len(), 1);
2651                 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2652                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2653                 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2654                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2655                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2656         }
2657         get_announce_close_broadcast_events(&nodes, 0, 1);
2658         assert_eq!(nodes[0].node.list_channels().len(), 0);
2659         assert_eq!(nodes[1].node.list_channels().len(), 0);
2660 }
2661
2662 #[test]
2663 fn claim_htlc_outputs_single_tx() {
2664         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2665         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2666         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2667         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2668         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2669         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2670
2671         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2672
2673         // Rebalance the network to generate htlc in the two directions
2674         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2675         // 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
2676         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2677         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2678         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2679
2680         // Get the will-be-revoked local txn from node[0]
2681         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2682
2683         //Revoke the old state
2684         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2685
2686         {
2687                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2688                 check_added_monitors!(nodes[0], 1);
2689                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2690                 check_added_monitors!(nodes[1], 1);
2691                 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2692
2693                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2694                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2695
2696                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2697                 assert_eq!(node_txn.len(), 9);
2698                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2699                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2700                 // 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)
2701                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2702
2703                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2704                 assert_eq!(node_txn[0].input.len(), 1);
2705                 check_spends!(node_txn[0], chan_1.3);
2706                 assert_eq!(node_txn[1].input.len(), 1);
2707                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2708                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2709                 check_spends!(node_txn[1], node_txn[0]);
2710
2711                 // Justice transactions are indices 1-2-4
2712                 assert_eq!(node_txn[2].input.len(), 1);
2713                 assert_eq!(node_txn[3].input.len(), 1);
2714                 assert_eq!(node_txn[4].input.len(), 1);
2715
2716                 check_spends!(node_txn[2], revoked_local_txn[0]);
2717                 check_spends!(node_txn[3], revoked_local_txn[0]);
2718                 check_spends!(node_txn[4], revoked_local_txn[0]);
2719
2720                 let mut witness_lens = BTreeSet::new();
2721                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2722                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2723                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2724                 assert_eq!(witness_lens.len(), 3);
2725                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2726                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2727                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2728         }
2729         get_announce_close_broadcast_events(&nodes, 0, 1);
2730         assert_eq!(nodes[0].node.list_channels().len(), 0);
2731         assert_eq!(nodes[1].node.list_channels().len(), 0);
2732 }
2733
2734 #[test]
2735 fn test_htlc_on_chain_success() {
2736         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2737         // the preimage backward accordingly. So here we test that ChannelManager is
2738         // broadcasting the right event to other nodes in payment path.
2739         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2740         // A --------------------> B ----------------------> C (preimage)
2741         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2742         // commitment transaction was broadcast.
2743         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2744         // towards B.
2745         // B should be able to claim via preimage if A then broadcasts its local tx.
2746         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2747         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2748         // PaymentSent event).
2749
2750         let chanmon_cfgs = create_chanmon_cfgs(3);
2751         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2752         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2753         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2754
2755         // Create some initial channels
2756         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2757         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2758
2759         // Rebalance the network a bit by relaying one payment through all the channels...
2760         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2761         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2762
2763         let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2764         let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2765
2766         // Broadcast legit commitment tx from C on B's chain
2767         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2768         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2769         assert_eq!(commitment_tx.len(), 1);
2770         check_spends!(commitment_tx[0], chan_2.3);
2771         nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2772         nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2773         check_added_monitors!(nodes[2], 2);
2774         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2775         assert!(updates.update_add_htlcs.is_empty());
2776         assert!(updates.update_fail_htlcs.is_empty());
2777         assert!(updates.update_fail_malformed_htlcs.is_empty());
2778         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2779
2780         mine_transaction(&nodes[2], &commitment_tx[0]);
2781         check_closed_broadcast!(nodes[2], false);
2782         check_added_monitors!(nodes[2], 1);
2783         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)
2784         assert_eq!(node_txn.len(), 5);
2785         assert_eq!(node_txn[0], node_txn[3]);
2786         assert_eq!(node_txn[1], node_txn[4]);
2787         assert_eq!(node_txn[2], commitment_tx[0]);
2788         check_spends!(node_txn[0], commitment_tx[0]);
2789         check_spends!(node_txn[1], commitment_tx[0]);
2790         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2791         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2792         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2793         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2794         assert_eq!(node_txn[0].lock_time, 0);
2795         assert_eq!(node_txn[1].lock_time, 0);
2796
2797         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2798         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2799         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2800         {
2801                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2802                 assert_eq!(added_monitors.len(), 1);
2803                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2804                 added_monitors.clear();
2805         }
2806         let events = nodes[1].node.get_and_clear_pending_msg_events();
2807         {
2808                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2809                 assert_eq!(added_monitors.len(), 2);
2810                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2811                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2812                 added_monitors.clear();
2813         }
2814         assert_eq!(events.len(), 2);
2815         match events[0] {
2816                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2817                 _ => panic!("Unexpected event"),
2818         }
2819         match events[1] {
2820                 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, .. } } => {
2821                         assert!(update_add_htlcs.is_empty());
2822                         assert!(update_fail_htlcs.is_empty());
2823                         assert_eq!(update_fulfill_htlcs.len(), 1);
2824                         assert!(update_fail_malformed_htlcs.is_empty());
2825                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2826                 },
2827                 _ => panic!("Unexpected event"),
2828         };
2829         macro_rules! check_tx_local_broadcast {
2830                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2831                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2832                         assert_eq!(node_txn.len(), 5);
2833                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2834                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2835                         check_spends!(node_txn[0], $commitment_tx);
2836                         check_spends!(node_txn[1], $commitment_tx);
2837                         assert_ne!(node_txn[0].lock_time, 0);
2838                         assert_ne!(node_txn[1].lock_time, 0);
2839                         if $htlc_offered {
2840                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2841                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2842                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2843                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2844                         } else {
2845                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2846                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2847                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2848                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2849                         }
2850                         check_spends!(node_txn[2], $chan_tx);
2851                         check_spends!(node_txn[3], node_txn[2]);
2852                         check_spends!(node_txn[4], node_txn[2]);
2853                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2854                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2855                         assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2856                         assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2857                         assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2858                         assert_ne!(node_txn[3].lock_time, 0);
2859                         assert_ne!(node_txn[4].lock_time, 0);
2860                         node_txn.clear();
2861                 } }
2862         }
2863         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2864         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2865         // timeout-claim of the output that nodes[2] just claimed via success.
2866         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2867
2868         // Broadcast legit commitment tx from A on B's chain
2869         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2870         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2871         check_spends!(commitment_tx[0], chan_1.3);
2872         mine_transaction(&nodes[1], &commitment_tx[0]);
2873         check_closed_broadcast!(nodes[1], false);
2874         check_added_monitors!(nodes[1], 1);
2875         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2876         assert_eq!(node_txn.len(), 4);
2877         check_spends!(node_txn[0], commitment_tx[0]);
2878         assert_eq!(node_txn[0].input.len(), 2);
2879         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2880         assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2881         assert_eq!(node_txn[0].lock_time, 0);
2882         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2883         check_spends!(node_txn[1], chan_1.3);
2884         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2885         check_spends!(node_txn[2], node_txn[1]);
2886         check_spends!(node_txn[3], node_txn[1]);
2887         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2888         // we already checked the same situation with A.
2889
2890         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2891         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2892         connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] });
2893         check_closed_broadcast!(nodes[0], false);
2894         check_added_monitors!(nodes[0], 1);
2895         let events = nodes[0].node.get_and_clear_pending_events();
2896         assert_eq!(events.len(), 2);
2897         let mut first_claimed = false;
2898         for event in events {
2899                 match event {
2900                         Event::PaymentSent { payment_preimage } => {
2901                                 if payment_preimage == our_payment_preimage {
2902                                         assert!(!first_claimed);
2903                                         first_claimed = true;
2904                                 } else {
2905                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2906                                 }
2907                         },
2908                         _ => panic!("Unexpected event"),
2909                 }
2910         }
2911         check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2912 }
2913
2914 #[test]
2915 fn test_htlc_on_chain_timeout() {
2916         // Test that in case of a unilateral close onchain, we detect the state of output and
2917         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2918         // broadcasting the right event to other nodes in payment path.
2919         // A ------------------> B ----------------------> C (timeout)
2920         //    B's commitment tx                 C's commitment tx
2921         //            \                                  \
2922         //         B's HTLC timeout tx               B's timeout tx
2923
2924         let chanmon_cfgs = create_chanmon_cfgs(3);
2925         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2926         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2927         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2928
2929         // Create some intial channels
2930         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2931         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2932
2933         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2934         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2935         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2936
2937         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2938
2939         // Broadcast legit commitment tx from C on B's chain
2940         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2941         check_spends!(commitment_tx[0], chan_2.3);
2942         nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2943         check_added_monitors!(nodes[2], 0);
2944         expect_pending_htlcs_forwardable!(nodes[2]);
2945         check_added_monitors!(nodes[2], 1);
2946
2947         let events = nodes[2].node.get_and_clear_pending_msg_events();
2948         assert_eq!(events.len(), 1);
2949         match events[0] {
2950                 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, .. } } => {
2951                         assert!(update_add_htlcs.is_empty());
2952                         assert!(!update_fail_htlcs.is_empty());
2953                         assert!(update_fulfill_htlcs.is_empty());
2954                         assert!(update_fail_malformed_htlcs.is_empty());
2955                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2956                 },
2957                 _ => panic!("Unexpected event"),
2958         };
2959         mine_transaction(&nodes[2], &commitment_tx[0]);
2960         check_closed_broadcast!(nodes[2], false);
2961         check_added_monitors!(nodes[2], 1);
2962         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2963         assert_eq!(node_txn.len(), 1);
2964         check_spends!(node_txn[0], chan_2.3);
2965         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2966
2967         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2968         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2969         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2970         mine_transaction(&nodes[1], &commitment_tx[0]);
2971         let timeout_tx;
2972         {
2973                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2974                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2975                 assert_eq!(node_txn[0], node_txn[3]);
2976                 assert_eq!(node_txn[1], node_txn[4]);
2977
2978                 check_spends!(node_txn[2], commitment_tx[0]);
2979                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2980
2981                 check_spends!(node_txn[0], chan_2.3);
2982                 check_spends!(node_txn[1], node_txn[0]);
2983                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2984                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2985
2986                 timeout_tx = node_txn[2].clone();
2987                 node_txn.clear();
2988         }
2989
2990         mine_transaction(&nodes[1], &timeout_tx);
2991         check_added_monitors!(nodes[1], 1);
2992         check_closed_broadcast!(nodes[1], false);
2993         {
2994                 // B will rebroadcast a fee-bumped timeout transaction here.
2995                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2996                 assert_eq!(node_txn.len(), 1);
2997                 check_spends!(node_txn[0], commitment_tx[0]);
2998         }
2999
3000         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3001         {
3002                 // B will rebroadcast its own holder commitment transaction here...just because
3003                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3004                 assert_eq!(node_txn.len(), 1);
3005                 check_spends!(node_txn[0], chan_2.3);
3006         }
3007
3008         expect_pending_htlcs_forwardable!(nodes[1]);
3009         check_added_monitors!(nodes[1], 1);
3010         let events = nodes[1].node.get_and_clear_pending_msg_events();
3011         assert_eq!(events.len(), 1);
3012         match events[0] {
3013                 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, .. } } => {
3014                         assert!(update_add_htlcs.is_empty());
3015                         assert!(!update_fail_htlcs.is_empty());
3016                         assert!(update_fulfill_htlcs.is_empty());
3017                         assert!(update_fail_malformed_htlcs.is_empty());
3018                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3019                 },
3020                 _ => panic!("Unexpected event"),
3021         };
3022
3023         // Broadcast legit commitment tx from B on A's chain
3024         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3025         check_spends!(commitment_tx[0], chan_1.3);
3026
3027         mine_transaction(&nodes[0], &commitment_tx[0]);
3028
3029         check_closed_broadcast!(nodes[0], false);
3030         check_added_monitors!(nodes[0], 1);
3031         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3032         assert_eq!(node_txn.len(), 3);
3033         check_spends!(node_txn[0], commitment_tx[0]);
3034         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3035         check_spends!(node_txn[1], chan_1.3);
3036         check_spends!(node_txn[2], node_txn[1]);
3037         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3038         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3039 }
3040
3041 #[test]
3042 fn test_simple_commitment_revoked_fail_backward() {
3043         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3044         // and fail backward accordingly.
3045
3046         let chanmon_cfgs = create_chanmon_cfgs(3);
3047         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3048         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3049         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3050
3051         // Create some initial channels
3052         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3053         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3054
3055         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3056         // Get the will-be-revoked local txn from nodes[2]
3057         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3058         // Revoke the old state
3059         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3060
3061         let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3062
3063         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3064         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3065         check_added_monitors!(nodes[1], 1);
3066         check_closed_broadcast!(nodes[1], false);
3067
3068         expect_pending_htlcs_forwardable!(nodes[1]);
3069         check_added_monitors!(nodes[1], 1);
3070         let events = nodes[1].node.get_and_clear_pending_msg_events();
3071         assert_eq!(events.len(), 1);
3072         match events[0] {
3073                 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, .. } } => {
3074                         assert!(update_add_htlcs.is_empty());
3075                         assert_eq!(update_fail_htlcs.len(), 1);
3076                         assert!(update_fulfill_htlcs.is_empty());
3077                         assert!(update_fail_malformed_htlcs.is_empty());
3078                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3079
3080                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3081                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3082
3083                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3084                         assert_eq!(events.len(), 1);
3085                         match events[0] {
3086                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3087                                 _ => panic!("Unexpected event"),
3088                         }
3089                         expect_payment_failed!(nodes[0], payment_hash, false);
3090                 },
3091                 _ => panic!("Unexpected event"),
3092         }
3093 }
3094
3095 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3096         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3097         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3098         // commitment transaction anymore.
3099         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3100         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3101         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3102         // technically disallowed and we should probably handle it reasonably.
3103         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3104         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3105         // transactions:
3106         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3107         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3108         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3109         //   and once they revoke the previous commitment transaction (allowing us to send a new
3110         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3111         let chanmon_cfgs = create_chanmon_cfgs(3);
3112         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3113         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3114         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3115
3116         // Create some initial channels
3117         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3118         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3119
3120         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3121         // Get the will-be-revoked local txn from nodes[2]
3122         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3123         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3124         // Revoke the old state
3125         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3126
3127         let value = if use_dust {
3128                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3129                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3130                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3131         } else { 3000000 };
3132
3133         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3134         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3135         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3136
3137         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3138         expect_pending_htlcs_forwardable!(nodes[2]);
3139         check_added_monitors!(nodes[2], 1);
3140         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3141         assert!(updates.update_add_htlcs.is_empty());
3142         assert!(updates.update_fulfill_htlcs.is_empty());
3143         assert!(updates.update_fail_malformed_htlcs.is_empty());
3144         assert_eq!(updates.update_fail_htlcs.len(), 1);
3145         assert!(updates.update_fee.is_none());
3146         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3147         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3148         // Drop the last RAA from 3 -> 2
3149
3150         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3151         expect_pending_htlcs_forwardable!(nodes[2]);
3152         check_added_monitors!(nodes[2], 1);
3153         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3154         assert!(updates.update_add_htlcs.is_empty());
3155         assert!(updates.update_fulfill_htlcs.is_empty());
3156         assert!(updates.update_fail_malformed_htlcs.is_empty());
3157         assert_eq!(updates.update_fail_htlcs.len(), 1);
3158         assert!(updates.update_fee.is_none());
3159         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3160         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3161         check_added_monitors!(nodes[1], 1);
3162         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3163         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3164         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3165         check_added_monitors!(nodes[2], 1);
3166
3167         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3168         expect_pending_htlcs_forwardable!(nodes[2]);
3169         check_added_monitors!(nodes[2], 1);
3170         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3171         assert!(updates.update_add_htlcs.is_empty());
3172         assert!(updates.update_fulfill_htlcs.is_empty());
3173         assert!(updates.update_fail_malformed_htlcs.is_empty());
3174         assert_eq!(updates.update_fail_htlcs.len(), 1);
3175         assert!(updates.update_fee.is_none());
3176         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3177         // At this point first_payment_hash has dropped out of the latest two commitment
3178         // transactions that nodes[1] is tracking...
3179         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3180         check_added_monitors!(nodes[1], 1);
3181         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3182         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3183         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3184         check_added_monitors!(nodes[2], 1);
3185
3186         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3187         // on nodes[2]'s RAA.
3188         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3189         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3190         let logger = test_utils::TestLogger::new();
3191         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();
3192         nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3193         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3194         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3195         check_added_monitors!(nodes[1], 0);
3196
3197         if deliver_bs_raa {
3198                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3199                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3200                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3201                 check_added_monitors!(nodes[1], 1);
3202                 let events = nodes[1].node.get_and_clear_pending_events();
3203                 assert_eq!(events.len(), 1);
3204                 match events[0] {
3205                         Event::PendingHTLCsForwardable { .. } => { },
3206                         _ => panic!("Unexpected event"),
3207                 };
3208                 // Deliberately don't process the pending fail-back so they all fail back at once after
3209                 // block connection just like the !deliver_bs_raa case
3210         }
3211
3212         let mut failed_htlcs = HashSet::new();
3213         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3214
3215         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3216         check_added_monitors!(nodes[1], 1);
3217         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3218
3219         let events = nodes[1].node.get_and_clear_pending_events();
3220         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3221         match events[0] {
3222                 Event::PaymentFailed { ref payment_hash, .. } => {
3223                         assert_eq!(*payment_hash, fourth_payment_hash);
3224                 },
3225                 _ => panic!("Unexpected event"),
3226         }
3227         if !deliver_bs_raa {
3228                 match events[1] {
3229                         Event::PendingHTLCsForwardable { .. } => { },
3230                         _ => panic!("Unexpected event"),
3231                 };
3232         }
3233         nodes[1].node.process_pending_htlc_forwards();
3234         check_added_monitors!(nodes[1], 1);
3235
3236         let events = nodes[1].node.get_and_clear_pending_msg_events();
3237         assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3238         match events[if deliver_bs_raa { 1 } else { 0 }] {
3239                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3240                 _ => panic!("Unexpected event"),
3241         }
3242         if deliver_bs_raa {
3243                 match events[0] {
3244                         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, .. } } => {
3245                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3246                                 assert_eq!(update_add_htlcs.len(), 1);
3247                                 assert!(update_fulfill_htlcs.is_empty());
3248                                 assert!(update_fail_htlcs.is_empty());
3249                                 assert!(update_fail_malformed_htlcs.is_empty());
3250                         },
3251                         _ => panic!("Unexpected event"),
3252                 }
3253         }
3254         match events[if deliver_bs_raa { 2 } else { 1 }] {
3255                 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, .. } } => {
3256                         assert!(update_add_htlcs.is_empty());
3257                         assert_eq!(update_fail_htlcs.len(), 3);
3258                         assert!(update_fulfill_htlcs.is_empty());
3259                         assert!(update_fail_malformed_htlcs.is_empty());
3260                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3261
3262                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3263                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3264                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3265
3266                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3267
3268                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3269                         // If we delivered B's RAA we got an unknown preimage error, not something
3270                         // that we should update our routing table for.
3271                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3272                         for event in events {
3273                                 match event {
3274                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3275                                         _ => panic!("Unexpected event"),
3276                                 }
3277                         }
3278                         let events = nodes[0].node.get_and_clear_pending_events();
3279                         assert_eq!(events.len(), 3);
3280                         match events[0] {
3281                                 Event::PaymentFailed { ref payment_hash, .. } => {
3282                                         assert!(failed_htlcs.insert(payment_hash.0));
3283                                 },
3284                                 _ => panic!("Unexpected event"),
3285                         }
3286                         match events[1] {
3287                                 Event::PaymentFailed { ref payment_hash, .. } => {
3288                                         assert!(failed_htlcs.insert(payment_hash.0));
3289                                 },
3290                                 _ => panic!("Unexpected event"),
3291                         }
3292                         match events[2] {
3293                                 Event::PaymentFailed { ref payment_hash, .. } => {
3294                                         assert!(failed_htlcs.insert(payment_hash.0));
3295                                 },
3296                                 _ => panic!("Unexpected event"),
3297                         }
3298                 },
3299                 _ => panic!("Unexpected event"),
3300         }
3301
3302         assert!(failed_htlcs.contains(&first_payment_hash.0));
3303         assert!(failed_htlcs.contains(&second_payment_hash.0));
3304         assert!(failed_htlcs.contains(&third_payment_hash.0));
3305 }
3306
3307 #[test]
3308 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3309         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3310         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3311         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3312         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3313 }
3314
3315 #[test]
3316 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3317         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3318         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3319         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3320         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3321 }
3322
3323 #[test]
3324 fn fail_backward_pending_htlc_upon_channel_failure() {
3325         let chanmon_cfgs = create_chanmon_cfgs(2);
3326         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3327         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3328         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3329         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3330         let logger = test_utils::TestLogger::new();
3331
3332         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3333         {
3334                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3335                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3336                 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();
3337                 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3338                 check_added_monitors!(nodes[0], 1);
3339
3340                 let payment_event = {
3341                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3342                         assert_eq!(events.len(), 1);
3343                         SendEvent::from_event(events.remove(0))
3344                 };
3345                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3346                 assert_eq!(payment_event.msgs.len(), 1);
3347         }
3348
3349         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3350         let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3351         {
3352                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3353                 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();
3354                 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3355                 check_added_monitors!(nodes[0], 0);
3356
3357                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3358         }
3359
3360         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3361         {
3362                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3363
3364                 let secp_ctx = Secp256k1::new();
3365                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3366                 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3367                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3368                 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();
3369                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3370                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3371                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3372
3373                 // Send a 0-msat update_add_htlc to fail the channel.
3374                 let update_add_htlc = msgs::UpdateAddHTLC {
3375                         channel_id: chan.2,
3376                         htlc_id: 0,
3377                         amount_msat: 0,
3378                         payment_hash,
3379                         cltv_expiry,
3380                         onion_routing_packet,
3381                 };
3382                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3383         }
3384
3385         // Check that Alice fails backward the pending HTLC from the second payment.
3386         expect_payment_failed!(nodes[0], failed_payment_hash, true);
3387         check_closed_broadcast!(nodes[0], true);
3388         check_added_monitors!(nodes[0], 1);
3389 }
3390
3391 #[test]
3392 fn test_htlc_ignore_latest_remote_commitment() {
3393         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3394         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3395         let chanmon_cfgs = create_chanmon_cfgs(2);
3396         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3397         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3398         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3399         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3400
3401         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3402         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3403         check_closed_broadcast!(nodes[0], false);
3404         check_added_monitors!(nodes[0], 1);
3405
3406         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3407         assert_eq!(node_txn.len(), 2);
3408
3409         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3410         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3411         check_closed_broadcast!(nodes[1], false);
3412         check_added_monitors!(nodes[1], 1);
3413
3414         // Duplicate the connect_block call since this may happen due to other listeners
3415         // registering new transactions
3416         header.prev_blockhash = header.block_hash();
3417         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3418 }
3419
3420 #[test]
3421 fn test_force_close_fail_back() {
3422         // Check which HTLCs are failed-backwards on channel force-closure
3423         let chanmon_cfgs = create_chanmon_cfgs(3);
3424         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3425         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3426         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3427         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3428         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3429         let logger = test_utils::TestLogger::new();
3430
3431         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3432
3433         let mut payment_event = {
3434                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3435                 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();
3436                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3437                 check_added_monitors!(nodes[0], 1);
3438
3439                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3440                 assert_eq!(events.len(), 1);
3441                 SendEvent::from_event(events.remove(0))
3442         };
3443
3444         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3445         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3446
3447         expect_pending_htlcs_forwardable!(nodes[1]);
3448
3449         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3450         assert_eq!(events_2.len(), 1);
3451         payment_event = SendEvent::from_event(events_2.remove(0));
3452         assert_eq!(payment_event.msgs.len(), 1);
3453
3454         check_added_monitors!(nodes[1], 1);
3455         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3456         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3457         check_added_monitors!(nodes[2], 1);
3458         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3459
3460         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3461         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3462         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3463
3464         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3465         check_closed_broadcast!(nodes[2], false);
3466         check_added_monitors!(nodes[2], 1);
3467         let tx = {
3468                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3469                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3470                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3471                 // back to nodes[1] upon timeout otherwise.
3472                 assert_eq!(node_txn.len(), 1);
3473                 node_txn.remove(0)
3474         };
3475
3476         mine_transaction(&nodes[1], &tx);
3477
3478         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3479         check_closed_broadcast!(nodes[1], false);
3480         check_added_monitors!(nodes[1], 1);
3481
3482         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3483         {
3484                 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3485                 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3486                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3487         }
3488         mine_transaction(&nodes[2], &tx);
3489         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3490         assert_eq!(node_txn.len(), 1);
3491         assert_eq!(node_txn[0].input.len(), 1);
3492         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3493         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3494         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3495
3496         check_spends!(node_txn[0], tx);
3497 }
3498
3499 #[test]
3500 fn test_simple_peer_disconnect() {
3501         // Test that we can reconnect when there are no lost messages
3502         let chanmon_cfgs = create_chanmon_cfgs(3);
3503         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3504         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3505         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3506         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3507         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3508
3509         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3510         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3511         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3512
3513         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3514         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3515         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3516         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3517
3518         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3519         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3520         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3521
3522         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3523         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3524         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3525         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3526
3527         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3528         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3529
3530         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3531         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3532
3533         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3534         {
3535                 let events = nodes[0].node.get_and_clear_pending_events();
3536                 assert_eq!(events.len(), 2);
3537                 match events[0] {
3538                         Event::PaymentSent { payment_preimage } => {
3539                                 assert_eq!(payment_preimage, payment_preimage_3);
3540                         },
3541                         _ => panic!("Unexpected event"),
3542                 }
3543                 match events[1] {
3544                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3545                                 assert_eq!(payment_hash, payment_hash_5);
3546                                 assert!(rejected_by_dest);
3547                         },
3548                         _ => panic!("Unexpected event"),
3549                 }
3550         }
3551
3552         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3553         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3554 }
3555
3556 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3557         // Test that we can reconnect when in-flight HTLC updates get dropped
3558         let chanmon_cfgs = create_chanmon_cfgs(2);
3559         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3560         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3561         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3562         if messages_delivered == 0 {
3563                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3564                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3565         } else {
3566                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3567         }
3568
3569         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3570
3571         let logger = test_utils::TestLogger::new();
3572         let payment_event = {
3573                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3574                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3575                         &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3576                         &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3577                 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3578                 check_added_monitors!(nodes[0], 1);
3579
3580                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3581                 assert_eq!(events.len(), 1);
3582                 SendEvent::from_event(events.remove(0))
3583         };
3584         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3585
3586         if messages_delivered < 2 {
3587                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3588         } else {
3589                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3590                 if messages_delivered >= 3 {
3591                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3592                         check_added_monitors!(nodes[1], 1);
3593                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3594
3595                         if messages_delivered >= 4 {
3596                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3597                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3598                                 check_added_monitors!(nodes[0], 1);
3599
3600                                 if messages_delivered >= 5 {
3601                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3602                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3603                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3604                                         check_added_monitors!(nodes[0], 1);
3605
3606                                         if messages_delivered >= 6 {
3607                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3608                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3609                                                 check_added_monitors!(nodes[1], 1);
3610                                         }
3611                                 }
3612                         }
3613                 }
3614         }
3615
3616         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3617         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3618         if messages_delivered < 3 {
3619                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3620                 // received on either side, both sides will need to resend them.
3621                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3622         } else if messages_delivered == 3 {
3623                 // nodes[0] still wants its RAA + commitment_signed
3624                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3625         } else if messages_delivered == 4 {
3626                 // nodes[0] still wants its commitment_signed
3627                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3628         } else if messages_delivered == 5 {
3629                 // nodes[1] still wants its final RAA
3630                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3631         } else if messages_delivered == 6 {
3632                 // Everything was delivered...
3633                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3634         }
3635
3636         let events_1 = nodes[1].node.get_and_clear_pending_events();
3637         assert_eq!(events_1.len(), 1);
3638         match events_1[0] {
3639                 Event::PendingHTLCsForwardable { .. } => { },
3640                 _ => panic!("Unexpected event"),
3641         };
3642
3643         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3644         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3645         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3646
3647         nodes[1].node.process_pending_htlc_forwards();
3648
3649         let events_2 = nodes[1].node.get_and_clear_pending_events();
3650         assert_eq!(events_2.len(), 1);
3651         match events_2[0] {
3652                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3653                         assert_eq!(payment_hash_1, *payment_hash);
3654                         assert_eq!(*payment_secret, None);
3655                         assert_eq!(amt, 1000000);
3656                 },
3657                 _ => panic!("Unexpected event"),
3658         }
3659
3660         nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3661         check_added_monitors!(nodes[1], 1);
3662
3663         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3664         assert_eq!(events_3.len(), 1);
3665         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3666                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3667                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3668                         assert!(updates.update_add_htlcs.is_empty());
3669                         assert!(updates.update_fail_htlcs.is_empty());
3670                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3671                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3672                         assert!(updates.update_fee.is_none());
3673                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3674                 },
3675                 _ => panic!("Unexpected event"),
3676         };
3677
3678         if messages_delivered >= 1 {
3679                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3680
3681                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3682                 assert_eq!(events_4.len(), 1);
3683                 match events_4[0] {
3684                         Event::PaymentSent { ref payment_preimage } => {
3685                                 assert_eq!(payment_preimage_1, *payment_preimage);
3686                         },
3687                         _ => panic!("Unexpected event"),
3688                 }
3689
3690                 if messages_delivered >= 2 {
3691                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3692                         check_added_monitors!(nodes[0], 1);
3693                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3694
3695                         if messages_delivered >= 3 {
3696                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3697                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3698                                 check_added_monitors!(nodes[1], 1);
3699
3700                                 if messages_delivered >= 4 {
3701                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3702                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3703                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3704                                         check_added_monitors!(nodes[1], 1);
3705
3706                                         if messages_delivered >= 5 {
3707                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3708                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3709                                                 check_added_monitors!(nodes[0], 1);
3710                                         }
3711                                 }
3712                         }
3713                 }
3714         }
3715
3716         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3717         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3718         if messages_delivered < 2 {
3719                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3720                 //TODO: Deduplicate PaymentSent events, then enable this if:
3721                 //if messages_delivered < 1 {
3722                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3723                         assert_eq!(events_4.len(), 1);
3724                         match events_4[0] {
3725                                 Event::PaymentSent { ref payment_preimage } => {
3726                                         assert_eq!(payment_preimage_1, *payment_preimage);
3727                                 },
3728                                 _ => panic!("Unexpected event"),
3729                         }
3730                 //}
3731         } else if messages_delivered == 2 {
3732                 // nodes[0] still wants its RAA + commitment_signed
3733                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3734         } else if messages_delivered == 3 {
3735                 // nodes[0] still wants its commitment_signed
3736                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3737         } else if messages_delivered == 4 {
3738                 // nodes[1] still wants its final RAA
3739                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3740         } else if messages_delivered == 5 {
3741                 // Everything was delivered...
3742                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3743         }
3744
3745         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3746         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3747         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3748
3749         // Channel should still work fine...
3750         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3751         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3752                 &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3753                 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3754         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3755         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3756 }
3757
3758 #[test]
3759 fn test_drop_messages_peer_disconnect_a() {
3760         do_test_drop_messages_peer_disconnect(0);
3761         do_test_drop_messages_peer_disconnect(1);
3762         do_test_drop_messages_peer_disconnect(2);
3763         do_test_drop_messages_peer_disconnect(3);
3764 }
3765
3766 #[test]
3767 fn test_drop_messages_peer_disconnect_b() {
3768         do_test_drop_messages_peer_disconnect(4);
3769         do_test_drop_messages_peer_disconnect(5);
3770         do_test_drop_messages_peer_disconnect(6);
3771 }
3772
3773 #[test]
3774 fn test_funding_peer_disconnect() {
3775         // Test that we can lock in our funding tx while disconnected
3776         let chanmon_cfgs = create_chanmon_cfgs(2);
3777         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3778         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3779         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3780         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3781
3782         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3783         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3784
3785         confirm_transaction(&nodes[0], &tx);
3786         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3787         assert_eq!(events_1.len(), 1);
3788         match events_1[0] {
3789                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3790                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3791                 },
3792                 _ => panic!("Unexpected event"),
3793         }
3794
3795         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3796
3797         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3798         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3799
3800         confirm_transaction(&nodes[1], &tx);
3801         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3802         assert_eq!(events_2.len(), 2);
3803         let funding_locked = match events_2[0] {
3804                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3805                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3806                         msg.clone()
3807                 },
3808                 _ => panic!("Unexpected event"),
3809         };
3810         let bs_announcement_sigs = match events_2[1] {
3811                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3812                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3813                         msg.clone()
3814                 },
3815                 _ => panic!("Unexpected event"),
3816         };
3817
3818         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3819
3820         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3821         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3822         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3823         assert_eq!(events_3.len(), 2);
3824         let as_announcement_sigs = match events_3[0] {
3825                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3826                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3827                         msg.clone()
3828                 },
3829                 _ => panic!("Unexpected event"),
3830         };
3831         let (as_announcement, as_update) = match events_3[1] {
3832                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3833                         (msg.clone(), update_msg.clone())
3834                 },
3835                 _ => panic!("Unexpected event"),
3836         };
3837
3838         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3839         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3840         assert_eq!(events_4.len(), 1);
3841         let (_, bs_update) = match events_4[0] {
3842                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3843                         (msg.clone(), update_msg.clone())
3844                 },
3845                 _ => panic!("Unexpected event"),
3846         };
3847
3848         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3849         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3850         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3851
3852         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3853         let logger = test_utils::TestLogger::new();
3854         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();
3855         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3856         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3857 }
3858
3859 #[test]
3860 fn test_drop_messages_peer_disconnect_dual_htlc() {
3861         // Test that we can handle reconnecting when both sides of a channel have pending
3862         // commitment_updates when we disconnect.
3863         let chanmon_cfgs = create_chanmon_cfgs(2);
3864         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3865         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3866         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3867         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3868         let logger = test_utils::TestLogger::new();
3869
3870         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3871
3872         // Now try to send a second payment which will fail to send
3873         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3874         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3875         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();
3876         nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3877         check_added_monitors!(nodes[0], 1);
3878
3879         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3880         assert_eq!(events_1.len(), 1);
3881         match events_1[0] {
3882                 MessageSendEvent::UpdateHTLCs { .. } => {},
3883                 _ => panic!("Unexpected event"),
3884         }
3885
3886         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3887         check_added_monitors!(nodes[1], 1);
3888
3889         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3890         assert_eq!(events_2.len(), 1);
3891         match events_2[0] {
3892                 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 } } => {
3893                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3894                         assert!(update_add_htlcs.is_empty());
3895                         assert_eq!(update_fulfill_htlcs.len(), 1);
3896                         assert!(update_fail_htlcs.is_empty());
3897                         assert!(update_fail_malformed_htlcs.is_empty());
3898                         assert!(update_fee.is_none());
3899
3900                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3901                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3902                         assert_eq!(events_3.len(), 1);
3903                         match events_3[0] {
3904                                 Event::PaymentSent { ref payment_preimage } => {
3905                                         assert_eq!(*payment_preimage, payment_preimage_1);
3906                                 },
3907                                 _ => panic!("Unexpected event"),
3908                         }
3909
3910                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3911                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3912                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3913                         check_added_monitors!(nodes[0], 1);
3914                 },
3915                 _ => panic!("Unexpected event"),
3916         }
3917
3918         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3919         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3920
3921         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3922         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3923         assert_eq!(reestablish_1.len(), 1);
3924         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3925         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3926         assert_eq!(reestablish_2.len(), 1);
3927
3928         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3929         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3930         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3931         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3932
3933         assert!(as_resp.0.is_none());
3934         assert!(bs_resp.0.is_none());
3935
3936         assert!(bs_resp.1.is_none());
3937         assert!(bs_resp.2.is_none());
3938
3939         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3940
3941         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3942         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3943         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3944         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3945         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3946         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3947         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3948         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3949         // No commitment_signed so get_event_msg's assert(len == 1) passes
3950         check_added_monitors!(nodes[1], 1);
3951
3952         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3953         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3954         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3955         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3956         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3957         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3958         assert!(bs_second_commitment_signed.update_fee.is_none());
3959         check_added_monitors!(nodes[1], 1);
3960
3961         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3962         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3963         assert!(as_commitment_signed.update_add_htlcs.is_empty());
3964         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3965         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3966         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3967         assert!(as_commitment_signed.update_fee.is_none());
3968         check_added_monitors!(nodes[0], 1);
3969
3970         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3971         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3972         // No commitment_signed so get_event_msg's assert(len == 1) passes
3973         check_added_monitors!(nodes[0], 1);
3974
3975         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3976         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3977         // No commitment_signed so get_event_msg's assert(len == 1) passes
3978         check_added_monitors!(nodes[1], 1);
3979
3980         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3981         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3982         check_added_monitors!(nodes[1], 1);
3983
3984         expect_pending_htlcs_forwardable!(nodes[1]);
3985
3986         let events_5 = nodes[1].node.get_and_clear_pending_events();
3987         assert_eq!(events_5.len(), 1);
3988         match events_5[0] {
3989                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
3990                         assert_eq!(payment_hash_2, *payment_hash);
3991                         assert_eq!(*payment_secret, None);
3992                 },
3993                 _ => panic!("Unexpected event"),
3994         }
3995
3996         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3997         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3998         check_added_monitors!(nodes[0], 1);
3999
4000         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4001 }
4002
4003 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4004         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4005         // to avoid our counterparty failing the channel.
4006         let chanmon_cfgs = create_chanmon_cfgs(2);
4007         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4008         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4009         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4010
4011         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4012         let logger = test_utils::TestLogger::new();
4013
4014         let our_payment_hash = if send_partial_mpp {
4015                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4016                 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();
4017                 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4018                 let payment_secret = PaymentSecret([0xdb; 32]);
4019                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4020                 // indicates there are more HTLCs coming.
4021                 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.
4022                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height).unwrap();
4023                 check_added_monitors!(nodes[0], 1);
4024                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4025                 assert_eq!(events.len(), 1);
4026                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4027                 // hop should *not* yet generate any PaymentReceived event(s).
4028                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4029                 our_payment_hash
4030         } else {
4031                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4032         };
4033
4034         let mut block = Block {
4035                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4036                 txdata: vec![],
4037         };
4038         connect_block(&nodes[0], &block);
4039         connect_block(&nodes[1], &block);
4040         for _ in CHAN_CONFIRM_DEPTH + 2 ..TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4041                 block.header.prev_blockhash = block.block_hash();
4042                 connect_block(&nodes[0], &block);
4043                 connect_block(&nodes[1], &block);
4044         }
4045
4046         expect_pending_htlcs_forwardable!(nodes[1]);
4047
4048         check_added_monitors!(nodes[1], 1);
4049         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4050         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4051         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4052         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4053         assert!(htlc_timeout_updates.update_fee.is_none());
4054
4055         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4056         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4057         // 100_000 msat as u64, followed by a height of TEST_FINAL_CLTV + 2 as u32
4058         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4059         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(TEST_FINAL_CLTV + 2));
4060         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4061 }
4062
4063 #[test]
4064 fn test_htlc_timeout() {
4065         do_test_htlc_timeout(true);
4066         do_test_htlc_timeout(false);
4067 }
4068
4069 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4070         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4071         let chanmon_cfgs = create_chanmon_cfgs(3);
4072         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4073         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4074         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4075         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4076         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4077
4078         // Make sure all nodes are at the same starting height
4079         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4080         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4081         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4082
4083         let logger = test_utils::TestLogger::new();
4084
4085         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4086         let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4087         {
4088                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4089                 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();
4090                 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4091         }
4092         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4093         check_added_monitors!(nodes[1], 1);
4094
4095         // Now attempt to route a second payment, which should be placed in the holding cell
4096         let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4097         if forwarded_htlc {
4098                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4099                 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();
4100                 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4101                 check_added_monitors!(nodes[0], 1);
4102                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4103                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4104                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4105                 expect_pending_htlcs_forwardable!(nodes[1]);
4106                 check_added_monitors!(nodes[1], 0);
4107         } else {
4108                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4109                 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();
4110                 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4111                 check_added_monitors!(nodes[1], 0);
4112         }
4113
4114         connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4115         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4116         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4117         connect_blocks(&nodes[1], 1);
4118
4119         if forwarded_htlc {
4120                 expect_pending_htlcs_forwardable!(nodes[1]);
4121                 check_added_monitors!(nodes[1], 1);
4122                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4123                 assert_eq!(fail_commit.len(), 1);
4124                 match fail_commit[0] {
4125                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4126                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4127                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4128                         },
4129                         _ => unreachable!(),
4130                 }
4131                 expect_payment_failed!(nodes[0], second_payment_hash, false);
4132                 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4133                         match update {
4134                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4135                                 _ => panic!("Unexpected event"),
4136                         }
4137                 } else {
4138                         panic!("Unexpected event");
4139                 }
4140         } else {
4141                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4142         }
4143 }
4144
4145 #[test]
4146 fn test_holding_cell_htlc_add_timeouts() {
4147         do_test_holding_cell_htlc_add_timeouts(false);
4148         do_test_holding_cell_htlc_add_timeouts(true);
4149 }
4150
4151 #[test]
4152 fn test_invalid_channel_announcement() {
4153         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4154         let secp_ctx = Secp256k1::new();
4155         let chanmon_cfgs = create_chanmon_cfgs(2);
4156         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4157         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4158         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4159
4160         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4161
4162         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4163         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4164         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4165         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4166
4167         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 } );
4168
4169         let as_bitcoin_key = as_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4170         let bs_bitcoin_key = bs_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4171
4172         let as_network_key = nodes[0].node.get_our_node_id();
4173         let bs_network_key = nodes[1].node.get_our_node_id();
4174
4175         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4176
4177         let mut chan_announcement;
4178
4179         macro_rules! dummy_unsigned_msg {
4180                 () => {
4181                         msgs::UnsignedChannelAnnouncement {
4182                                 features: ChannelFeatures::known(),
4183                                 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4184                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4185                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4186                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4187                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4188                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4189                                 excess_data: Vec::new(),
4190                         };
4191                 }
4192         }
4193
4194         macro_rules! sign_msg {
4195                 ($unsigned_msg: expr) => {
4196                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4197                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_signer().inner.funding_key);
4198                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_signer().inner.funding_key);
4199                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4200                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4201                         chan_announcement = msgs::ChannelAnnouncement {
4202                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4203                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4204                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4205                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4206                                 contents: $unsigned_msg
4207                         }
4208                 }
4209         }
4210
4211         let unsigned_msg = dummy_unsigned_msg!();
4212         sign_msg!(unsigned_msg);
4213         assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4214         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 } );
4215
4216         // Configured with Network::Testnet
4217         let mut unsigned_msg = dummy_unsigned_msg!();
4218         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4219         sign_msg!(unsigned_msg);
4220         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4221
4222         let mut unsigned_msg = dummy_unsigned_msg!();
4223         unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4224         sign_msg!(unsigned_msg);
4225         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4226 }
4227
4228 #[test]
4229 fn test_no_txn_manager_serialize_deserialize() {
4230         let chanmon_cfgs = create_chanmon_cfgs(2);
4231         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4232         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4233         let logger: test_utils::TestLogger;
4234         let fee_estimator: test_utils::TestFeeEstimator;
4235         let persister: test_utils::TestPersister;
4236         let new_chain_monitor: test_utils::TestChainMonitor;
4237         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4238         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4239
4240         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4241
4242         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4243
4244         let nodes_0_serialized = nodes[0].node.encode();
4245         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4246         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4247
4248         logger = test_utils::TestLogger::new();
4249         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4250         persister = test_utils::TestPersister::new();
4251         let keys_manager = &chanmon_cfgs[0].keys_manager;
4252         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4253         nodes[0].chain_monitor = &new_chain_monitor;
4254         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4255         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4256                 &mut chan_0_monitor_read, keys_manager).unwrap();
4257         assert!(chan_0_monitor_read.is_empty());
4258
4259         let mut nodes_0_read = &nodes_0_serialized[..];
4260         let config = UserConfig::default();
4261         let (_, nodes_0_deserialized_tmp) = {
4262                 let mut channel_monitors = HashMap::new();
4263                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4264                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4265                         default_config: config,
4266                         keys_manager,
4267                         fee_estimator: &fee_estimator,
4268                         chain_monitor: nodes[0].chain_monitor,
4269                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4270                         logger: &logger,
4271                         channel_monitors,
4272                 }).unwrap()
4273         };
4274         nodes_0_deserialized = nodes_0_deserialized_tmp;
4275         assert!(nodes_0_read.is_empty());
4276
4277         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4278         nodes[0].node = &nodes_0_deserialized;
4279         assert_eq!(nodes[0].node.list_channels().len(), 1);
4280         check_added_monitors!(nodes[0], 1);
4281
4282         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4283         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4284         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4285         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4286
4287         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4288         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4289         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4290         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4291
4292         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4293         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4294         for node in nodes.iter() {
4295                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4296                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4297                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4298         }
4299
4300         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4301 }
4302
4303 #[test]
4304 fn test_manager_serialize_deserialize_events() {
4305         // This test makes sure the events field in ChannelManager survives de/serialization
4306         let chanmon_cfgs = create_chanmon_cfgs(2);
4307         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4308         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4309         let fee_estimator: test_utils::TestFeeEstimator;
4310         let persister: test_utils::TestPersister;
4311         let logger: test_utils::TestLogger;
4312         let new_chain_monitor: test_utils::TestChainMonitor;
4313         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4314         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4315
4316         // Start creating a channel, but stop right before broadcasting the funding transaction
4317         let channel_value = 100000;
4318         let push_msat = 10001;
4319         let a_flags = InitFeatures::known();
4320         let b_flags = InitFeatures::known();
4321         let node_a = nodes.remove(0);
4322         let node_b = nodes.remove(0);
4323         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4324         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()));
4325         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()));
4326
4327         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4328
4329         node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4330         check_added_monitors!(node_a, 0);
4331
4332         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()));
4333         {
4334                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4335                 assert_eq!(added_monitors.len(), 1);
4336                 assert_eq!(added_monitors[0].0, funding_output);
4337                 added_monitors.clear();
4338         }
4339
4340         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()));
4341         {
4342                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4343                 assert_eq!(added_monitors.len(), 1);
4344                 assert_eq!(added_monitors[0].0, funding_output);
4345                 added_monitors.clear();
4346         }
4347         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4348
4349         nodes.push(node_a);
4350         nodes.push(node_b);
4351
4352         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4353         let nodes_0_serialized = nodes[0].node.encode();
4354         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4355         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4356
4357         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4358         logger = test_utils::TestLogger::new();
4359         persister = test_utils::TestPersister::new();
4360         let keys_manager = &chanmon_cfgs[0].keys_manager;
4361         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4362         nodes[0].chain_monitor = &new_chain_monitor;
4363         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4364         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4365                 &mut chan_0_monitor_read, keys_manager).unwrap();
4366         assert!(chan_0_monitor_read.is_empty());
4367
4368         let mut nodes_0_read = &nodes_0_serialized[..];
4369         let config = UserConfig::default();
4370         let (_, nodes_0_deserialized_tmp) = {
4371                 let mut channel_monitors = HashMap::new();
4372                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4373                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4374                         default_config: config,
4375                         keys_manager,
4376                         fee_estimator: &fee_estimator,
4377                         chain_monitor: nodes[0].chain_monitor,
4378                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4379                         logger: &logger,
4380                         channel_monitors,
4381                 }).unwrap()
4382         };
4383         nodes_0_deserialized = nodes_0_deserialized_tmp;
4384         assert!(nodes_0_read.is_empty());
4385
4386         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4387
4388         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4389         nodes[0].node = &nodes_0_deserialized;
4390
4391         // After deserializing, make sure the funding_transaction is still held by the channel manager
4392         let events_4 = nodes[0].node.get_and_clear_pending_events();
4393         assert_eq!(events_4.len(), 0);
4394         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4395         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4396
4397         // Make sure the channel is functioning as though the de/serialization never happened
4398         assert_eq!(nodes[0].node.list_channels().len(), 1);
4399         check_added_monitors!(nodes[0], 1);
4400
4401         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4402         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4403         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4404         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4405
4406         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4407         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4408         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4409         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4410
4411         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4412         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4413         for node in nodes.iter() {
4414                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4415                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4416                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4417         }
4418
4419         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4420 }
4421
4422 #[test]
4423 fn test_simple_manager_serialize_deserialize() {
4424         let chanmon_cfgs = create_chanmon_cfgs(2);
4425         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4426         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4427         let logger: test_utils::TestLogger;
4428         let fee_estimator: test_utils::TestFeeEstimator;
4429         let persister: test_utils::TestPersister;
4430         let new_chain_monitor: test_utils::TestChainMonitor;
4431         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4432         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4433         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4434
4435         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4436         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4437
4438         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4439
4440         let nodes_0_serialized = nodes[0].node.encode();
4441         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4442         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4443
4444         logger = test_utils::TestLogger::new();
4445         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4446         persister = test_utils::TestPersister::new();
4447         let keys_manager = &chanmon_cfgs[0].keys_manager;
4448         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4449         nodes[0].chain_monitor = &new_chain_monitor;
4450         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4451         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4452                 &mut chan_0_monitor_read, keys_manager).unwrap();
4453         assert!(chan_0_monitor_read.is_empty());
4454
4455         let mut nodes_0_read = &nodes_0_serialized[..];
4456         let (_, nodes_0_deserialized_tmp) = {
4457                 let mut channel_monitors = HashMap::new();
4458                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4459                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4460                         default_config: UserConfig::default(),
4461                         keys_manager,
4462                         fee_estimator: &fee_estimator,
4463                         chain_monitor: nodes[0].chain_monitor,
4464                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4465                         logger: &logger,
4466                         channel_monitors,
4467                 }).unwrap()
4468         };
4469         nodes_0_deserialized = nodes_0_deserialized_tmp;
4470         assert!(nodes_0_read.is_empty());
4471
4472         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4473         nodes[0].node = &nodes_0_deserialized;
4474         check_added_monitors!(nodes[0], 1);
4475
4476         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4477
4478         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4479         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4480 }
4481
4482 #[test]
4483 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4484         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4485         let chanmon_cfgs = create_chanmon_cfgs(4);
4486         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4487         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4488         let logger: test_utils::TestLogger;
4489         let fee_estimator: test_utils::TestFeeEstimator;
4490         let persister: test_utils::TestPersister;
4491         let new_chain_monitor: test_utils::TestChainMonitor;
4492         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4493         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4494         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4495         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4496         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4497
4498         let mut node_0_stale_monitors_serialized = Vec::new();
4499         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4500                 let mut writer = test_utils::TestVecWriter(Vec::new());
4501                 monitor.1.write(&mut writer).unwrap();
4502                 node_0_stale_monitors_serialized.push(writer.0);
4503         }
4504
4505         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4506
4507         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4508         let nodes_0_serialized = nodes[0].node.encode();
4509
4510         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4511         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4512         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4513         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4514
4515         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4516         // nodes[3])
4517         let mut node_0_monitors_serialized = Vec::new();
4518         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4519                 let mut writer = test_utils::TestVecWriter(Vec::new());
4520                 monitor.1.write(&mut writer).unwrap();
4521                 node_0_monitors_serialized.push(writer.0);
4522         }
4523
4524         logger = test_utils::TestLogger::new();
4525         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4526         persister = test_utils::TestPersister::new();
4527         let keys_manager = &chanmon_cfgs[0].keys_manager;
4528         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4529         nodes[0].chain_monitor = &new_chain_monitor;
4530
4531
4532         let mut node_0_stale_monitors = Vec::new();
4533         for serialized in node_0_stale_monitors_serialized.iter() {
4534                 let mut read = &serialized[..];
4535                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4536                 assert!(read.is_empty());
4537                 node_0_stale_monitors.push(monitor);
4538         }
4539
4540         let mut node_0_monitors = Vec::new();
4541         for serialized in node_0_monitors_serialized.iter() {
4542                 let mut read = &serialized[..];
4543                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4544                 assert!(read.is_empty());
4545                 node_0_monitors.push(monitor);
4546         }
4547
4548         let mut nodes_0_read = &nodes_0_serialized[..];
4549         if let Err(msgs::DecodeError::InvalidValue) =
4550                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4551                 default_config: UserConfig::default(),
4552                 keys_manager,
4553                 fee_estimator: &fee_estimator,
4554                 chain_monitor: nodes[0].chain_monitor,
4555                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4556                 logger: &logger,
4557                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4558         }) { } else {
4559                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4560         };
4561
4562         let mut nodes_0_read = &nodes_0_serialized[..];
4563         let (_, nodes_0_deserialized_tmp) =
4564                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4565                 default_config: UserConfig::default(),
4566                 keys_manager,
4567                 fee_estimator: &fee_estimator,
4568                 chain_monitor: nodes[0].chain_monitor,
4569                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4570                 logger: &logger,
4571                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4572         }).unwrap();
4573         nodes_0_deserialized = nodes_0_deserialized_tmp;
4574         assert!(nodes_0_read.is_empty());
4575
4576         { // Channel close should result in a commitment tx and an HTLC tx
4577                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4578                 assert_eq!(txn.len(), 2);
4579                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4580                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4581         }
4582
4583         for monitor in node_0_monitors.drain(..) {
4584                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4585                 check_added_monitors!(nodes[0], 1);
4586         }
4587         nodes[0].node = &nodes_0_deserialized;
4588
4589         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4590         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4591         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4592         //... and we can even still claim the payment!
4593         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4594
4595         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4596         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4597         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4598         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4599         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4600         assert_eq!(msg_events.len(), 1);
4601         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4602                 match action {
4603                         &ErrorAction::SendErrorMessage { ref msg } => {
4604                                 assert_eq!(msg.channel_id, channel_id);
4605                         },
4606                         _ => panic!("Unexpected event!"),
4607                 }
4608         }
4609 }
4610
4611 macro_rules! check_spendable_outputs {
4612         ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4613                 {
4614                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4615                         let mut txn = Vec::new();
4616                         let mut all_outputs = Vec::new();
4617                         let secp_ctx = Secp256k1::new();
4618                         for event in events.drain(..) {
4619                                 match event {
4620                                         Event::SpendableOutputs { mut outputs } => {
4621                                                 for outp in outputs.drain(..) {
4622                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4623                                                         all_outputs.push(outp);
4624                                                 }
4625                                         },
4626                                         _ => panic!("Unexpected event"),
4627                                 };
4628                         }
4629                         if all_outputs.len() > 1 {
4630                                 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) {
4631                                         txn.push(tx);
4632                                 }
4633                         }
4634                         txn
4635                 }
4636         }
4637 }
4638
4639 #[test]
4640 fn test_claim_sizeable_push_msat() {
4641         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4642         let chanmon_cfgs = create_chanmon_cfgs(2);
4643         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4644         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4645         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4646
4647         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4648         nodes[1].node.force_close_channel(&chan.2).unwrap();
4649         check_closed_broadcast!(nodes[1], false);
4650         check_added_monitors!(nodes[1], 1);
4651         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4652         assert_eq!(node_txn.len(), 1);
4653         check_spends!(node_txn[0], chan.3);
4654         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
4655
4656         mine_transaction(&nodes[1], &node_txn[0]);
4657         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4658
4659         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4660         assert_eq!(spend_txn.len(), 1);
4661         check_spends!(spend_txn[0], node_txn[0]);
4662 }
4663
4664 #[test]
4665 fn test_claim_on_remote_sizeable_push_msat() {
4666         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4667         // to_remote output is encumbered by a P2WPKH
4668         let chanmon_cfgs = create_chanmon_cfgs(2);
4669         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4670         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4671         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4672
4673         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4674         nodes[0].node.force_close_channel(&chan.2).unwrap();
4675         check_closed_broadcast!(nodes[0], false);
4676         check_added_monitors!(nodes[0], 1);
4677
4678         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4679         assert_eq!(node_txn.len(), 1);
4680         check_spends!(node_txn[0], chan.3);
4681         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
4682
4683         mine_transaction(&nodes[1], &node_txn[0]);
4684         check_closed_broadcast!(nodes[1], false);
4685         check_added_monitors!(nodes[1], 1);
4686         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4687
4688         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4689         assert_eq!(spend_txn.len(), 1);
4690         check_spends!(spend_txn[0], node_txn[0]);
4691 }
4692
4693 #[test]
4694 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4695         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4696         // to_remote output is encumbered by a P2WPKH
4697
4698         let chanmon_cfgs = create_chanmon_cfgs(2);
4699         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4700         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4701         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4702
4703         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4704         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4705         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4706         assert_eq!(revoked_local_txn[0].input.len(), 1);
4707         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4708
4709         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4710         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4711         check_closed_broadcast!(nodes[1], false);
4712         check_added_monitors!(nodes[1], 1);
4713
4714         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4715         mine_transaction(&nodes[1], &node_txn[0]);
4716         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4717
4718         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4719         assert_eq!(spend_txn.len(), 3);
4720         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4721         check_spends!(spend_txn[1], node_txn[0]);
4722         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4723 }
4724
4725 #[test]
4726 fn test_static_spendable_outputs_preimage_tx() {
4727         let chanmon_cfgs = create_chanmon_cfgs(2);
4728         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4729         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4730         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4731
4732         // Create some initial channels
4733         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4734
4735         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4736
4737         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4738         assert_eq!(commitment_tx[0].input.len(), 1);
4739         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4740
4741         // Settle A's commitment tx on B's chain
4742         assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4743         check_added_monitors!(nodes[1], 1);
4744         mine_transaction(&nodes[1], &commitment_tx[0]);
4745         check_added_monitors!(nodes[1], 1);
4746         let events = nodes[1].node.get_and_clear_pending_msg_events();
4747         match events[0] {
4748                 MessageSendEvent::UpdateHTLCs { .. } => {},
4749                 _ => panic!("Unexpected event"),
4750         }
4751         match events[1] {
4752                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4753                 _ => panic!("Unexepected event"),
4754         }
4755
4756         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4757         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4758         assert_eq!(node_txn.len(), 3);
4759         check_spends!(node_txn[0], commitment_tx[0]);
4760         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4761         check_spends!(node_txn[1], chan_1.3);
4762         check_spends!(node_txn[2], node_txn[1]);
4763
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(), 1);
4769         check_spends!(spend_txn[0], node_txn[0]);
4770 }
4771
4772 #[test]
4773 fn test_static_spendable_outputs_timeout_tx() {
4774         let chanmon_cfgs = create_chanmon_cfgs(2);
4775         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4776         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4777         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4778
4779         // Create some initial channels
4780         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4781
4782         // Rebalance the network a bit by relaying one payment through all the channels ...
4783         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4784
4785         let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4786
4787         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4788         assert_eq!(commitment_tx[0].input.len(), 1);
4789         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4790
4791         // Settle A's commitment tx on B' chain
4792         mine_transaction(&nodes[1], &commitment_tx[0]);
4793         check_added_monitors!(nodes[1], 1);
4794         let events = nodes[1].node.get_and_clear_pending_msg_events();
4795         match events[0] {
4796                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4797                 _ => panic!("Unexpected event"),
4798         }
4799
4800         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4801         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4802         assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4803         check_spends!(node_txn[0],  commitment_tx[0].clone());
4804         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4805         check_spends!(node_txn[1], chan_1.3.clone());
4806         check_spends!(node_txn[2], node_txn[1]);
4807
4808         mine_transaction(&nodes[1], &node_txn[0]);
4809         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4810         expect_payment_failed!(nodes[1], our_payment_hash, true);
4811
4812         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4813         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4814         check_spends!(spend_txn[0], commitment_tx[0]);
4815         check_spends!(spend_txn[1], node_txn[0]);
4816         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4817 }
4818
4819 #[test]
4820 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4821         let chanmon_cfgs = create_chanmon_cfgs(2);
4822         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4823         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4824         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4825
4826         // Create some initial channels
4827         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4828
4829         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4830         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4831         assert_eq!(revoked_local_txn[0].input.len(), 1);
4832         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4833
4834         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4835
4836         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4837         check_closed_broadcast!(nodes[1], false);
4838         check_added_monitors!(nodes[1], 1);
4839
4840         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4841         assert_eq!(node_txn.len(), 2);
4842         assert_eq!(node_txn[0].input.len(), 2);
4843         check_spends!(node_txn[0], revoked_local_txn[0]);
4844
4845         mine_transaction(&nodes[1], &node_txn[0]);
4846         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4847
4848         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4849         assert_eq!(spend_txn.len(), 1);
4850         check_spends!(spend_txn[0], node_txn[0]);
4851 }
4852
4853 #[test]
4854 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4855         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4856         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4857         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4858         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4859         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4860
4861         // Create some initial channels
4862         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4863
4864         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4865         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4866         assert_eq!(revoked_local_txn[0].input.len(), 1);
4867         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4868
4869         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4870
4871         // A will generate HTLC-Timeout from revoked commitment tx
4872         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4873         check_closed_broadcast!(nodes[0], false);
4874         check_added_monitors!(nodes[0], 1);
4875
4876         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4877         assert_eq!(revoked_htlc_txn.len(), 2);
4878         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4879         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4880         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4881         check_spends!(revoked_htlc_txn[1], chan_1.3);
4882
4883         // B will generate justice tx from A's revoked commitment/HTLC tx
4884         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4885         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4886         check_closed_broadcast!(nodes[1], false);
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(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4891         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4892         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4893         // transactions next...
4894         assert_eq!(node_txn[0].input.len(), 3);
4895         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4896
4897         assert_eq!(node_txn[1].input.len(), 2);
4898         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4899         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4900                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4901         } else {
4902                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4903                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4904         }
4905
4906         assert_eq!(node_txn[2].input.len(), 1);
4907         check_spends!(node_txn[2], chan_1.3);
4908
4909         mine_transaction(&nodes[1], &node_txn[1]);
4910         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4911
4912         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4913         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4914         assert_eq!(spend_txn.len(), 1);
4915         assert_eq!(spend_txn[0].input.len(), 1);
4916         check_spends!(spend_txn[0], node_txn[1]);
4917 }
4918
4919 #[test]
4920 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4921         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4922         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4923         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4924         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4925         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4926
4927         // Create some initial channels
4928         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4929
4930         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4931         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4932         assert_eq!(revoked_local_txn[0].input.len(), 1);
4933         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4934
4935         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4936         assert_eq!(revoked_local_txn[0].output.len(), 2);
4937
4938         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4939
4940         // B will generate HTLC-Success from revoked commitment tx
4941         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4942         check_closed_broadcast!(nodes[1], false);
4943         check_added_monitors!(nodes[1], 1);
4944         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4945
4946         assert_eq!(revoked_htlc_txn.len(), 2);
4947         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4948         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4949         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4950
4951         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4952         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4953         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4954
4955         // A will generate justice tx from B's revoked commitment/HTLC tx
4956         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4957         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4958         check_closed_broadcast!(nodes[0], false);
4959         check_added_monitors!(nodes[0], 1);
4960
4961         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4962         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4963
4964         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4965         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4966         // transactions next...
4967         assert_eq!(node_txn[0].input.len(), 2);
4968         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4969         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4970                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4971         } else {
4972                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4973                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4974         }
4975
4976         assert_eq!(node_txn[1].input.len(), 1);
4977         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4978
4979         check_spends!(node_txn[2], chan_1.3);
4980
4981         mine_transaction(&nodes[0], &node_txn[1]);
4982         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4983
4984         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4985         // didn't try to generate any new transactions.
4986
4987         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4988         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
4989         assert_eq!(spend_txn.len(), 3);
4990         assert_eq!(spend_txn[0].input.len(), 1);
4991         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4992         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4993         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4994         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4995 }
4996
4997 #[test]
4998 fn test_onchain_to_onchain_claim() {
4999         // Test that in case of channel closure, we detect the state of output and claim HTLC
5000         // on downstream peer's remote commitment tx.
5001         // First, have C claim an HTLC against its own latest commitment transaction.
5002         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5003         // channel.
5004         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5005         // gets broadcast.
5006
5007         let chanmon_cfgs = create_chanmon_cfgs(3);
5008         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5009         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5010         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5011
5012         // Create some initial channels
5013         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5014         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5015
5016         // Rebalance the network a bit by relaying one payment through all the channels ...
5017         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5018         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5019
5020         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5021         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5022         check_spends!(commitment_tx[0], chan_2.3);
5023         nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5024         check_added_monitors!(nodes[2], 1);
5025         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5026         assert!(updates.update_add_htlcs.is_empty());
5027         assert!(updates.update_fail_htlcs.is_empty());
5028         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5029         assert!(updates.update_fail_malformed_htlcs.is_empty());
5030
5031         mine_transaction(&nodes[2], &commitment_tx[0]);
5032         check_closed_broadcast!(nodes[2], false);
5033         check_added_monitors!(nodes[2], 1);
5034
5035         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5036         assert_eq!(c_txn.len(), 3);
5037         assert_eq!(c_txn[0], c_txn[2]);
5038         assert_eq!(commitment_tx[0], c_txn[1]);
5039         check_spends!(c_txn[1], chan_2.3);
5040         check_spends!(c_txn[2], c_txn[1]);
5041         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5042         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5043         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5044         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5045
5046         // 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
5047         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5048         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5049         {
5050                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5051                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5052                 assert_eq!(b_txn.len(), 3);
5053                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5054                 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5055                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5056                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5057                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5058                 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5059                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5060                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5061                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5062                 b_txn.clear();
5063         }
5064         check_added_monitors!(nodes[1], 1);
5065         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5066         check_added_monitors!(nodes[1], 1);
5067         match msg_events[0] {
5068                 MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
5069                 _ => panic!("Unexpected event"),
5070         }
5071         match msg_events[1] {
5072                 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, .. } } => {
5073                         assert!(update_add_htlcs.is_empty());
5074                         assert!(update_fail_htlcs.is_empty());
5075                         assert_eq!(update_fulfill_htlcs.len(), 1);
5076                         assert!(update_fail_malformed_htlcs.is_empty());
5077                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5078                 },
5079                 _ => panic!("Unexpected event"),
5080         };
5081         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5082         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5083         mine_transaction(&nodes[1], &commitment_tx[0]);
5084         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5085         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5086         assert_eq!(b_txn.len(), 3);
5087         check_spends!(b_txn[1], chan_1.3);
5088         check_spends!(b_txn[2], b_txn[1]);
5089         check_spends!(b_txn[0], commitment_tx[0]);
5090         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5091         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5092         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5093
5094         check_closed_broadcast!(nodes[1], false);
5095         check_added_monitors!(nodes[1], 1);
5096 }
5097
5098 #[test]
5099 fn test_duplicate_payment_hash_one_failure_one_success() {
5100         // Topology : A --> B --> C
5101         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5102         let chanmon_cfgs = create_chanmon_cfgs(3);
5103         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5104         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5105         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5106
5107         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5108         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5109
5110         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5111         *nodes[0].network_payment_count.borrow_mut() -= 1;
5112         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5113
5114         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5115         assert_eq!(commitment_txn[0].input.len(), 1);
5116         check_spends!(commitment_txn[0], chan_2.3);
5117
5118         mine_transaction(&nodes[1], &commitment_txn[0]);
5119         check_closed_broadcast!(nodes[1], false);
5120         check_added_monitors!(nodes[1], 1);
5121
5122         let htlc_timeout_tx;
5123         { // Extract one of the two HTLC-Timeout transaction
5124                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5125                 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5126                 assert_eq!(node_txn.len(), 5);
5127                 check_spends!(node_txn[0], commitment_txn[0]);
5128                 assert_eq!(node_txn[0].input.len(), 1);
5129                 check_spends!(node_txn[1], commitment_txn[0]);
5130                 assert_eq!(node_txn[1].input.len(), 1);
5131                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5132                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5133                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5134                 check_spends!(node_txn[2], chan_2.3);
5135                 check_spends!(node_txn[3], node_txn[2]);
5136                 check_spends!(node_txn[4], node_txn[2]);
5137                 htlc_timeout_tx = node_txn[1].clone();
5138         }
5139
5140         nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5141         mine_transaction(&nodes[2], &commitment_txn[0]);
5142         check_added_monitors!(nodes[2], 3);
5143         let events = nodes[2].node.get_and_clear_pending_msg_events();
5144         match events[0] {
5145                 MessageSendEvent::UpdateHTLCs { .. } => {},
5146                 _ => panic!("Unexpected event"),
5147         }
5148         match events[1] {
5149                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5150                 _ => panic!("Unexepected event"),
5151         }
5152         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5153         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)
5154         check_spends!(htlc_success_txn[2], chan_2.3);
5155         check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5156         check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5157         assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5158         assert_eq!(htlc_success_txn[0].input.len(), 1);
5159         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5160         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5161         assert_eq!(htlc_success_txn[1].input.len(), 1);
5162         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5163         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5164         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5165         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5166
5167         mine_transaction(&nodes[1], &htlc_timeout_tx);
5168         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5169         expect_pending_htlcs_forwardable!(nodes[1]);
5170         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5171         assert!(htlc_updates.update_add_htlcs.is_empty());
5172         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5173         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5174         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5175         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5176         check_added_monitors!(nodes[1], 1);
5177
5178         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5179         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5180         {
5181                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5182                 let events = nodes[0].node.get_and_clear_pending_msg_events();
5183                 assert_eq!(events.len(), 1);
5184                 match events[0] {
5185                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
5186                         },
5187                         _ => { panic!("Unexpected event"); }
5188                 }
5189         }
5190         expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5191
5192         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5193         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5194         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5195         assert!(updates.update_add_htlcs.is_empty());
5196         assert!(updates.update_fail_htlcs.is_empty());
5197         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5198         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5199         assert!(updates.update_fail_malformed_htlcs.is_empty());
5200         check_added_monitors!(nodes[1], 1);
5201
5202         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5203         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5204
5205         let events = nodes[0].node.get_and_clear_pending_events();
5206         match events[0] {
5207                 Event::PaymentSent { ref payment_preimage } => {
5208                         assert_eq!(*payment_preimage, our_payment_preimage);
5209                 }
5210                 _ => panic!("Unexpected event"),
5211         }
5212 }
5213
5214 #[test]
5215 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5216         let chanmon_cfgs = create_chanmon_cfgs(2);
5217         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5218         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5219         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5220
5221         // Create some initial channels
5222         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5223
5224         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5225         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5226         assert_eq!(local_txn.len(), 1);
5227         assert_eq!(local_txn[0].input.len(), 1);
5228         check_spends!(local_txn[0], chan_1.3);
5229
5230         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5231         nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5232         check_added_monitors!(nodes[1], 1);
5233         mine_transaction(&nodes[1], &local_txn[0]);
5234         check_added_monitors!(nodes[1], 1);
5235         let events = nodes[1].node.get_and_clear_pending_msg_events();
5236         match events[0] {
5237                 MessageSendEvent::UpdateHTLCs { .. } => {},
5238                 _ => panic!("Unexpected event"),
5239         }
5240         match events[1] {
5241                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5242                 _ => panic!("Unexepected event"),
5243         }
5244         let node_tx = {
5245                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5246                 assert_eq!(node_txn.len(), 3);
5247                 assert_eq!(node_txn[0], node_txn[2]);
5248                 assert_eq!(node_txn[1], local_txn[0]);
5249                 assert_eq!(node_txn[0].input.len(), 1);
5250                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5251                 check_spends!(node_txn[0], local_txn[0]);
5252                 node_txn[0].clone()
5253         };
5254
5255         mine_transaction(&nodes[1], &node_tx);
5256         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5257
5258         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5259         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5260         assert_eq!(spend_txn.len(), 1);
5261         check_spends!(spend_txn[0], node_tx);
5262 }
5263
5264 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5265         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5266         // unrevoked commitment transaction.
5267         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5268         // a remote RAA before they could be failed backwards (and combinations thereof).
5269         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5270         // use the same payment hashes.
5271         // Thus, we use a six-node network:
5272         //
5273         // A \         / E
5274         //    - C - D -
5275         // B /         \ F
5276         // And test where C fails back to A/B when D announces its latest commitment transaction
5277         let chanmon_cfgs = create_chanmon_cfgs(6);
5278         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5279         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5280         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5281         let logger = test_utils::TestLogger::new();
5282
5283         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5284         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5285         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5286         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5287         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5288
5289         // Rebalance and check output sanity...
5290         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5291         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5292         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5293
5294         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5295         // 0th HTLC:
5296         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
5297         // 1st HTLC:
5298         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
5299         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5300         let our_node_id = &nodes[1].node.get_our_node_id();
5301         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();
5302         // 2nd HTLC:
5303         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
5304         // 3rd HTLC:
5305         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
5306         // 4th HTLC:
5307         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5308         // 5th HTLC:
5309         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5310         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();
5311         // 6th HTLC:
5312         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5313         // 7th HTLC:
5314         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5315
5316         // 8th HTLC:
5317         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5318         // 9th HTLC:
5319         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();
5320         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
5321
5322         // 10th HTLC:
5323         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
5324         // 11th HTLC:
5325         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();
5326         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5327
5328         // Double-check that six of the new HTLC were added
5329         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5330         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5331         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5332         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5333
5334         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5335         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5336         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5337         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5338         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5339         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5340         check_added_monitors!(nodes[4], 0);
5341         expect_pending_htlcs_forwardable!(nodes[4]);
5342         check_added_monitors!(nodes[4], 1);
5343
5344         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5345         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5346         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5347         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5348         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5349         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5350
5351         // Fail 3rd below-dust and 7th above-dust HTLCs
5352         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5353         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5354         check_added_monitors!(nodes[5], 0);
5355         expect_pending_htlcs_forwardable!(nodes[5]);
5356         check_added_monitors!(nodes[5], 1);
5357
5358         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5359         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5360         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5361         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5362
5363         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5364
5365         expect_pending_htlcs_forwardable!(nodes[3]);
5366         check_added_monitors!(nodes[3], 1);
5367         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5368         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5369         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5370         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5371         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5372         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5373         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5374         if deliver_last_raa {
5375                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5376         } else {
5377                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5378         }
5379
5380         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5381         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5382         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5383         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5384         //
5385         // We now broadcast the latest commitment transaction, which *should* result in failures for
5386         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5387         // the non-broadcast above-dust HTLCs.
5388         //
5389         // Alternatively, we may broadcast the previous commitment transaction, which should only
5390         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5391         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5392
5393         if announce_latest {
5394                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5395         } else {
5396                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5397         }
5398         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5399         check_closed_broadcast!(nodes[2], false);
5400         expect_pending_htlcs_forwardable!(nodes[2]);
5401         check_added_monitors!(nodes[2], 3);
5402
5403         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5404         assert_eq!(cs_msgs.len(), 2);
5405         let mut a_done = false;
5406         for msg in cs_msgs {
5407                 match msg {
5408                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5409                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5410                                 // should be failed-backwards here.
5411                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5412                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5413                                         for htlc in &updates.update_fail_htlcs {
5414                                                 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 });
5415                                         }
5416                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5417                                         assert!(!a_done);
5418                                         a_done = true;
5419                                         &nodes[0]
5420                                 } else {
5421                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5422                                         for htlc in &updates.update_fail_htlcs {
5423                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5424                                         }
5425                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5426                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5427                                         &nodes[1]
5428                                 };
5429                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5430                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5431                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5432                                 if announce_latest {
5433                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5434                                         if *node_id == nodes[0].node.get_our_node_id() {
5435                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5436                                         }
5437                                 }
5438                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5439                         },
5440                         _ => panic!("Unexpected event"),
5441                 }
5442         }
5443
5444         let as_events = nodes[0].node.get_and_clear_pending_events();
5445         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5446         let mut as_failds = HashSet::new();
5447         for event in as_events.iter() {
5448                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5449                         assert!(as_failds.insert(*payment_hash));
5450                         if *payment_hash != payment_hash_2 {
5451                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5452                         } else {
5453                                 assert!(!rejected_by_dest);
5454                         }
5455                 } else { panic!("Unexpected event"); }
5456         }
5457         assert!(as_failds.contains(&payment_hash_1));
5458         assert!(as_failds.contains(&payment_hash_2));
5459         if announce_latest {
5460                 assert!(as_failds.contains(&payment_hash_3));
5461                 assert!(as_failds.contains(&payment_hash_5));
5462         }
5463         assert!(as_failds.contains(&payment_hash_6));
5464
5465         let bs_events = nodes[1].node.get_and_clear_pending_events();
5466         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5467         let mut bs_failds = HashSet::new();
5468         for event in bs_events.iter() {
5469                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5470                         assert!(bs_failds.insert(*payment_hash));
5471                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5472                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5473                         } else {
5474                                 assert!(!rejected_by_dest);
5475                         }
5476                 } else { panic!("Unexpected event"); }
5477         }
5478         assert!(bs_failds.contains(&payment_hash_1));
5479         assert!(bs_failds.contains(&payment_hash_2));
5480         if announce_latest {
5481                 assert!(bs_failds.contains(&payment_hash_4));
5482         }
5483         assert!(bs_failds.contains(&payment_hash_5));
5484
5485         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5486         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5487         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5488         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5489         // PaymentFailureNetworkUpdates.
5490         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5491         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5492         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5493         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5494         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5495                 match event {
5496                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5497                         _ => panic!("Unexpected event"),
5498                 }
5499         }
5500 }
5501
5502 #[test]
5503 fn test_fail_backwards_latest_remote_announce_a() {
5504         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5505 }
5506
5507 #[test]
5508 fn test_fail_backwards_latest_remote_announce_b() {
5509         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5510 }
5511
5512 #[test]
5513 fn test_fail_backwards_previous_remote_announce() {
5514         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5515         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5516         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5517 }
5518
5519 #[test]
5520 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5521         let chanmon_cfgs = create_chanmon_cfgs(2);
5522         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5523         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5524         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5525
5526         // Create some initial channels
5527         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5528
5529         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5530         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5531         assert_eq!(local_txn[0].input.len(), 1);
5532         check_spends!(local_txn[0], chan_1.3);
5533
5534         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5535         mine_transaction(&nodes[0], &local_txn[0]);
5536         check_closed_broadcast!(nodes[0], false);
5537         check_added_monitors!(nodes[0], 1);
5538
5539         let htlc_timeout = {
5540                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5541                 assert_eq!(node_txn[0].input.len(), 1);
5542                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5543                 check_spends!(node_txn[0], local_txn[0]);
5544                 node_txn[0].clone()
5545         };
5546
5547         mine_transaction(&nodes[0], &htlc_timeout);
5548         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5549         expect_payment_failed!(nodes[0], our_payment_hash, true);
5550
5551         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5552         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5553         assert_eq!(spend_txn.len(), 3);
5554         check_spends!(spend_txn[0], local_txn[0]);
5555         check_spends!(spend_txn[1], htlc_timeout);
5556         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5557 }
5558
5559 #[test]
5560 fn test_key_derivation_params() {
5561         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5562         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5563         // let us re-derive the channel key set to then derive a delayed_payment_key.
5564
5565         let chanmon_cfgs = create_chanmon_cfgs(3);
5566
5567         // We manually create the node configuration to backup the seed.
5568         let seed = [42; 32];
5569         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5570         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);
5571         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 };
5572         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5573         node_cfgs.remove(0);
5574         node_cfgs.insert(0, node);
5575
5576         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5577         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5578
5579         // Create some initial channels
5580         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5581         // for node 0
5582         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5583         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5584         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5585
5586         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5587         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5588         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5589         assert_eq!(local_txn_1[0].input.len(), 1);
5590         check_spends!(local_txn_1[0], chan_1.3);
5591
5592         // We check funding pubkey are unique
5593         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]));
5594         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]));
5595         if from_0_funding_key_0 == from_1_funding_key_0
5596             || from_0_funding_key_0 == from_1_funding_key_1
5597             || from_0_funding_key_1 == from_1_funding_key_0
5598             || from_0_funding_key_1 == from_1_funding_key_1 {
5599                 panic!("Funding pubkeys aren't unique");
5600         }
5601
5602         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5603         mine_transaction(&nodes[0], &local_txn_1[0]);
5604         check_closed_broadcast!(nodes[0], false);
5605         check_added_monitors!(nodes[0], 1);
5606
5607         let htlc_timeout = {
5608                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5609                 assert_eq!(node_txn[0].input.len(), 1);
5610                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5611                 check_spends!(node_txn[0], local_txn_1[0]);
5612                 node_txn[0].clone()
5613         };
5614
5615         mine_transaction(&nodes[0], &htlc_timeout);
5616         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5617         expect_payment_failed!(nodes[0], our_payment_hash, true);
5618
5619         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5620         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5621         let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5622         assert_eq!(spend_txn.len(), 3);
5623         check_spends!(spend_txn[0], local_txn_1[0]);
5624         check_spends!(spend_txn[1], htlc_timeout);
5625         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5626 }
5627
5628 #[test]
5629 fn test_static_output_closing_tx() {
5630         let chanmon_cfgs = create_chanmon_cfgs(2);
5631         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5632         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5633         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5634
5635         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5636
5637         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5638         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5639
5640         mine_transaction(&nodes[0], &closing_tx);
5641         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5642
5643         let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5644         assert_eq!(spend_txn.len(), 1);
5645         check_spends!(spend_txn[0], closing_tx);
5646
5647         mine_transaction(&nodes[1], &closing_tx);
5648         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5649
5650         let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5651         assert_eq!(spend_txn.len(), 1);
5652         check_spends!(spend_txn[0], closing_tx);
5653 }
5654
5655 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5656         let chanmon_cfgs = create_chanmon_cfgs(2);
5657         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5658         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5659         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5660         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5661
5662         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5663
5664         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5665         // present in B's local commitment transaction, but none of A's commitment transactions.
5666         assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5667         check_added_monitors!(nodes[1], 1);
5668
5669         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5670         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5671         let events = nodes[0].node.get_and_clear_pending_events();
5672         assert_eq!(events.len(), 1);
5673         match events[0] {
5674                 Event::PaymentSent { payment_preimage } => {
5675                         assert_eq!(payment_preimage, our_payment_preimage);
5676                 },
5677                 _ => panic!("Unexpected event"),
5678         }
5679
5680         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5681         check_added_monitors!(nodes[0], 1);
5682         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5683         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5684         check_added_monitors!(nodes[1], 1);
5685
5686         let starting_block = nodes[1].best_block_info();
5687         let mut block = Block {
5688                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5689                 txdata: vec![],
5690         };
5691         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5692                 connect_block(&nodes[1], &block);
5693                 block.header.prev_blockhash = block.block_hash();
5694         }
5695         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5696         check_closed_broadcast!(nodes[1], false);
5697         check_added_monitors!(nodes[1], 1);
5698 }
5699
5700 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5701         let chanmon_cfgs = create_chanmon_cfgs(2);
5702         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5703         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5704         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5705         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5706         let logger = test_utils::TestLogger::new();
5707
5708         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5709         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5710         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();
5711         nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5712         check_added_monitors!(nodes[0], 1);
5713
5714         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5715
5716         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5717         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5718         // to "time out" the HTLC.
5719
5720         let starting_block = nodes[1].best_block_info();
5721         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5722
5723         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5724                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5725                 header.prev_blockhash = header.block_hash();
5726         }
5727         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5728         check_closed_broadcast!(nodes[0], false);
5729         check_added_monitors!(nodes[0], 1);
5730 }
5731
5732 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5733         let chanmon_cfgs = create_chanmon_cfgs(3);
5734         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5735         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5736         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5737         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5738
5739         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5740         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5741         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5742         // actually revoked.
5743         let htlc_value = if use_dust { 50000 } else { 3000000 };
5744         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5745         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5746         expect_pending_htlcs_forwardable!(nodes[1]);
5747         check_added_monitors!(nodes[1], 1);
5748
5749         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5750         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5751         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5752         check_added_monitors!(nodes[0], 1);
5753         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5754         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5755         check_added_monitors!(nodes[1], 1);
5756         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5757         check_added_monitors!(nodes[1], 1);
5758         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5759
5760         if check_revoke_no_close {
5761                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5762                 check_added_monitors!(nodes[0], 1);
5763         }
5764
5765         let starting_block = nodes[1].best_block_info();
5766         let mut block = Block {
5767                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5768                 txdata: vec![],
5769         };
5770         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5771                 connect_block(&nodes[0], &block);
5772                 block.header.prev_blockhash = block.block_hash();
5773         }
5774         if !check_revoke_no_close {
5775                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5776                 check_closed_broadcast!(nodes[0], false);
5777                 check_added_monitors!(nodes[0], 1);
5778         } else {
5779                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5780         }
5781 }
5782
5783 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5784 // There are only a few cases to test here:
5785 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5786 //    broadcastable commitment transactions result in channel closure,
5787 //  * its included in an unrevoked-but-previous remote commitment transaction,
5788 //  * its included in the latest remote or local commitment transactions.
5789 // We test each of the three possible commitment transactions individually and use both dust and
5790 // non-dust HTLCs.
5791 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5792 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5793 // tested for at least one of the cases in other tests.
5794 #[test]
5795 fn htlc_claim_single_commitment_only_a() {
5796         do_htlc_claim_local_commitment_only(true);
5797         do_htlc_claim_local_commitment_only(false);
5798
5799         do_htlc_claim_current_remote_commitment_only(true);
5800         do_htlc_claim_current_remote_commitment_only(false);
5801 }
5802
5803 #[test]
5804 fn htlc_claim_single_commitment_only_b() {
5805         do_htlc_claim_previous_remote_commitment_only(true, false);
5806         do_htlc_claim_previous_remote_commitment_only(false, false);
5807         do_htlc_claim_previous_remote_commitment_only(true, true);
5808         do_htlc_claim_previous_remote_commitment_only(false, true);
5809 }
5810
5811 #[test]
5812 #[should_panic]
5813 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5814         let chanmon_cfgs = create_chanmon_cfgs(2);
5815         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5816         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5817         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5818         //Force duplicate channel ids
5819         for node in nodes.iter() {
5820                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5821         }
5822
5823         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5824         let channel_value_satoshis=10000;
5825         let push_msat=10001;
5826         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5827         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5828         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5829
5830         //Create a second channel with a channel_id collision
5831         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5832 }
5833
5834 #[test]
5835 fn bolt2_open_channel_sending_node_checks_part2() {
5836         let chanmon_cfgs = create_chanmon_cfgs(2);
5837         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5838         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5839         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5840
5841         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5842         let channel_value_satoshis=2^24;
5843         let push_msat=10001;
5844         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5845
5846         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5847         let channel_value_satoshis=10000;
5848         // Test when push_msat is equal to 1000 * funding_satoshis.
5849         let push_msat=1000*channel_value_satoshis+1;
5850         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5851
5852         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5853         let channel_value_satoshis=10000;
5854         let push_msat=10001;
5855         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
5856         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5857         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5858
5859         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5860         // 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
5861         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5862
5863         // 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.
5864         assert!(BREAKDOWN_TIMEOUT>0);
5865         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5866
5867         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5868         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5869         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5870
5871         // 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.
5872         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5873         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5874         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5875         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5876         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5877 }
5878
5879 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5880 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5881 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5882 // is no longer affordable once it's freed.
5883 #[test]
5884 fn test_fail_holding_cell_htlc_upon_free() {
5885         let chanmon_cfgs = create_chanmon_cfgs(2);
5886         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5887         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5888         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5889         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5890         let logger = test_utils::TestLogger::new();
5891
5892         // First nodes[0] generates an update_fee, setting the channel's
5893         // pending_update_fee.
5894         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
5895         check_added_monitors!(nodes[0], 1);
5896
5897         let events = nodes[0].node.get_and_clear_pending_msg_events();
5898         assert_eq!(events.len(), 1);
5899         let (update_msg, commitment_signed) = match events[0] {
5900                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5901                         (update_fee.as_ref(), commitment_signed)
5902                 },
5903                 _ => panic!("Unexpected event"),
5904         };
5905
5906         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5907
5908         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5909         let channel_reserve = chan_stat.channel_reserve_msat;
5910         let feerate = get_feerate!(nodes[0], chan.2);
5911
5912         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5913         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5914         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5915         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5916         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();
5917
5918         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5919         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5920         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5921         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5922
5923         // Flush the pending fee update.
5924         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5925         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5926         check_added_monitors!(nodes[1], 1);
5927         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5928         check_added_monitors!(nodes[0], 1);
5929
5930         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5931         // HTLC, but now that the fee has been raised the payment will now fail, causing
5932         // us to surface its failure to the user.
5933         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5934         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5935         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
5936         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);
5937         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5938
5939         // Check that the payment failed to be sent out.
5940         let events = nodes[0].node.get_and_clear_pending_events();
5941         assert_eq!(events.len(), 1);
5942         match &events[0] {
5943                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
5944                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5945                         assert_eq!(*rejected_by_dest, false);
5946                         assert_eq!(*error_code, None);
5947                         assert_eq!(*error_data, None);
5948                 },
5949                 _ => panic!("Unexpected event"),
5950         }
5951 }
5952
5953 // Test that if multiple HTLCs are released from the holding cell and one is
5954 // valid but the other is no longer valid upon release, the valid HTLC can be
5955 // successfully completed while the other one fails as expected.
5956 #[test]
5957 fn test_free_and_fail_holding_cell_htlcs() {
5958         let chanmon_cfgs = create_chanmon_cfgs(2);
5959         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5960         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5961         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5962         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5963         let logger = test_utils::TestLogger::new();
5964
5965         // First nodes[0] generates an update_fee, setting the channel's
5966         // pending_update_fee.
5967         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
5968         check_added_monitors!(nodes[0], 1);
5969
5970         let events = nodes[0].node.get_and_clear_pending_msg_events();
5971         assert_eq!(events.len(), 1);
5972         let (update_msg, commitment_signed) = match events[0] {
5973                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5974                         (update_fee.as_ref(), commitment_signed)
5975                 },
5976                 _ => panic!("Unexpected event"),
5977         };
5978
5979         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5980
5981         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5982         let channel_reserve = chan_stat.channel_reserve_msat;
5983         let feerate = get_feerate!(nodes[0], chan.2);
5984
5985         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5986         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
5987         let amt_1 = 20000;
5988         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
5989         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
5990         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5991         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();
5992         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();
5993
5994         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5995         nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
5996         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5997         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5998         nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
5999         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6000         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6001
6002         // Flush the pending fee update.
6003         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6004         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6005         check_added_monitors!(nodes[1], 1);
6006         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6007         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6008         check_added_monitors!(nodes[0], 2);
6009
6010         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6011         // but now that the fee has been raised the second payment will now fail, causing us
6012         // to surface its failure to the user. The first payment should succeed.
6013         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6014         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6015         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6016         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);
6017         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6018
6019         // Check that the second payment failed to be sent out.
6020         let events = nodes[0].node.get_and_clear_pending_events();
6021         assert_eq!(events.len(), 1);
6022         match &events[0] {
6023                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6024                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6025                         assert_eq!(*rejected_by_dest, false);
6026                         assert_eq!(*error_code, None);
6027                         assert_eq!(*error_data, None);
6028                 },
6029                 _ => panic!("Unexpected event"),
6030         }
6031
6032         // Complete the first payment and the RAA from the fee update.
6033         let (payment_event, send_raa_event) = {
6034                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6035                 assert_eq!(msgs.len(), 2);
6036                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6037         };
6038         let raa = match send_raa_event {
6039                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6040                 _ => panic!("Unexpected event"),
6041         };
6042         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6043         check_added_monitors!(nodes[1], 1);
6044         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6045         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6046         let events = nodes[1].node.get_and_clear_pending_events();
6047         assert_eq!(events.len(), 1);
6048         match events[0] {
6049                 Event::PendingHTLCsForwardable { .. } => {},
6050                 _ => panic!("Unexpected event"),
6051         }
6052         nodes[1].node.process_pending_htlc_forwards();
6053         let events = nodes[1].node.get_and_clear_pending_events();
6054         assert_eq!(events.len(), 1);
6055         match events[0] {
6056                 Event::PaymentReceived { .. } => {},
6057                 _ => panic!("Unexpected event"),
6058         }
6059         nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6060         check_added_monitors!(nodes[1], 1);
6061         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6062         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6063         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6064         let events = nodes[0].node.get_and_clear_pending_events();
6065         assert_eq!(events.len(), 1);
6066         match events[0] {
6067                 Event::PaymentSent { ref payment_preimage } => {
6068                         assert_eq!(*payment_preimage, payment_preimage_1);
6069                 }
6070                 _ => panic!("Unexpected event"),
6071         }
6072 }
6073
6074 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6075 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6076 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6077 // once it's freed.
6078 #[test]
6079 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6080         let chanmon_cfgs = create_chanmon_cfgs(3);
6081         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6082         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6083         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6084         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6085         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6086         let logger = test_utils::TestLogger::new();
6087
6088         // First nodes[1] generates an update_fee, setting the channel's
6089         // pending_update_fee.
6090         nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6091         check_added_monitors!(nodes[1], 1);
6092
6093         let events = nodes[1].node.get_and_clear_pending_msg_events();
6094         assert_eq!(events.len(), 1);
6095         let (update_msg, commitment_signed) = match events[0] {
6096                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6097                         (update_fee.as_ref(), commitment_signed)
6098                 },
6099                 _ => panic!("Unexpected event"),
6100         };
6101
6102         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6103
6104         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6105         let channel_reserve = chan_stat.channel_reserve_msat;
6106         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6107
6108         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6109         let feemsat = 239;
6110         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6111         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6112         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6113         let payment_event = {
6114                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6115                 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();
6116                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6117                 check_added_monitors!(nodes[0], 1);
6118
6119                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6120                 assert_eq!(events.len(), 1);
6121
6122                 SendEvent::from_event(events.remove(0))
6123         };
6124         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6125         check_added_monitors!(nodes[1], 0);
6126         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6127         expect_pending_htlcs_forwardable!(nodes[1]);
6128
6129         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6130         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6131
6132         // Flush the pending fee update.
6133         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6134         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6135         check_added_monitors!(nodes[2], 1);
6136         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6137         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6138         check_added_monitors!(nodes[1], 2);
6139
6140         // A final RAA message is generated to finalize the fee update.
6141         let events = nodes[1].node.get_and_clear_pending_msg_events();
6142         assert_eq!(events.len(), 1);
6143
6144         let raa_msg = match &events[0] {
6145                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6146                         msg.clone()
6147                 },
6148                 _ => panic!("Unexpected event"),
6149         };
6150
6151         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6152         check_added_monitors!(nodes[2], 1);
6153         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6154
6155         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6156         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6157         assert_eq!(process_htlc_forwards_event.len(), 1);
6158         match &process_htlc_forwards_event[0] {
6159                 &Event::PendingHTLCsForwardable { .. } => {},
6160                 _ => panic!("Unexpected event"),
6161         }
6162
6163         // In response, we call ChannelManager's process_pending_htlc_forwards
6164         nodes[1].node.process_pending_htlc_forwards();
6165         check_added_monitors!(nodes[1], 1);
6166
6167         // This causes the HTLC to be failed backwards.
6168         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6169         assert_eq!(fail_event.len(), 1);
6170         let (fail_msg, commitment_signed) = match &fail_event[0] {
6171                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6172                         assert_eq!(updates.update_add_htlcs.len(), 0);
6173                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6174                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6175                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6176                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6177                 },
6178                 _ => panic!("Unexpected event"),
6179         };
6180
6181         // Pass the failure messages back to nodes[0].
6182         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6183         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6184
6185         // Complete the HTLC failure+removal process.
6186         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6187         check_added_monitors!(nodes[0], 1);
6188         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6189         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6190         check_added_monitors!(nodes[1], 2);
6191         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6192         assert_eq!(final_raa_event.len(), 1);
6193         let raa = match &final_raa_event[0] {
6194                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6195                 _ => panic!("Unexpected event"),
6196         };
6197         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6198         let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6199         assert_eq!(fail_msg_event.len(), 1);
6200         match &fail_msg_event[0] {
6201                 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6202                 _ => panic!("Unexpected event"),
6203         }
6204         let failure_event = nodes[0].node.get_and_clear_pending_events();
6205         assert_eq!(failure_event.len(), 1);
6206         match &failure_event[0] {
6207                 &Event::PaymentFailed { rejected_by_dest, .. } => {
6208                         assert!(!rejected_by_dest);
6209                 },
6210                 _ => panic!("Unexpected event"),
6211         }
6212         check_added_monitors!(nodes[0], 1);
6213 }
6214
6215 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6216 // 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.
6217 //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.
6218
6219 #[test]
6220 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6221         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6222         let chanmon_cfgs = create_chanmon_cfgs(2);
6223         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6224         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6225         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6226         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6227
6228         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6229         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6230         let logger = test_utils::TestLogger::new();
6231         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();
6232         route.paths[0][0].fee_msat = 100;
6233
6234         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6235                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6236         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6237         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6238 }
6239
6240 #[test]
6241 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6242         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6243         let chanmon_cfgs = create_chanmon_cfgs(2);
6244         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6245         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6246         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6247         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6248         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6249
6250         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6251         let logger = test_utils::TestLogger::new();
6252         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();
6253         route.paths[0][0].fee_msat = 0;
6254         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6255                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6256
6257         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6258         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6259 }
6260
6261 #[test]
6262 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6263         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6264         let chanmon_cfgs = create_chanmon_cfgs(2);
6265         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6266         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6267         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6268         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6269
6270         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6271         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6272         let logger = test_utils::TestLogger::new();
6273         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();
6274         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6275         check_added_monitors!(nodes[0], 1);
6276         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6277         updates.update_add_htlcs[0].amount_msat = 0;
6278
6279         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6280         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6281         check_closed_broadcast!(nodes[1], true).unwrap();
6282         check_added_monitors!(nodes[1], 1);
6283 }
6284
6285 #[test]
6286 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6287         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6288         //It is enforced when constructing a route.
6289         let chanmon_cfgs = create_chanmon_cfgs(2);
6290         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6291         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6292         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6293         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6294         let logger = test_utils::TestLogger::new();
6295
6296         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6297
6298         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6299         let 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();
6300         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6301                 assert_eq!(err, &"Channel CLTV overflowed?"));
6302 }
6303
6304 #[test]
6305 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6306         //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.
6307         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6308         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6309         let chanmon_cfgs = create_chanmon_cfgs(2);
6310         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6311         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6312         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6313         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6314         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6315
6316         let logger = test_utils::TestLogger::new();
6317         for i in 0..max_accepted_htlcs {
6318                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6319                 let payment_event = {
6320                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6321                         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6322                         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6323                         check_added_monitors!(nodes[0], 1);
6324
6325                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6326                         assert_eq!(events.len(), 1);
6327                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6328                                 assert_eq!(htlcs[0].htlc_id, i);
6329                         } else {
6330                                 assert!(false);
6331                         }
6332                         SendEvent::from_event(events.remove(0))
6333                 };
6334                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6335                 check_added_monitors!(nodes[1], 0);
6336                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6337
6338                 expect_pending_htlcs_forwardable!(nodes[1]);
6339                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6340         }
6341         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6342         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6343         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();
6344         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6345                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6346
6347         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6348         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6349 }
6350
6351 #[test]
6352 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6353         //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.
6354         let chanmon_cfgs = create_chanmon_cfgs(2);
6355         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6356         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6357         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6358         let channel_value = 100000;
6359         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6360         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6361
6362         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6363
6364         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6365         // Manually create a route over our max in flight (which our router normally automatically
6366         // limits us to.
6367         let route = Route { paths: vec![vec![RouteHop {
6368            pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6369            short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6370            fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6371         }]] };
6372         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6373                 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)));
6374
6375         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6376         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);
6377
6378         send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6379 }
6380
6381 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6382 #[test]
6383 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6384         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6385         let chanmon_cfgs = create_chanmon_cfgs(2);
6386         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6387         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6388         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6389         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6390         let htlc_minimum_msat: u64;
6391         {
6392                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6393                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6394                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6395         }
6396
6397         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6398         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6399         let logger = test_utils::TestLogger::new();
6400         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();
6401         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6402         check_added_monitors!(nodes[0], 1);
6403         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6404         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6405         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6406         assert!(nodes[1].node.list_channels().is_empty());
6407         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6408         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()));
6409         check_added_monitors!(nodes[1], 1);
6410 }
6411
6412 #[test]
6413 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6414         //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
6415         let chanmon_cfgs = create_chanmon_cfgs(2);
6416         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6417         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6418         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6419         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6420         let logger = test_utils::TestLogger::new();
6421
6422         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6423         let channel_reserve = chan_stat.channel_reserve_msat;
6424         let feerate = get_feerate!(nodes[0], chan.2);
6425         // The 2* and +1 are for the fee spike reserve.
6426         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6427
6428         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6429         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6430         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6431         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();
6432         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6433         check_added_monitors!(nodes[0], 1);
6434         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6435
6436         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6437         // at this time channel-initiatee receivers are not required to enforce that senders
6438         // respect the fee_spike_reserve.
6439         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6440         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6441
6442         assert!(nodes[1].node.list_channels().is_empty());
6443         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6444         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6445         check_added_monitors!(nodes[1], 1);
6446 }
6447
6448 #[test]
6449 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6450         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6451         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6452         let chanmon_cfgs = create_chanmon_cfgs(2);
6453         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6454         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6455         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6456         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6457         let logger = test_utils::TestLogger::new();
6458
6459         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6460         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6461
6462         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6463         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();
6464
6465         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6466         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6467         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6468         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6469
6470         let mut msg = msgs::UpdateAddHTLC {
6471                 channel_id: chan.2,
6472                 htlc_id: 0,
6473                 amount_msat: 1000,
6474                 payment_hash: our_payment_hash,
6475                 cltv_expiry: htlc_cltv,
6476                 onion_routing_packet: onion_packet.clone(),
6477         };
6478
6479         for i in 0..super::channel::OUR_MAX_HTLCS {
6480                 msg.htlc_id = i as u64;
6481                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6482         }
6483         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6484         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6485
6486         assert!(nodes[1].node.list_channels().is_empty());
6487         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6488         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6489         check_added_monitors!(nodes[1], 1);
6490 }
6491
6492 #[test]
6493 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6494         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6495         let chanmon_cfgs = create_chanmon_cfgs(2);
6496         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6497         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6498         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6499         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6500         let logger = test_utils::TestLogger::new();
6501
6502         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6503         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6504         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();
6505         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6506         check_added_monitors!(nodes[0], 1);
6507         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6508         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6509         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6510
6511         assert!(nodes[1].node.list_channels().is_empty());
6512         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6513         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6514         check_added_monitors!(nodes[1], 1);
6515 }
6516
6517 #[test]
6518 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6519         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6520         let chanmon_cfgs = create_chanmon_cfgs(2);
6521         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6522         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6523         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6524         let logger = test_utils::TestLogger::new();
6525
6526         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6527         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6528         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6529         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();
6530         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6531         check_added_monitors!(nodes[0], 1);
6532         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6533         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6534         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6535
6536         assert!(nodes[1].node.list_channels().is_empty());
6537         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6538         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6539         check_added_monitors!(nodes[1], 1);
6540 }
6541
6542 #[test]
6543 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6544         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6545         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6546         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6547         let chanmon_cfgs = create_chanmon_cfgs(2);
6548         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6549         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6550         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6551         let logger = test_utils::TestLogger::new();
6552
6553         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6554         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6555         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6556         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();
6557         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6558         check_added_monitors!(nodes[0], 1);
6559         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6560         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6561
6562         //Disconnect and Reconnect
6563         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6564         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6565         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6566         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6567         assert_eq!(reestablish_1.len(), 1);
6568         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6569         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6570         assert_eq!(reestablish_2.len(), 1);
6571         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6572         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6573         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6574         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6575
6576         //Resend HTLC
6577         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6578         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6579         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6580         check_added_monitors!(nodes[1], 1);
6581         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6582
6583         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6584
6585         assert!(nodes[1].node.list_channels().is_empty());
6586         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6587         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6588         check_added_monitors!(nodes[1], 1);
6589 }
6590
6591 #[test]
6592 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6593         //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.
6594
6595         let chanmon_cfgs = create_chanmon_cfgs(2);
6596         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6597         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6598         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6599         let logger = test_utils::TestLogger::new();
6600         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6601         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6602         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6603         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();
6604         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6605
6606         check_added_monitors!(nodes[0], 1);
6607         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6608         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6609
6610         let update_msg = msgs::UpdateFulfillHTLC{
6611                 channel_id: chan.2,
6612                 htlc_id: 0,
6613                 payment_preimage: our_payment_preimage,
6614         };
6615
6616         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6617
6618         assert!(nodes[0].node.list_channels().is_empty());
6619         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6620         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()));
6621         check_added_monitors!(nodes[0], 1);
6622 }
6623
6624 #[test]
6625 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6626         //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.
6627
6628         let chanmon_cfgs = create_chanmon_cfgs(2);
6629         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6630         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6631         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6632         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6633         let logger = test_utils::TestLogger::new();
6634
6635         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6636         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6637         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();
6638         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6639         check_added_monitors!(nodes[0], 1);
6640         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6641         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6642
6643         let update_msg = msgs::UpdateFailHTLC{
6644                 channel_id: chan.2,
6645                 htlc_id: 0,
6646                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6647         };
6648
6649         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6650
6651         assert!(nodes[0].node.list_channels().is_empty());
6652         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6653         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()));
6654         check_added_monitors!(nodes[0], 1);
6655 }
6656
6657 #[test]
6658 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6659         //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.
6660
6661         let chanmon_cfgs = create_chanmon_cfgs(2);
6662         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6663         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6664         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6665         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6666         let logger = test_utils::TestLogger::new();
6667
6668         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6669         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6670         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();
6671         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6672         check_added_monitors!(nodes[0], 1);
6673         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6674         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6675         let update_msg = msgs::UpdateFailMalformedHTLC{
6676                 channel_id: chan.2,
6677                 htlc_id: 0,
6678                 sha256_of_onion: [1; 32],
6679                 failure_code: 0x8000,
6680         };
6681
6682         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6683
6684         assert!(nodes[0].node.list_channels().is_empty());
6685         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6686         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()));
6687         check_added_monitors!(nodes[0], 1);
6688 }
6689
6690 #[test]
6691 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6692         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6693
6694         let chanmon_cfgs = create_chanmon_cfgs(2);
6695         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6696         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6697         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6698         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6699
6700         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6701
6702         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6703         check_added_monitors!(nodes[1], 1);
6704
6705         let events = nodes[1].node.get_and_clear_pending_msg_events();
6706         assert_eq!(events.len(), 1);
6707         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6708                 match events[0] {
6709                         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, .. } } => {
6710                                 assert!(update_add_htlcs.is_empty());
6711                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6712                                 assert!(update_fail_htlcs.is_empty());
6713                                 assert!(update_fail_malformed_htlcs.is_empty());
6714                                 assert!(update_fee.is_none());
6715                                 update_fulfill_htlcs[0].clone()
6716                         },
6717                         _ => panic!("Unexpected event"),
6718                 }
6719         };
6720
6721         update_fulfill_msg.htlc_id = 1;
6722
6723         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6724
6725         assert!(nodes[0].node.list_channels().is_empty());
6726         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6727         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6728         check_added_monitors!(nodes[0], 1);
6729 }
6730
6731 #[test]
6732 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6733         //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.
6734
6735         let chanmon_cfgs = create_chanmon_cfgs(2);
6736         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6737         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6738         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6739         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6740
6741         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6742
6743         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6744         check_added_monitors!(nodes[1], 1);
6745
6746         let events = nodes[1].node.get_and_clear_pending_msg_events();
6747         assert_eq!(events.len(), 1);
6748         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6749                 match events[0] {
6750                         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, .. } } => {
6751                                 assert!(update_add_htlcs.is_empty());
6752                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6753                                 assert!(update_fail_htlcs.is_empty());
6754                                 assert!(update_fail_malformed_htlcs.is_empty());
6755                                 assert!(update_fee.is_none());
6756                                 update_fulfill_htlcs[0].clone()
6757                         },
6758                         _ => panic!("Unexpected event"),
6759                 }
6760         };
6761
6762         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6763
6764         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6765
6766         assert!(nodes[0].node.list_channels().is_empty());
6767         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6768         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6769         check_added_monitors!(nodes[0], 1);
6770 }
6771
6772 #[test]
6773 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6774         //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.
6775
6776         let chanmon_cfgs = create_chanmon_cfgs(2);
6777         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6778         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6779         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6780         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6781         let logger = test_utils::TestLogger::new();
6782
6783         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6784         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6785         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();
6786         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6787         check_added_monitors!(nodes[0], 1);
6788
6789         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6790         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6791
6792         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6793         check_added_monitors!(nodes[1], 0);
6794         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6795
6796         let events = nodes[1].node.get_and_clear_pending_msg_events();
6797
6798         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6799                 match events[0] {
6800                         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, .. } } => {
6801                                 assert!(update_add_htlcs.is_empty());
6802                                 assert!(update_fulfill_htlcs.is_empty());
6803                                 assert!(update_fail_htlcs.is_empty());
6804                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6805                                 assert!(update_fee.is_none());
6806                                 update_fail_malformed_htlcs[0].clone()
6807                         },
6808                         _ => panic!("Unexpected event"),
6809                 }
6810         };
6811         update_msg.failure_code &= !0x8000;
6812         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6813
6814         assert!(nodes[0].node.list_channels().is_empty());
6815         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6816         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6817         check_added_monitors!(nodes[0], 1);
6818 }
6819
6820 #[test]
6821 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6822         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6823         //    * 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.
6824
6825         let chanmon_cfgs = create_chanmon_cfgs(3);
6826         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6827         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6828         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6829         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6830         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6831         let logger = test_utils::TestLogger::new();
6832
6833         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6834
6835         //First hop
6836         let mut payment_event = {
6837                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6838                 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();
6839                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6840                 check_added_monitors!(nodes[0], 1);
6841                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6842                 assert_eq!(events.len(), 1);
6843                 SendEvent::from_event(events.remove(0))
6844         };
6845         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6846         check_added_monitors!(nodes[1], 0);
6847         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6848         expect_pending_htlcs_forwardable!(nodes[1]);
6849         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6850         assert_eq!(events_2.len(), 1);
6851         check_added_monitors!(nodes[1], 1);
6852         payment_event = SendEvent::from_event(events_2.remove(0));
6853         assert_eq!(payment_event.msgs.len(), 1);
6854
6855         //Second Hop
6856         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6857         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6858         check_added_monitors!(nodes[2], 0);
6859         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6860
6861         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6862         assert_eq!(events_3.len(), 1);
6863         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6864                 match events_3[0] {
6865                         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 } } => {
6866                                 assert!(update_add_htlcs.is_empty());
6867                                 assert!(update_fulfill_htlcs.is_empty());
6868                                 assert!(update_fail_htlcs.is_empty());
6869                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6870                                 assert!(update_fee.is_none());
6871                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6872                         },
6873                         _ => panic!("Unexpected event"),
6874                 }
6875         };
6876
6877         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6878
6879         check_added_monitors!(nodes[1], 0);
6880         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6881         expect_pending_htlcs_forwardable!(nodes[1]);
6882         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6883         assert_eq!(events_4.len(), 1);
6884
6885         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6886         match events_4[0] {
6887                 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, .. } } => {
6888                         assert!(update_add_htlcs.is_empty());
6889                         assert!(update_fulfill_htlcs.is_empty());
6890                         assert_eq!(update_fail_htlcs.len(), 1);
6891                         assert!(update_fail_malformed_htlcs.is_empty());
6892                         assert!(update_fee.is_none());
6893                 },
6894                 _ => panic!("Unexpected event"),
6895         };
6896
6897         check_added_monitors!(nodes[1], 1);
6898 }
6899
6900 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6901         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6902         // 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
6903         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6904
6905         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6906         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6907         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6908         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6909         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6910         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6911
6912         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6913
6914         // We route 2 dust-HTLCs between A and B
6915         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6916         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6917         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6918
6919         // Cache one local commitment tx as previous
6920         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6921
6922         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6923         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
6924         check_added_monitors!(nodes[1], 0);
6925         expect_pending_htlcs_forwardable!(nodes[1]);
6926         check_added_monitors!(nodes[1], 1);
6927
6928         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6929         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6930         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6931         check_added_monitors!(nodes[0], 1);
6932
6933         // Cache one local commitment tx as lastest
6934         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6935
6936         let events = nodes[0].node.get_and_clear_pending_msg_events();
6937         match events[0] {
6938                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6939                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6940                 },
6941                 _ => panic!("Unexpected event"),
6942         }
6943         match events[1] {
6944                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6945                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6946                 },
6947                 _ => panic!("Unexpected event"),
6948         }
6949
6950         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6951         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6952         if announce_latest {
6953                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6954         } else {
6955                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6956         }
6957
6958         check_closed_broadcast!(nodes[0], false);
6959         check_added_monitors!(nodes[0], 1);
6960
6961         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6962         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6963         let events = nodes[0].node.get_and_clear_pending_events();
6964         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
6965         assert_eq!(events.len(), 2);
6966         let mut first_failed = false;
6967         for event in events {
6968                 match event {
6969                         Event::PaymentFailed { payment_hash, .. } => {
6970                                 if payment_hash == payment_hash_1 {
6971                                         assert!(!first_failed);
6972                                         first_failed = true;
6973                                 } else {
6974                                         assert_eq!(payment_hash, payment_hash_2);
6975                                 }
6976                         }
6977                         _ => panic!("Unexpected event"),
6978                 }
6979         }
6980 }
6981
6982 #[test]
6983 fn test_failure_delay_dust_htlc_local_commitment() {
6984         do_test_failure_delay_dust_htlc_local_commitment(true);
6985         do_test_failure_delay_dust_htlc_local_commitment(false);
6986 }
6987
6988 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6989         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6990         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6991         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6992         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6993         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6994         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6995
6996         let chanmon_cfgs = create_chanmon_cfgs(3);
6997         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6998         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6999         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7000         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7001
7002         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7003
7004         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7005         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7006
7007         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7008         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7009
7010         // We revoked bs_commitment_tx
7011         if revoked {
7012                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7013                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7014         }
7015
7016         let mut timeout_tx = Vec::new();
7017         if local {
7018                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7019                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7020                 check_closed_broadcast!(nodes[0], false);
7021                 check_added_monitors!(nodes[0], 1);
7022                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7023                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7024                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7025                 expect_payment_failed!(nodes[0], dust_hash, true);
7026                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7027                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7028                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7029                 mine_transaction(&nodes[0], &timeout_tx[0]);
7030                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7031                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7032         } else {
7033                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7034                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7035                 check_closed_broadcast!(nodes[0], false);
7036                 check_added_monitors!(nodes[0], 1);
7037                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7038                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7039                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7040                 if !revoked {
7041                         expect_payment_failed!(nodes[0], dust_hash, true);
7042                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7043                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7044                         mine_transaction(&nodes[0], &timeout_tx[0]);
7045                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7046                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7047                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7048                 } else {
7049                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7050                         // commitment tx
7051                         let events = nodes[0].node.get_and_clear_pending_events();
7052                         assert_eq!(events.len(), 2);
7053                         let first;
7054                         match events[0] {
7055                                 Event::PaymentFailed { payment_hash, .. } => {
7056                                         if payment_hash == dust_hash { first = true; }
7057                                         else { first = false; }
7058                                 },
7059                                 _ => panic!("Unexpected event"),
7060                         }
7061                         match events[1] {
7062                                 Event::PaymentFailed { payment_hash, .. } => {
7063                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7064                                         else { assert_eq!(payment_hash, dust_hash); }
7065                                 },
7066                                 _ => panic!("Unexpected event"),
7067                         }
7068                 }
7069         }
7070 }
7071
7072 #[test]
7073 fn test_sweep_outbound_htlc_failure_update() {
7074         do_test_sweep_outbound_htlc_failure_update(false, true);
7075         do_test_sweep_outbound_htlc_failure_update(false, false);
7076         do_test_sweep_outbound_htlc_failure_update(true, false);
7077 }
7078
7079 #[test]
7080 fn test_upfront_shutdown_script() {
7081         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7082         // enforce it at shutdown message
7083
7084         let mut config = UserConfig::default();
7085         config.channel_options.announced_channel = true;
7086         config.peer_channel_config_limits.force_announced_channel_preference = false;
7087         config.channel_options.commit_upfront_shutdown_pubkey = false;
7088         let user_cfgs = [None, Some(config), None];
7089         let chanmon_cfgs = create_chanmon_cfgs(3);
7090         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7091         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7092         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7093
7094         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7095         let flags = InitFeatures::known();
7096         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7097         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7098         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7099         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7100         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
7101         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7102     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()));
7103         check_added_monitors!(nodes[2], 1);
7104
7105         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7106         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7107         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7108         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7109         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7110         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7111         let events = nodes[2].node.get_and_clear_pending_msg_events();
7112         assert_eq!(events.len(), 1);
7113         match events[0] {
7114                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7115                 _ => panic!("Unexpected event"),
7116         }
7117
7118         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7119         let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7120         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7121         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7122         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7123         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7124         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
7125         let events = nodes[1].node.get_and_clear_pending_msg_events();
7126         assert_eq!(events.len(), 1);
7127         match events[0] {
7128                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7129                 _ => panic!("Unexpected event"),
7130         }
7131
7132         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7133         // channel smoothly, opt-out is from channel initiator here
7134         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7135         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7136         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7137         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7138         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7139         let events = nodes[0].node.get_and_clear_pending_msg_events();
7140         assert_eq!(events.len(), 1);
7141         match events[0] {
7142                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7143                 _ => panic!("Unexpected event"),
7144         }
7145
7146         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7147         //// channel smoothly
7148         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7149         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7150         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7151         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7152         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7153         let events = nodes[0].node.get_and_clear_pending_msg_events();
7154         assert_eq!(events.len(), 2);
7155         match events[0] {
7156                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7157                 _ => panic!("Unexpected event"),
7158         }
7159         match events[1] {
7160                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7161                 _ => panic!("Unexpected event"),
7162         }
7163 }
7164
7165 #[test]
7166 fn test_upfront_shutdown_script_unsupport_segwit() {
7167         // We test that channel is closed early
7168         // if a segwit program is passed as upfront shutdown script,
7169         // but the peer does not support segwit.
7170         let chanmon_cfgs = create_chanmon_cfgs(2);
7171         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7172         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7173         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7174
7175         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
7176
7177         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7178         open_channel.shutdown_scriptpubkey = Present(Builder::new().push_int(16)
7179                 .push_slice(&[0, 0])
7180                 .into_script());
7181
7182         let features = InitFeatures::known().clear_shutdown_anysegwit();
7183         nodes[0].node.handle_open_channel(&nodes[0].node.get_our_node_id(), features, &open_channel);
7184
7185         let events = nodes[0].node.get_and_clear_pending_msg_events();
7186         assert_eq!(events.len(), 1);
7187         match events[0] {
7188                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7189                         assert_eq!(node_id, nodes[0].node.get_our_node_id());
7190                         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));
7191                 },
7192                 _ => panic!("Unexpected event"),
7193         }
7194 }
7195
7196 #[test]
7197 fn test_shutdown_script_any_segwit_allowed() {
7198         let mut config = UserConfig::default();
7199         config.channel_options.announced_channel = true;
7200         config.peer_channel_config_limits.force_announced_channel_preference = false;
7201         config.channel_options.commit_upfront_shutdown_pubkey = false;
7202         let user_cfgs = [None, Some(config), None];
7203         let chanmon_cfgs = create_chanmon_cfgs(3);
7204         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7205         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7206         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7207
7208         //// We test if the remote peer accepts opt_shutdown_anysegwit, a witness program can be used on shutdown
7209         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7210         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7211         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7212         node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7213                 .push_slice(&[0, 0])
7214                 .into_script();
7215         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7216         let events = nodes[0].node.get_and_clear_pending_msg_events();
7217         assert_eq!(events.len(), 2);
7218         match events[0] {
7219                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7220                 _ => panic!("Unexpected event"),
7221         }
7222         match events[1] {
7223                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7224                 _ => panic!("Unexpected event"),
7225         }
7226 }
7227
7228 #[test]
7229 fn test_shutdown_script_any_segwit_not_allowed() {
7230         let mut config = UserConfig::default();
7231         config.channel_options.announced_channel = true;
7232         config.peer_channel_config_limits.force_announced_channel_preference = false;
7233         config.channel_options.commit_upfront_shutdown_pubkey = false;
7234         let user_cfgs = [None, Some(config), None];
7235         let chanmon_cfgs = create_chanmon_cfgs(3);
7236         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7237         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7238         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7239
7240         //// We test that if the remote peer does not accept opt_shutdown_anysegwit, the witness program cannot be used on shutdown
7241         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7242         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7243         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7244         // Make an any segwit version script
7245         node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7246                 .push_slice(&[0, 0])
7247                 .into_script();
7248         let flags_no = InitFeatures::known().clear_shutdown_anysegwit();
7249         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &flags_no, &node_0_shutdown);
7250         let events = nodes[0].node.get_and_clear_pending_msg_events();
7251         assert_eq!(events.len(), 2);
7252         match events[1] {
7253                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7254                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7255                         assert_eq!(msg.data, "Got a nonstandard scriptpubkey (60020000) from remote peer".to_owned())
7256                 },
7257                 _ => panic!("Unexpected event"),
7258         }
7259         check_added_monitors!(nodes[0], 1);
7260 }
7261
7262 #[test]
7263 fn test_shutdown_script_segwit_but_not_anysegwit() {
7264         let mut config = UserConfig::default();
7265         config.channel_options.announced_channel = true;
7266         config.peer_channel_config_limits.force_announced_channel_preference = false;
7267         config.channel_options.commit_upfront_shutdown_pubkey = false;
7268         let user_cfgs = [None, Some(config), None];
7269         let chanmon_cfgs = create_chanmon_cfgs(3);
7270         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7271         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7272         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7273
7274         //// We test that if shutdown any segwit is supported and we send a witness script with 0 version, this is not accepted
7275         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7276         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7277         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7278         // Make a segwit script that is not a valid as any segwit
7279         node_0_shutdown.scriptpubkey = Builder::new().push_int(0)
7280                 .push_slice(&[0, 0])
7281                 .into_script();
7282         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7283         let events = nodes[0].node.get_and_clear_pending_msg_events();
7284         assert_eq!(events.len(), 2);
7285         match events[1] {
7286                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7287                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7288                         assert_eq!(msg.data, "Got a nonstandard scriptpubkey (00020000) from remote peer".to_owned())
7289                 },
7290                 _ => panic!("Unexpected event"),
7291         }
7292         check_added_monitors!(nodes[0], 1);
7293 }
7294
7295 #[test]
7296 fn test_user_configurable_csv_delay() {
7297         // We test our channel constructors yield errors when we pass them absurd csv delay
7298
7299         let mut low_our_to_self_config = UserConfig::default();
7300         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7301         let mut high_their_to_self_config = UserConfig::default();
7302         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7303         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7304         let chanmon_cfgs = create_chanmon_cfgs(2);
7305         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7306         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7307         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7308
7309         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7310         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) {
7311                 match error {
7312                         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())); },
7313                         _ => panic!("Unexpected event"),
7314                 }
7315         } else { assert!(false) }
7316
7317         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7318         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7319         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7320         open_channel.to_self_delay = 200;
7321         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) {
7322                 match error {
7323                         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()));  },
7324                         _ => panic!("Unexpected event"),
7325                 }
7326         } else { assert!(false); }
7327
7328         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7329         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7330         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()));
7331         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7332         accept_channel.to_self_delay = 200;
7333         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7334         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7335                 match action {
7336                         &ErrorAction::SendErrorMessage { ref msg } => {
7337                                 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()));
7338                         },
7339                         _ => { assert!(false); }
7340                 }
7341         } else { assert!(false); }
7342
7343         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7344         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7345         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7346         open_channel.to_self_delay = 200;
7347         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) {
7348                 match error {
7349                         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())); },
7350                         _ => panic!("Unexpected event"),
7351                 }
7352         } else { assert!(false); }
7353 }
7354
7355 #[test]
7356 fn test_data_loss_protect() {
7357         // We want to be sure that :
7358         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7359         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7360         // * we close channel in case of detecting other being fallen behind
7361         // * we are able to claim our own outputs thanks to to_remote being static
7362         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7363         let persister;
7364         let logger;
7365         let fee_estimator;
7366         let tx_broadcaster;
7367         let chain_source;
7368         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7369         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7370         // during signing due to revoked tx
7371         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7372         let keys_manager = &chanmon_cfgs[0].keys_manager;
7373         let monitor;
7374         let node_state_0;
7375         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7376         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7377         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7378
7379         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7380
7381         // Cache node A state before any channel update
7382         let previous_node_state = nodes[0].node.encode();
7383         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7384         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7385
7386         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7387         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7388
7389         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7390         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7391
7392         // Restore node A from previous state
7393         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7394         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7395         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7396         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7397         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7398         persister = test_utils::TestPersister::new();
7399         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7400         node_state_0 = {
7401                 let mut channel_monitors = HashMap::new();
7402                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7403                 <(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 {
7404                         keys_manager: keys_manager,
7405                         fee_estimator: &fee_estimator,
7406                         chain_monitor: &monitor,
7407                         logger: &logger,
7408                         tx_broadcaster: &tx_broadcaster,
7409                         default_config: UserConfig::default(),
7410                         channel_monitors,
7411                 }).unwrap().1
7412         };
7413         nodes[0].node = &node_state_0;
7414         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7415         nodes[0].chain_monitor = &monitor;
7416         nodes[0].chain_source = &chain_source;
7417
7418         check_added_monitors!(nodes[0], 1);
7419
7420         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7421         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7422
7423         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7424
7425         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7426         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7427         check_added_monitors!(nodes[0], 1);
7428
7429         {
7430                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7431                 assert_eq!(node_txn.len(), 0);
7432         }
7433
7434         let mut reestablish_1 = Vec::with_capacity(1);
7435         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7436                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7437                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7438                         reestablish_1.push(msg.clone());
7439                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7440                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7441                         match action {
7442                                 &ErrorAction::SendErrorMessage { ref msg } => {
7443                                         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");
7444                                 },
7445                                 _ => panic!("Unexpected event!"),
7446                         }
7447                 } else {
7448                         panic!("Unexpected event")
7449                 }
7450         }
7451
7452         // Check we close channel detecting A is fallen-behind
7453         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7454         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7455         check_added_monitors!(nodes[1], 1);
7456
7457
7458         // Check A is able to claim to_remote output
7459         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7460         assert_eq!(node_txn.len(), 1);
7461         check_spends!(node_txn[0], chan.3);
7462         assert_eq!(node_txn[0].output.len(), 2);
7463         mine_transaction(&nodes[0], &node_txn[0]);
7464         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7465         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 1000000);
7466         assert_eq!(spend_txn.len(), 1);
7467         check_spends!(spend_txn[0], node_txn[0]);
7468 }
7469
7470 #[test]
7471 fn test_check_htlc_underpaying() {
7472         // Send payment through A -> B but A is maliciously
7473         // sending a probe payment (i.e less than expected value0
7474         // to B, B should refuse payment.
7475
7476         let chanmon_cfgs = create_chanmon_cfgs(2);
7477         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7478         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7479         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7480
7481         // Create some initial channels
7482         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7483
7484         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7485
7486         // Node 3 is expecting payment of 100_000 but receive 10_000,
7487         // fail htlc like we didn't know the preimage.
7488         nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7489         nodes[1].node.process_pending_htlc_forwards();
7490
7491         let events = nodes[1].node.get_and_clear_pending_msg_events();
7492         assert_eq!(events.len(), 1);
7493         let (update_fail_htlc, commitment_signed) = match events[0] {
7494                 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 } } => {
7495                         assert!(update_add_htlcs.is_empty());
7496                         assert!(update_fulfill_htlcs.is_empty());
7497                         assert_eq!(update_fail_htlcs.len(), 1);
7498                         assert!(update_fail_malformed_htlcs.is_empty());
7499                         assert!(update_fee.is_none());
7500                         (update_fail_htlcs[0].clone(), commitment_signed)
7501                 },
7502                 _ => panic!("Unexpected event"),
7503         };
7504         check_added_monitors!(nodes[1], 1);
7505
7506         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7507         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7508
7509         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7510         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7511         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7512         expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7513         nodes[1].node.get_and_clear_pending_events();
7514 }
7515
7516 #[test]
7517 fn test_announce_disable_channels() {
7518         // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7519         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7520
7521         let chanmon_cfgs = create_chanmon_cfgs(2);
7522         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7523         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7524         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7525
7526         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7527         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7528         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7529
7530         // Disconnect peers
7531         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7532         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7533
7534         nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7535         nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7536         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7537         assert_eq!(msg_events.len(), 3);
7538         for e in msg_events {
7539                 match e {
7540                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7541                                 let short_id = msg.contents.short_channel_id;
7542                                 // Check generated channel_update match list in PendingChannelUpdate
7543                                 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7544                                         panic!("Generated ChannelUpdate for wrong chan!");
7545                                 }
7546                         },
7547                         _ => panic!("Unexpected event"),
7548                 }
7549         }
7550         // Reconnect peers
7551         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7552         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7553         assert_eq!(reestablish_1.len(), 3);
7554         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7555         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7556         assert_eq!(reestablish_2.len(), 3);
7557
7558         // Reestablish chan_1
7559         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7560         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7561         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7562         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7563         // Reestablish chan_2
7564         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7565         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7566         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7567         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7568         // Reestablish chan_3
7569         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7570         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7571         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7572         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7573
7574         nodes[0].node.timer_chan_freshness_every_min();
7575         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7576 }
7577
7578 #[test]
7579 fn test_bump_penalty_txn_on_revoked_commitment() {
7580         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7581         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7582
7583         let chanmon_cfgs = create_chanmon_cfgs(2);
7584         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7585         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7586         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7587
7588         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7589         let logger = test_utils::TestLogger::new();
7590
7591         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7592         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7593         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();
7594         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7595
7596         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7597         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7598         assert_eq!(revoked_txn[0].output.len(), 4);
7599         assert_eq!(revoked_txn[0].input.len(), 1);
7600         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7601         let revoked_txid = revoked_txn[0].txid();
7602
7603         let mut penalty_sum = 0;
7604         for outp in revoked_txn[0].output.iter() {
7605                 if outp.script_pubkey.is_v0_p2wsh() {
7606                         penalty_sum += outp.value;
7607                 }
7608         }
7609
7610         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7611         let header_114 = connect_blocks(&nodes[1], 14);
7612
7613         // Actually revoke tx by claiming a HTLC
7614         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7615         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7616         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7617         check_added_monitors!(nodes[1], 1);
7618
7619         // One or more justice tx should have been broadcast, check it
7620         let penalty_1;
7621         let feerate_1;
7622         {
7623                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7624                 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7625                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7626                 assert_eq!(node_txn[0].output.len(), 1);
7627                 check_spends!(node_txn[0], revoked_txn[0]);
7628                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7629                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7630                 penalty_1 = node_txn[0].txid();
7631                 node_txn.clear();
7632         };
7633
7634         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7635         connect_blocks(&nodes[1], 15);
7636         let mut penalty_2 = penalty_1;
7637         let mut feerate_2 = 0;
7638         {
7639                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7640                 assert_eq!(node_txn.len(), 1);
7641                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7642                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7643                         assert_eq!(node_txn[0].output.len(), 1);
7644                         check_spends!(node_txn[0], revoked_txn[0]);
7645                         penalty_2 = node_txn[0].txid();
7646                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7647                         assert_ne!(penalty_2, penalty_1);
7648                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7649                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7650                         // Verify 25% bump heuristic
7651                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7652                         node_txn.clear();
7653                 }
7654         }
7655         assert_ne!(feerate_2, 0);
7656
7657         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7658         connect_blocks(&nodes[1], 1);
7659         let penalty_3;
7660         let mut feerate_3 = 0;
7661         {
7662                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7663                 assert_eq!(node_txn.len(), 1);
7664                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7665                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7666                         assert_eq!(node_txn[0].output.len(), 1);
7667                         check_spends!(node_txn[0], revoked_txn[0]);
7668                         penalty_3 = node_txn[0].txid();
7669                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7670                         assert_ne!(penalty_3, penalty_2);
7671                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7672                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7673                         // Verify 25% bump heuristic
7674                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7675                         node_txn.clear();
7676                 }
7677         }
7678         assert_ne!(feerate_3, 0);
7679
7680         nodes[1].node.get_and_clear_pending_events();
7681         nodes[1].node.get_and_clear_pending_msg_events();
7682 }
7683
7684 #[test]
7685 fn test_bump_penalty_txn_on_revoked_htlcs() {
7686         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7687         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7688
7689         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7690         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7691         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7692         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7693         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7694
7695         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7696         // Lock HTLC in both directions
7697         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7698         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7699
7700         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7701         assert_eq!(revoked_local_txn[0].input.len(), 1);
7702         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7703
7704         // Revoke local commitment tx
7705         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7706
7707         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7708         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7709         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7710         check_closed_broadcast!(nodes[1], false);
7711         check_added_monitors!(nodes[1], 1);
7712
7713         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7714         assert_eq!(revoked_htlc_txn.len(), 4);
7715         if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7716                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7717                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7718                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7719                 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7720                 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7721                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7722         } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7723                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7724                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7725                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7726                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7727                 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7728                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7729         }
7730
7731         // Broadcast set of revoked txn on A
7732         let hash_128 = connect_blocks(&nodes[0], 40);
7733         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7734         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7735         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7736         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7737         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7738         let first;
7739         let feerate_1;
7740         let penalty_txn;
7741         {
7742                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7743                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7744                 // Verify claim tx are spending revoked HTLC txn
7745
7746                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7747                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7748                 // which are included in the same block (they are broadcasted because we scan the
7749                 // transactions linearly and generate claims as we go, they likely should be removed in the
7750                 // future).
7751                 assert_eq!(node_txn[0].input.len(), 1);
7752                 check_spends!(node_txn[0], revoked_local_txn[0]);
7753                 assert_eq!(node_txn[1].input.len(), 1);
7754                 check_spends!(node_txn[1], revoked_local_txn[0]);
7755                 assert_eq!(node_txn[2].input.len(), 1);
7756                 check_spends!(node_txn[2], revoked_local_txn[0]);
7757
7758                 // Each of the three justice transactions claim a separate (single) output of the three
7759                 // available, which we check here:
7760                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7761                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7762                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7763
7764                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7765                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7766
7767                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7768                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7769                 // a remote commitment tx has already been confirmed).
7770                 check_spends!(node_txn[3], chan.3);
7771
7772                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7773                 // output, checked above).
7774                 assert_eq!(node_txn[4].input.len(), 2);
7775                 assert_eq!(node_txn[4].output.len(), 1);
7776                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7777
7778                 first = node_txn[4].txid();
7779                 // Store both feerates for later comparison
7780                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7781                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7782                 penalty_txn = vec![node_txn[2].clone()];
7783                 node_txn.clear();
7784         }
7785
7786         // Connect one more block to see if bumped penalty are issued for HTLC txn
7787         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7788         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7789         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7790         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7791         {
7792                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7793                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7794
7795                 check_spends!(node_txn[0], revoked_local_txn[0]);
7796                 check_spends!(node_txn[1], revoked_local_txn[0]);
7797                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7798                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7799                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7800                 } else {
7801                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7802                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7803                 }
7804
7805                 node_txn.clear();
7806         };
7807
7808         // Few more blocks to confirm penalty txn
7809         connect_blocks(&nodes[0], 4);
7810         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7811         let header_144 = connect_blocks(&nodes[0], 9);
7812         let node_txn = {
7813                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7814                 assert_eq!(node_txn.len(), 1);
7815
7816                 assert_eq!(node_txn[0].input.len(), 2);
7817                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7818                 // Verify bumped tx is different and 25% bump heuristic
7819                 assert_ne!(first, node_txn[0].txid());
7820                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7821                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7822                 assert!(feerate_2 * 100 > feerate_1 * 125);
7823                 let txn = vec![node_txn[0].clone()];
7824                 node_txn.clear();
7825                 txn
7826         };
7827         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7828         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7829         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7830         connect_blocks(&nodes[0], 20);
7831         {
7832                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7833                 // We verify than no new transaction has been broadcast because previously
7834                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7835                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7836                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7837                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7838                 // up bumped justice generation.
7839                 assert_eq!(node_txn.len(), 0);
7840                 node_txn.clear();
7841         }
7842         check_closed_broadcast!(nodes[0], false);
7843         check_added_monitors!(nodes[0], 1);
7844 }
7845
7846 #[test]
7847 fn test_bump_penalty_txn_on_remote_commitment() {
7848         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7849         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7850
7851         // Create 2 HTLCs
7852         // Provide preimage for one
7853         // Check aggregation
7854
7855         let chanmon_cfgs = create_chanmon_cfgs(2);
7856         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7857         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7858         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7859
7860         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7861         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7862         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7863
7864         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7865         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7866         assert_eq!(remote_txn[0].output.len(), 4);
7867         assert_eq!(remote_txn[0].input.len(), 1);
7868         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7869
7870         // Claim a HTLC without revocation (provide B monitor with preimage)
7871         nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7872         mine_transaction(&nodes[1], &remote_txn[0]);
7873         check_added_monitors!(nodes[1], 2);
7874
7875         // One or more claim tx should have been broadcast, check it
7876         let timeout;
7877         let preimage;
7878         let feerate_timeout;
7879         let feerate_preimage;
7880         {
7881                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7882                 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7883                 assert_eq!(node_txn[0].input.len(), 1);
7884                 assert_eq!(node_txn[1].input.len(), 1);
7885                 check_spends!(node_txn[0], remote_txn[0]);
7886                 check_spends!(node_txn[1], remote_txn[0]);
7887                 check_spends!(node_txn[2], chan.3);
7888                 check_spends!(node_txn[3], node_txn[2]);
7889                 check_spends!(node_txn[4], node_txn[2]);
7890                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7891                         timeout = node_txn[0].txid();
7892                         let index = node_txn[0].input[0].previous_output.vout;
7893                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7894                         feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7895
7896                         preimage = node_txn[1].txid();
7897                         let index = node_txn[1].input[0].previous_output.vout;
7898                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7899                         feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7900                 } else {
7901                         timeout = node_txn[1].txid();
7902                         let index = node_txn[1].input[0].previous_output.vout;
7903                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7904                         feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7905
7906                         preimage = node_txn[0].txid();
7907                         let index = node_txn[0].input[0].previous_output.vout;
7908                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7909                         feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7910                 }
7911                 node_txn.clear();
7912         };
7913         assert_ne!(feerate_timeout, 0);
7914         assert_ne!(feerate_preimage, 0);
7915
7916         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7917         connect_blocks(&nodes[1], 15);
7918         {
7919                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7920                 assert_eq!(node_txn.len(), 2);
7921                 assert_eq!(node_txn[0].input.len(), 1);
7922                 assert_eq!(node_txn[1].input.len(), 1);
7923                 check_spends!(node_txn[0], remote_txn[0]);
7924                 check_spends!(node_txn[1], remote_txn[0]);
7925                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7926                         let index = node_txn[0].input[0].previous_output.vout;
7927                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7928                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7929                         assert!(new_feerate * 100 > feerate_timeout * 125);
7930                         assert_ne!(timeout, node_txn[0].txid());
7931
7932                         let index = node_txn[1].input[0].previous_output.vout;
7933                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7934                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7935                         assert!(new_feerate * 100 > feerate_preimage * 125);
7936                         assert_ne!(preimage, node_txn[1].txid());
7937                 } else {
7938                         let index = node_txn[1].input[0].previous_output.vout;
7939                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7940                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7941                         assert!(new_feerate * 100 > feerate_timeout * 125);
7942                         assert_ne!(timeout, node_txn[1].txid());
7943
7944                         let index = node_txn[0].input[0].previous_output.vout;
7945                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7946                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7947                         assert!(new_feerate * 100 > feerate_preimage * 125);
7948                         assert_ne!(preimage, node_txn[0].txid());
7949                 }
7950                 node_txn.clear();
7951         }
7952
7953         nodes[1].node.get_and_clear_pending_events();
7954         nodes[1].node.get_and_clear_pending_msg_events();
7955 }
7956
7957 #[test]
7958 fn test_counterparty_raa_skip_no_crash() {
7959         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7960         // commitment transaction, we would have happily carried on and provided them the next
7961         // commitment transaction based on one RAA forward. This would probably eventually have led to
7962         // channel closure, but it would not have resulted in funds loss. Still, our
7963         // EnforcingSigner would have paniced as it doesn't like jumps into the future. Here, we
7964         // check simply that the channel is closed in response to such an RAA, but don't check whether
7965         // we decide to punish our counterparty for revoking their funds (as we don't currently
7966         // implement that).
7967         let chanmon_cfgs = create_chanmon_cfgs(2);
7968         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7969         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7970         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7971         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7972
7973         let mut guard = nodes[0].node.channel_state.lock().unwrap();
7974         let keys = &guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7975         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7976         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7977         // Must revoke without gaps
7978         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7979         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7980                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7981
7982         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7983                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7984         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7985         check_added_monitors!(nodes[1], 1);
7986 }
7987
7988 #[test]
7989 fn test_bump_txn_sanitize_tracking_maps() {
7990         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7991         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7992
7993         let chanmon_cfgs = create_chanmon_cfgs(2);
7994         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7995         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7996         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7997
7998         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7999         // Lock HTLC in both directions
8000         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8001         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8002
8003         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8004         assert_eq!(revoked_local_txn[0].input.len(), 1);
8005         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8006
8007         // Revoke local commitment tx
8008         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8009
8010         // Broadcast set of revoked txn on A
8011         connect_blocks(&nodes[0], 52 - CHAN_CONFIRM_DEPTH);
8012         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8013         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8014
8015         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8016         check_closed_broadcast!(nodes[0], false);
8017         check_added_monitors!(nodes[0], 1);
8018         let penalty_txn = {
8019                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8020                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8021                 check_spends!(node_txn[0], revoked_local_txn[0]);
8022                 check_spends!(node_txn[1], revoked_local_txn[0]);
8023                 check_spends!(node_txn[2], revoked_local_txn[0]);
8024                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8025                 node_txn.clear();
8026                 penalty_txn
8027         };
8028         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8029         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8030         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8031         {
8032                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8033                 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8034                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8035                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8036                 }
8037         }
8038 }
8039
8040 #[test]
8041 fn test_override_channel_config() {
8042         let chanmon_cfgs = create_chanmon_cfgs(2);
8043         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8044         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8045         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8046
8047         // Node0 initiates a channel to node1 using the override config.
8048         let mut override_config = UserConfig::default();
8049         override_config.own_channel_config.our_to_self_delay = 200;
8050
8051         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8052
8053         // Assert the channel created by node0 is using the override config.
8054         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8055         assert_eq!(res.channel_flags, 0);
8056         assert_eq!(res.to_self_delay, 200);
8057 }
8058
8059 #[test]
8060 fn test_override_0msat_htlc_minimum() {
8061         let mut zero_config = UserConfig::default();
8062         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8063         let chanmon_cfgs = create_chanmon_cfgs(2);
8064         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8065         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8066         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8067
8068         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8069         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8070         assert_eq!(res.htlc_minimum_msat, 1);
8071
8072         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8073         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8074         assert_eq!(res.htlc_minimum_msat, 1);
8075 }
8076
8077 #[test]
8078 fn test_simple_payment_secret() {
8079         // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8080         // features, however.
8081         let chanmon_cfgs = create_chanmon_cfgs(3);
8082         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8083         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8084         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8085
8086         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8087         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8088         let logger = test_utils::TestLogger::new();
8089
8090         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8091         let payment_secret = PaymentSecret([0xdb; 32]);
8092         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8093         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();
8094         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8095         // Claiming with all the correct values but the wrong secret should result in nothing...
8096         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8097         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8098         // ...but with the right secret we should be able to claim all the way back
8099         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8100 }
8101
8102 #[test]
8103 fn test_simple_mpp() {
8104         // Simple test of sending a multi-path payment.
8105         let chanmon_cfgs = create_chanmon_cfgs(4);
8106         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8107         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8108         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8109
8110         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8111         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8112         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8113         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8114         let logger = test_utils::TestLogger::new();
8115
8116         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8117         let payment_secret = PaymentSecret([0xdb; 32]);
8118         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8119         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();
8120         let path = route.paths[0].clone();
8121         route.paths.push(path);
8122         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8123         route.paths[0][0].short_channel_id = chan_1_id;
8124         route.paths[0][1].short_channel_id = chan_3_id;
8125         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8126         route.paths[1][0].short_channel_id = chan_2_id;
8127         route.paths[1][1].short_channel_id = chan_4_id;
8128         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8129         // Claiming with all the correct values but the wrong secret should result in nothing...
8130         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8131         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8132         // ...but with the right secret we should be able to claim all the way back
8133         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8134 }
8135
8136 #[test]
8137 fn test_update_err_monitor_lockdown() {
8138         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8139         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8140         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8141         //
8142         // This scenario may happen in a watchtower setup, where watchtower process a block height
8143         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8144         // commitment at same time.
8145
8146         let chanmon_cfgs = create_chanmon_cfgs(2);
8147         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8148         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8149         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8150
8151         // Create some initial channel
8152         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8153         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8154
8155         // Rebalance the network to generate htlc in the two directions
8156         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8157
8158         // Route a HTLC from node 0 to node 1 (but don't settle)
8159         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8160
8161         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8162         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8163         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8164         let persister = test_utils::TestPersister::new();
8165         let watchtower = {
8166                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8167                 let monitor = monitors.get(&outpoint).unwrap();
8168                 let mut w = test_utils::TestVecWriter(Vec::new());
8169                 monitor.write(&mut w).unwrap();
8170                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8171                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8172                 assert!(new_monitor == *monitor);
8173                 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);
8174                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8175                 watchtower
8176         };
8177         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8178         watchtower.chain_monitor.block_connected(&header, &[], 200);
8179
8180         // Try to update ChannelMonitor
8181         assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8182         check_added_monitors!(nodes[1], 1);
8183         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8184         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8185         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8186         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8187                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8188                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8189                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8190                 } else { assert!(false); }
8191         } else { assert!(false); };
8192         // Our local monitor is in-sync and hasn't processed yet timeout
8193         check_added_monitors!(nodes[0], 1);
8194         let events = nodes[0].node.get_and_clear_pending_events();
8195         assert_eq!(events.len(), 1);
8196 }
8197
8198 #[test]
8199 fn test_concurrent_monitor_claim() {
8200         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8201         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8202         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8203         // state N+1 confirms. Alice claims output from state N+1.
8204
8205         let chanmon_cfgs = create_chanmon_cfgs(2);
8206         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8207         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8208         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8209
8210         // Create some initial channel
8211         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8212         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8213
8214         // Rebalance the network to generate htlc in the two directions
8215         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8216
8217         // Route a HTLC from node 0 to node 1 (but don't settle)
8218         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8219
8220         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8221         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8222         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8223         let persister = test_utils::TestPersister::new();
8224         let watchtower_alice = {
8225                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8226                 let monitor = monitors.get(&outpoint).unwrap();
8227                 let mut w = test_utils::TestVecWriter(Vec::new());
8228                 monitor.write(&mut w).unwrap();
8229                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8230                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8231                 assert!(new_monitor == *monitor);
8232                 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);
8233                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8234                 watchtower
8235         };
8236         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8237         watchtower_alice.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8238
8239         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8240         {
8241                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8242                 assert_eq!(txn.len(), 2);
8243                 txn.clear();
8244         }
8245
8246         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8247         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8248         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8249         let persister = test_utils::TestPersister::new();
8250         let watchtower_bob = {
8251                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8252                 let monitor = monitors.get(&outpoint).unwrap();
8253                 let mut w = test_utils::TestVecWriter(Vec::new());
8254                 monitor.write(&mut w).unwrap();
8255                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8256                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8257                 assert!(new_monitor == *monitor);
8258                 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);
8259                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8260                 watchtower
8261         };
8262         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8263         watchtower_bob.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8264
8265         // Route another payment to generate another update with still previous HTLC pending
8266         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8267         {
8268                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8269                 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();
8270                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8271         }
8272         check_added_monitors!(nodes[1], 1);
8273
8274         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8275         assert_eq!(updates.update_add_htlcs.len(), 1);
8276         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8277         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8278                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8279                         // Watchtower Alice should already have seen the block and reject the update
8280                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8281                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8282                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8283                 } else { assert!(false); }
8284         } else { assert!(false); };
8285         // Our local monitor is in-sync and hasn't processed yet timeout
8286         check_added_monitors!(nodes[0], 1);
8287
8288         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8289         watchtower_bob.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8290
8291         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8292         let bob_state_y;
8293         {
8294                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8295                 assert_eq!(txn.len(), 2);
8296                 bob_state_y = txn[0].clone();
8297                 txn.clear();
8298         };
8299
8300         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8301         watchtower_alice.chain_monitor.block_connected(&header, &vec![(0, &bob_state_y)], CHAN_CONFIRM_DEPTH + 2 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8302         {
8303                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8304                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8305                 // the onchain detection of the HTLC output
8306                 assert_eq!(htlc_txn.len(), 2);
8307                 check_spends!(htlc_txn[0], bob_state_y);
8308                 check_spends!(htlc_txn[1], bob_state_y);
8309         }
8310 }
8311
8312 #[test]
8313 fn test_pre_lockin_no_chan_closed_update() {
8314         // Test that if a peer closes a channel in response to a funding_created message we don't
8315         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8316         // message).
8317         //
8318         // Doing so would imply a channel monitor update before the initial channel monitor
8319         // registration, violating our API guarantees.
8320         //
8321         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8322         // then opening a second channel with the same funding output as the first (which is not
8323         // rejected because the first channel does not exist in the ChannelManager) and closing it
8324         // before receiving funding_signed.
8325         let chanmon_cfgs = create_chanmon_cfgs(2);
8326         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8327         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8328         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8329
8330         // Create an initial channel
8331         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8332         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8333         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8334         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8335         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8336
8337         // Move the first channel through the funding flow...
8338         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8339
8340         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8341         check_added_monitors!(nodes[0], 0);
8342
8343         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8344         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8345         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8346         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8347 }
8348
8349 #[test]
8350 fn test_htlc_no_detection() {
8351         // This test is a mutation to underscore the detection logic bug we had
8352         // before #653. HTLC value routed is above the remaining balance, thus
8353         // inverting HTLC and `to_remote` output. HTLC will come second and
8354         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8355         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8356         // outputs order detection for correct spending children filtring.
8357
8358         let chanmon_cfgs = create_chanmon_cfgs(2);
8359         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8360         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8361         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8362
8363         // Create some initial channels
8364         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8365
8366         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000, 1_000_000);
8367         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8368         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8369         assert_eq!(local_txn[0].input.len(), 1);
8370         assert_eq!(local_txn[0].output.len(), 3);
8371         check_spends!(local_txn[0], chan_1.3);
8372
8373         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8374         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8375         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8376         // We deliberately connect the local tx twice as this should provoke a failure calling
8377         // this test before #653 fix.
8378         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);
8379         check_closed_broadcast!(nodes[0], false);
8380         check_added_monitors!(nodes[0], 1);
8381
8382         let htlc_timeout = {
8383                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8384                 assert_eq!(node_txn[0].input.len(), 1);
8385                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8386                 check_spends!(node_txn[0], local_txn[0]);
8387                 node_txn[0].clone()
8388         };
8389
8390         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8391         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8392         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8393         expect_payment_failed!(nodes[0], our_payment_hash, true);
8394 }
8395
8396 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8397         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8398         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8399         // Carol, Alice would be the upstream node, and Carol the downstream.)
8400         //
8401         // Steps of the test:
8402         // 1) Alice sends a HTLC to Carol through Bob.
8403         // 2) Carol doesn't settle the HTLC.
8404         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8405         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8406         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8407         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8408         // 5) Carol release the preimage to Bob off-chain.
8409         // 6) Bob claims the offered output on the broadcasted commitment.
8410         let chanmon_cfgs = create_chanmon_cfgs(3);
8411         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8412         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8413         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8414
8415         // Create some initial channels
8416         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8417         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8418
8419         // Steps (1) and (2):
8420         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8421         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8422
8423         // Check that Alice's commitment transaction now contains an output for this HTLC.
8424         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8425         check_spends!(alice_txn[0], chan_ab.3);
8426         assert_eq!(alice_txn[0].output.len(), 2);
8427         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8428         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8429         assert_eq!(alice_txn.len(), 2);
8430
8431         // Steps (3) and (4):
8432         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8433         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8434         let mut force_closing_node = 0; // Alice force-closes
8435         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8436         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8437         check_closed_broadcast!(nodes[force_closing_node], false);
8438         check_added_monitors!(nodes[force_closing_node], 1);
8439         if go_onchain_before_fulfill {
8440                 let txn_to_broadcast = match broadcast_alice {
8441                         true => alice_txn.clone(),
8442                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8443                 };
8444                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8445                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8446                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8447                 if broadcast_alice {
8448                         check_closed_broadcast!(nodes[1], false);
8449                         check_added_monitors!(nodes[1], 1);
8450                 }
8451                 assert_eq!(bob_txn.len(), 1);
8452                 check_spends!(bob_txn[0], chan_ab.3);
8453         }
8454
8455         // Step (5):
8456         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8457         // process of removing the HTLC from their commitment transactions.
8458         assert!(nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000));
8459         check_added_monitors!(nodes[2], 1);
8460         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8461         assert!(carol_updates.update_add_htlcs.is_empty());
8462         assert!(carol_updates.update_fail_htlcs.is_empty());
8463         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8464         assert!(carol_updates.update_fee.is_none());
8465         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8466
8467         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8468         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8469         if !go_onchain_before_fulfill && broadcast_alice {
8470                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8471                 assert_eq!(events.len(), 1);
8472                 match events[0] {
8473                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8474                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8475                         },
8476                         _ => panic!("Unexpected event"),
8477                 };
8478         }
8479         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8480         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8481         // Carol<->Bob's updated commitment transaction info.
8482         check_added_monitors!(nodes[1], 2);
8483
8484         let events = nodes[1].node.get_and_clear_pending_msg_events();
8485         assert_eq!(events.len(), 2);
8486         let bob_revocation = match events[0] {
8487                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8488                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8489                         (*msg).clone()
8490                 },
8491                 _ => panic!("Unexpected event"),
8492         };
8493         let bob_updates = match events[1] {
8494                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8495                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8496                         (*updates).clone()
8497                 },
8498                 _ => panic!("Unexpected event"),
8499         };
8500
8501         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8502         check_added_monitors!(nodes[2], 1);
8503         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8504         check_added_monitors!(nodes[2], 1);
8505
8506         let events = nodes[2].node.get_and_clear_pending_msg_events();
8507         assert_eq!(events.len(), 1);
8508         let carol_revocation = match events[0] {
8509                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8510                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8511                         (*msg).clone()
8512                 },
8513                 _ => panic!("Unexpected event"),
8514         };
8515         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8516         check_added_monitors!(nodes[1], 1);
8517
8518         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8519         // here's where we put said channel's commitment tx on-chain.
8520         let mut txn_to_broadcast = alice_txn.clone();
8521         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8522         if !go_onchain_before_fulfill {
8523                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8524                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8525                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8526                 if broadcast_alice {
8527                         check_closed_broadcast!(nodes[1], false);
8528                         check_added_monitors!(nodes[1], 1);
8529                 }
8530                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8531                 if broadcast_alice {
8532                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8533                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8534                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8535                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8536                         // broadcasted.
8537                         assert_eq!(bob_txn.len(), 3);
8538                         check_spends!(bob_txn[1], chan_ab.3);
8539                 } else {
8540                         assert_eq!(bob_txn.len(), 2);
8541                         check_spends!(bob_txn[0], chan_ab.3);
8542                 }
8543         }
8544
8545         // Step (6):
8546         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8547         // broadcasted commitment transaction.
8548         {
8549                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8550                 if go_onchain_before_fulfill {
8551                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8552                         assert_eq!(bob_txn.len(), 2);
8553                 }
8554                 let script_weight = match broadcast_alice {
8555                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8556                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8557                 };
8558                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8559                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8560                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8561                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8562                 if broadcast_alice && !go_onchain_before_fulfill {
8563                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8564                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8565                 } else {
8566                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8567                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8568                 }
8569         }
8570 }
8571
8572 #[test]
8573 fn test_onchain_htlc_settlement_after_close() {
8574         do_test_onchain_htlc_settlement_after_close(true, true);
8575         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8576         do_test_onchain_htlc_settlement_after_close(true, false);
8577         do_test_onchain_htlc_settlement_after_close(false, false);
8578 }
8579
8580 #[test]
8581 fn test_duplicate_chan_id() {
8582         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8583         // already open we reject it and keep the old channel.
8584         //
8585         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8586         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8587         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8588         // updating logic for the existing channel.
8589         let chanmon_cfgs = create_chanmon_cfgs(2);
8590         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8591         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8592         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8593
8594         // Create an initial channel
8595         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8596         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8597         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8598         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()));
8599
8600         // Try to create a second channel with the same temporary_channel_id as the first and check
8601         // that it is rejected.
8602         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8603         {
8604                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8605                 assert_eq!(events.len(), 1);
8606                 match events[0] {
8607                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8608                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8609                                 // first (valid) and second (invalid) channels are closed, given they both have
8610                                 // the same non-temporary channel_id. However, currently we do not, so we just
8611                                 // move forward with it.
8612                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8613                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8614                         },
8615                         _ => panic!("Unexpected event"),
8616                 }
8617         }
8618
8619         // Move the first channel through the funding flow...
8620         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8621
8622         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8623         check_added_monitors!(nodes[0], 0);
8624
8625         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8626         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8627         {
8628                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8629                 assert_eq!(added_monitors.len(), 1);
8630                 assert_eq!(added_monitors[0].0, funding_output);
8631                 added_monitors.clear();
8632         }
8633         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8634
8635         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8636         let channel_id = funding_outpoint.to_channel_id();
8637
8638         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8639         // temporary one).
8640
8641         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8642         // Technically this is allowed by the spec, but we don't support it and there's little reason
8643         // to. Still, it shouldn't cause any other issues.
8644         open_chan_msg.temporary_channel_id = channel_id;
8645         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8646         {
8647                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8648                 assert_eq!(events.len(), 1);
8649                 match events[0] {
8650                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8651                                 // Technically, at this point, nodes[1] would be justified in thinking both
8652                                 // channels are closed, but currently we do not, so we just move forward with it.
8653                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8654                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8655                         },
8656                         _ => panic!("Unexpected event"),
8657                 }
8658         }
8659
8660         // Now try to create a second channel which has a duplicate funding output.
8661         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8662         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8663         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8664         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()));
8665         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8666
8667         let funding_created = {
8668                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8669                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8670                 let logger = test_utils::TestLogger::new();
8671                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8672         };
8673         check_added_monitors!(nodes[0], 0);
8674         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8675         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8676         // still needs to be cleared here.
8677         check_added_monitors!(nodes[1], 1);
8678
8679         // ...still, nodes[1] will reject the duplicate channel.
8680         {
8681                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8682                 assert_eq!(events.len(), 1);
8683                 match events[0] {
8684                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8685                                 // Technically, at this point, nodes[1] would be justified in thinking both
8686                                 // channels are closed, but currently we do not, so we just move forward with it.
8687                                 assert_eq!(msg.channel_id, channel_id);
8688                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8689                         },
8690                         _ => panic!("Unexpected event"),
8691                 }
8692         }
8693
8694         // finally, finish creating the original channel and send a payment over it to make sure
8695         // everything is functional.
8696         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8697         {
8698                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8699                 assert_eq!(added_monitors.len(), 1);
8700                 assert_eq!(added_monitors[0].0, funding_output);
8701                 added_monitors.clear();
8702         }
8703
8704         let events_4 = nodes[0].node.get_and_clear_pending_events();
8705         assert_eq!(events_4.len(), 0);
8706         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8707         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
8708
8709         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8710         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8711         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8712         send_payment(&nodes[0], &[&nodes[1]], 8000000, 8_000_000);
8713 }
8714
8715 #[test]
8716 fn test_error_chans_closed() {
8717         // Test that we properly handle error messages, closing appropriate channels.
8718         //
8719         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8720         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8721         // we can test various edge cases around it to ensure we don't regress.
8722         let chanmon_cfgs = create_chanmon_cfgs(3);
8723         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8724         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8725         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8726
8727         // Create some initial channels
8728         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8729         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8730         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8731
8732         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8733         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8734         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8735
8736         // Closing a channel from a different peer has no effect
8737         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8738         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8739
8740         // Closing one channel doesn't impact others
8741         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8742         check_added_monitors!(nodes[0], 1);
8743         check_closed_broadcast!(nodes[0], false);
8744         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8745         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8746         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);
8747         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);
8748
8749         // A null channel ID should close all channels
8750         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8751         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8752         check_added_monitors!(nodes[0], 2);
8753         let events = nodes[0].node.get_and_clear_pending_msg_events();
8754         assert_eq!(events.len(), 2);
8755         match events[0] {
8756                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8757                         assert_eq!(msg.contents.flags & 2, 2);
8758                 },
8759                 _ => panic!("Unexpected event"),
8760         }
8761         match events[1] {
8762                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8763                         assert_eq!(msg.contents.flags & 2, 2);
8764                 },
8765                 _ => panic!("Unexpected event"),
8766         }
8767         // Note that at this point users of a standard PeerHandler will end up calling
8768         // peer_disconnected with no_connection_possible set to false, duplicating the
8769         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8770         // users with their own peer handling logic. We duplicate the call here, however.
8771         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8772         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8773
8774         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8775         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8776         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8777 }