c7a79e32210639fddcd4c3d01ab16e6f311248a3
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use chain;
15 use chain::Watch;
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::{Sign, KeysInterface};
20 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
21 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
22 use ln::channel::{Channel, ChannelError};
23 use ln::{chan_utils, onion_utils};
24 use routing::router::{Route, RouteHop, get_route};
25 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
26 use ln::msgs;
27 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
28 use util::enforcing_trait_impls::EnforcingSigner;
29 use util::{byte_utils, test_utils};
30 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
31 use util::errors::APIError;
32 use util::ser::{Writeable, ReadableArgs};
33 use util::config::UserConfig;
34
35 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
36 use bitcoin::hash_types::{Txid, BlockHash};
37 use bitcoin::blockdata::block::{Block, BlockHeader};
38 use bitcoin::blockdata::script::Builder;
39 use bitcoin::blockdata::opcodes;
40 use bitcoin::blockdata::constants::genesis_block;
41 use bitcoin::network::constants::Network;
42
43 use bitcoin::hashes::sha256::Hash as Sha256;
44 use bitcoin::hashes::Hash;
45
46 use bitcoin::secp256k1::{Secp256k1, Message};
47 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
48
49 use regex;
50
51 use std::collections::{BTreeSet, HashMap, HashSet};
52 use std::default::Default;
53 use std::sync::Mutex;
54 use std::sync::atomic::Ordering;
55
56 use ln::functional_test_utils::*;
57 use ln::chan_utils::CommitmentTransaction;
58 use ln::msgs::OptionalField::Present;
59
60 #[test]
61 fn test_insane_channel_opens() {
62         // Stand up a network of 2 nodes
63         let chanmon_cfgs = create_chanmon_cfgs(2);
64         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
65         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
66         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
67
68         // Instantiate channel parameters where we push the maximum msats given our
69         // funding satoshis
70         let channel_value_sat = 31337; // same as funding satoshis
71         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
72         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
73
74         // Have node0 initiate a channel to node1 with aforementioned parameters
75         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
76
77         // Extract the channel open message from node0 to node1
78         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
79
80         // Test helper that asserts we get the correct error string given a mutator
81         // that supposedly makes the channel open message insane
82         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
83                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
84                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
85                 assert_eq!(msg_events.len(), 1);
86                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
87                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
88                         match action {
89                                 &ErrorAction::SendErrorMessage { .. } => {
90                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
91                                 },
92                                 _ => panic!("unexpected event!"),
93                         }
94                 } else { assert!(false); }
95         };
96
97         use ln::channel::MAX_FUNDING_SATOSHIS;
98         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
99
100         // Test all mutations that would make the channel open message insane
101         insane_open_helper(format!("Funding must be smaller than {}. It was {}", MAX_FUNDING_SATOSHIS, MAX_FUNDING_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
102
103         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
104
105         insane_open_helper(r"push_msat \d+ was larger than funding value \d+", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
106
107         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
108
109         insane_open_helper(r"Bogus; channel reserve \(\d+\) is less than dust limit \(\d+\)", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
110
111         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
112
113         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
114
115         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
116
117         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
118 }
119
120 #[test]
121 fn test_async_inbound_update_fee() {
122         let chanmon_cfgs = create_chanmon_cfgs(2);
123         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
124         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
125         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
126         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
127         let logger = test_utils::TestLogger::new();
128         let channel_id = chan.2;
129
130         // balancing
131         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
132
133         // A                                        B
134         // update_fee                            ->
135         // send (1) commitment_signed            -.
136         //                                       <- update_add_htlc/commitment_signed
137         // send (2) RAA (awaiting remote revoke) -.
138         // (1) commitment_signed is delivered    ->
139         //                                       .- send (3) RAA (awaiting remote revoke)
140         // (2) RAA is delivered                  ->
141         //                                       .- send (4) commitment_signed
142         //                                       <- (3) RAA is delivered
143         // send (5) commitment_signed            -.
144         //                                       <- (4) commitment_signed is delivered
145         // send (6) RAA                          -.
146         // (5) commitment_signed is delivered    ->
147         //                                       <- RAA
148         // (6) RAA is delivered                  ->
149
150         // First nodes[0] generates an update_fee
151         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
152         check_added_monitors!(nodes[0], 1);
153
154         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
155         assert_eq!(events_0.len(), 1);
156         let (update_msg, commitment_signed) = match events_0[0] { // (1)
157                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
158                         (update_fee.as_ref(), commitment_signed)
159                 },
160                 _ => panic!("Unexpected event"),
161         };
162
163         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
164
165         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
166         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
167         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
168         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
169         check_added_monitors!(nodes[1], 1);
170
171         let payment_event = {
172                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
173                 assert_eq!(events_1.len(), 1);
174                 SendEvent::from_event(events_1.remove(0))
175         };
176         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
177         assert_eq!(payment_event.msgs.len(), 1);
178
179         // ...now when the messages get delivered everyone should be happy
180         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
181         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
182         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
183         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
184         check_added_monitors!(nodes[0], 1);
185
186         // deliver(1), generate (3):
187         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
188         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
189         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
190         check_added_monitors!(nodes[1], 1);
191
192         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
193         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
194         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
195         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
196         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
197         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
198         assert!(bs_update.update_fee.is_none()); // (4)
199         check_added_monitors!(nodes[1], 1);
200
201         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
202         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
203         assert!(as_update.update_add_htlcs.is_empty()); // (5)
204         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
205         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
206         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
207         assert!(as_update.update_fee.is_none()); // (5)
208         check_added_monitors!(nodes[0], 1);
209
210         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
211         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
212         // only (6) so get_event_msg's assert(len == 1) passes
213         check_added_monitors!(nodes[0], 1);
214
215         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
216         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
217         check_added_monitors!(nodes[1], 1);
218
219         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
220         check_added_monitors!(nodes[0], 1);
221
222         let events_2 = nodes[0].node.get_and_clear_pending_events();
223         assert_eq!(events_2.len(), 1);
224         match events_2[0] {
225                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
226                 _ => panic!("Unexpected event"),
227         }
228
229         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
230         check_added_monitors!(nodes[1], 1);
231 }
232
233 #[test]
234 fn test_update_fee_unordered_raa() {
235         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
236         // crash in an earlier version of the update_fee patch)
237         let chanmon_cfgs = create_chanmon_cfgs(2);
238         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
239         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
240         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
241         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
242         let channel_id = chan.2;
243         let logger = test_utils::TestLogger::new();
244
245         // balancing
246         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
247
248         // First nodes[0] generates an update_fee
249         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
250         check_added_monitors!(nodes[0], 1);
251
252         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
253         assert_eq!(events_0.len(), 1);
254         let update_msg = match events_0[0] { // (1)
255                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
256                         update_fee.as_ref()
257                 },
258                 _ => panic!("Unexpected event"),
259         };
260
261         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
262
263         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
264         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
265         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
266         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
267         check_added_monitors!(nodes[1], 1);
268
269         let payment_event = {
270                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
271                 assert_eq!(events_1.len(), 1);
272                 SendEvent::from_event(events_1.remove(0))
273         };
274         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
275         assert_eq!(payment_event.msgs.len(), 1);
276
277         // ...now when the messages get delivered everyone should be happy
278         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
279         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
280         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
281         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
282         check_added_monitors!(nodes[0], 1);
283
284         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
285         check_added_monitors!(nodes[1], 1);
286
287         // We can't continue, sadly, because our (1) now has a bogus signature
288 }
289
290 #[test]
291 fn test_multi_flight_update_fee() {
292         let chanmon_cfgs = create_chanmon_cfgs(2);
293         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
294         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
295         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
296         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
297         let channel_id = chan.2;
298
299         // A                                        B
300         // update_fee/commitment_signed          ->
301         //                                       .- send (1) RAA and (2) commitment_signed
302         // update_fee (never committed)          ->
303         // (3) update_fee                        ->
304         // We have to manually generate the above update_fee, it is allowed by the protocol but we
305         // don't track which updates correspond to which revoke_and_ack responses so we're in
306         // AwaitingRAA mode and will not generate the update_fee yet.
307         //                                       <- (1) RAA delivered
308         // (3) is generated and send (4) CS      -.
309         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
310         // know the per_commitment_point to use for it.
311         //                                       <- (2) commitment_signed delivered
312         // revoke_and_ack                        ->
313         //                                          B should send no response here
314         // (4) commitment_signed delivered       ->
315         //                                       <- RAA/commitment_signed delivered
316         // revoke_and_ack                        ->
317
318         // First nodes[0] generates an update_fee
319         let initial_feerate = get_feerate!(nodes[0], channel_id);
320         nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
321         check_added_monitors!(nodes[0], 1);
322
323         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
324         assert_eq!(events_0.len(), 1);
325         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
326                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
327                         (update_fee.as_ref().unwrap(), commitment_signed)
328                 },
329                 _ => panic!("Unexpected event"),
330         };
331
332         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
333         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
334         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
335         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
336         check_added_monitors!(nodes[1], 1);
337
338         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
339         // transaction:
340         nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
341         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
342         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
343
344         // Create the (3) update_fee message that nodes[0] will generate before it does...
345         let mut update_msg_2 = msgs::UpdateFee {
346                 channel_id: update_msg_1.channel_id.clone(),
347                 feerate_per_kw: (initial_feerate + 30) as u32,
348         };
349
350         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
351
352         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
353         // Deliver (3)
354         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
355
356         // Deliver (1), generating (3) and (4)
357         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
358         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
359         check_added_monitors!(nodes[0], 1);
360         assert!(as_second_update.update_add_htlcs.is_empty());
361         assert!(as_second_update.update_fulfill_htlcs.is_empty());
362         assert!(as_second_update.update_fail_htlcs.is_empty());
363         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
364         // Check that the update_fee newly generated matches what we delivered:
365         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
366         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
367
368         // Deliver (2) commitment_signed
369         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
370         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
371         check_added_monitors!(nodes[0], 1);
372         // No commitment_signed so get_event_msg's assert(len == 1) passes
373
374         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
375         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
376         check_added_monitors!(nodes[1], 1);
377
378         // Delever (4)
379         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
380         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
381         check_added_monitors!(nodes[1], 1);
382
383         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
384         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
385         check_added_monitors!(nodes[0], 1);
386
387         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
388         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
389         // No commitment_signed so get_event_msg's assert(len == 1) passes
390         check_added_monitors!(nodes[0], 1);
391
392         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
393         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
394         check_added_monitors!(nodes[1], 1);
395 }
396
397 #[test]
398 fn test_1_conf_open() {
399         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
400         // tests that we properly send one in that case.
401         let mut alice_config = UserConfig::default();
402         alice_config.own_channel_config.minimum_depth = 1;
403         alice_config.channel_options.announced_channel = true;
404         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
405         let mut bob_config = UserConfig::default();
406         bob_config.own_channel_config.minimum_depth = 1;
407         bob_config.channel_options.announced_channel = true;
408         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
409         let chanmon_cfgs = create_chanmon_cfgs(2);
410         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
411         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
412         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
413
414         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
415         mine_transaction(&nodes[1], &tx);
416         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id()));
417
418         mine_transaction(&nodes[0], &tx);
419         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
420         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
421
422         for node in nodes {
423                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
424                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
425                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
426         }
427 }
428
429 fn do_test_sanity_on_in_flight_opens(steps: u8) {
430         // Previously, we had issues deserializing channels when we hadn't connected the first block
431         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
432         // serialization round-trips and simply do steps towards opening a channel and then drop the
433         // Node objects.
434
435         let chanmon_cfgs = create_chanmon_cfgs(2);
436         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
437         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
438         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
439
440         if steps & 0b1000_0000 != 0{
441                 let block = Block {
442                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
443                         txdata: vec![],
444                 };
445                 connect_block(&nodes[0], &block);
446                 connect_block(&nodes[1], &block);
447         }
448
449         if steps & 0x0f == 0 { return; }
450         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
451         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
452
453         if steps & 0x0f == 1 { return; }
454         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
455         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
456
457         if steps & 0x0f == 2 { return; }
458         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
459
460         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
461
462         if steps & 0x0f == 3 { return; }
463         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
464         check_added_monitors!(nodes[0], 0);
465         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
466
467         if steps & 0x0f == 4 { return; }
468         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
469         {
470                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
471                 assert_eq!(added_monitors.len(), 1);
472                 assert_eq!(added_monitors[0].0, funding_output);
473                 added_monitors.clear();
474         }
475         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
476
477         if steps & 0x0f == 5 { return; }
478         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
479         {
480                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
481                 assert_eq!(added_monitors.len(), 1);
482                 assert_eq!(added_monitors[0].0, funding_output);
483                 added_monitors.clear();
484         }
485
486         let events_4 = nodes[0].node.get_and_clear_pending_events();
487         assert_eq!(events_4.len(), 1);
488         match events_4[0] {
489                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
490                         assert_eq!(user_channel_id, 42);
491                         assert_eq!(*funding_txo, funding_output);
492                 },
493                 _ => panic!("Unexpected event"),
494         };
495
496         if steps & 0x0f == 6 { return; }
497         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
498
499         if steps & 0x0f == 7 { return; }
500         confirm_transaction_at(&nodes[0], &tx, 2);
501         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
502         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
503 }
504
505 #[test]
506 fn test_sanity_on_in_flight_opens() {
507         do_test_sanity_on_in_flight_opens(0);
508         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
509         do_test_sanity_on_in_flight_opens(1);
510         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
511         do_test_sanity_on_in_flight_opens(2);
512         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
513         do_test_sanity_on_in_flight_opens(3);
514         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
515         do_test_sanity_on_in_flight_opens(4);
516         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
517         do_test_sanity_on_in_flight_opens(5);
518         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
519         do_test_sanity_on_in_flight_opens(6);
520         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
521         do_test_sanity_on_in_flight_opens(7);
522         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
523         do_test_sanity_on_in_flight_opens(8);
524         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
525 }
526
527 #[test]
528 fn test_update_fee_vanilla() {
529         let chanmon_cfgs = create_chanmon_cfgs(2);
530         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
531         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
532         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
533         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
534         let channel_id = chan.2;
535
536         let feerate = get_feerate!(nodes[0], channel_id);
537         nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
538         check_added_monitors!(nodes[0], 1);
539
540         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
541         assert_eq!(events_0.len(), 1);
542         let (update_msg, commitment_signed) = match events_0[0] {
543                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
544                         (update_fee.as_ref(), commitment_signed)
545                 },
546                 _ => panic!("Unexpected event"),
547         };
548         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
549
550         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
551         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
552         check_added_monitors!(nodes[1], 1);
553
554         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
555         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
556         check_added_monitors!(nodes[0], 1);
557
558         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
559         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
560         // No commitment_signed so get_event_msg's assert(len == 1) passes
561         check_added_monitors!(nodes[0], 1);
562
563         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
564         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
565         check_added_monitors!(nodes[1], 1);
566 }
567
568 #[test]
569 fn test_update_fee_that_funder_cannot_afford() {
570         let chanmon_cfgs = create_chanmon_cfgs(2);
571         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
572         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
573         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
574         let channel_value = 1888;
575         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
576         let channel_id = chan.2;
577
578         let feerate = 260;
579         nodes[0].node.update_fee(channel_id, feerate).unwrap();
580         check_added_monitors!(nodes[0], 1);
581         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
582
583         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
584
585         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
586
587         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
588         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
589         {
590                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
591
592                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
593                 let num_htlcs = commitment_tx.output.len() - 2;
594                 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
595                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
596                 actual_fee = channel_value - actual_fee;
597                 assert_eq!(total_fee, actual_fee);
598         }
599
600         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
601         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
602         nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
603         check_added_monitors!(nodes[0], 1);
604
605         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
606
607         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
608
609         //While producing the commitment_signed response after handling a received update_fee request the
610         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
611         //Should produce and error.
612         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
613         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
614         check_added_monitors!(nodes[1], 1);
615         check_closed_broadcast!(nodes[1], true);
616 }
617
618 #[test]
619 fn test_update_fee_with_fundee_update_add_htlc() {
620         let chanmon_cfgs = create_chanmon_cfgs(2);
621         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
622         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
623         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
624         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
625         let channel_id = chan.2;
626         let logger = test_utils::TestLogger::new();
627
628         // balancing
629         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
630
631         let feerate = get_feerate!(nodes[0], channel_id);
632         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
633         check_added_monitors!(nodes[0], 1);
634
635         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
636         assert_eq!(events_0.len(), 1);
637         let (update_msg, commitment_signed) = match events_0[0] {
638                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
639                         (update_fee.as_ref(), commitment_signed)
640                 },
641                 _ => panic!("Unexpected event"),
642         };
643         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
644         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
645         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
646         check_added_monitors!(nodes[1], 1);
647
648         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
649         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
650         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 800000, TEST_FINAL_CLTV, &logger).unwrap();
651
652         // nothing happens since node[1] is in AwaitingRemoteRevoke
653         nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
654         {
655                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
656                 assert_eq!(added_monitors.len(), 0);
657                 added_monitors.clear();
658         }
659         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
660         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
661         // node[1] has nothing to do
662
663         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
664         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
665         check_added_monitors!(nodes[0], 1);
666
667         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
668         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
669         // No commitment_signed so get_event_msg's assert(len == 1) passes
670         check_added_monitors!(nodes[0], 1);
671         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
672         check_added_monitors!(nodes[1], 1);
673         // AwaitingRemoteRevoke ends here
674
675         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
676         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
677         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
678         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
679         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
680         assert_eq!(commitment_update.update_fee.is_none(), true);
681
682         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
683         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
684         check_added_monitors!(nodes[0], 1);
685         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
686
687         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
688         check_added_monitors!(nodes[1], 1);
689         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
690
691         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
692         check_added_monitors!(nodes[1], 1);
693         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
694         // No commitment_signed so get_event_msg's assert(len == 1) passes
695
696         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
697         check_added_monitors!(nodes[0], 1);
698         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
699
700         expect_pending_htlcs_forwardable!(nodes[0]);
701
702         let events = nodes[0].node.get_and_clear_pending_events();
703         assert_eq!(events.len(), 1);
704         match events[0] {
705                 Event::PaymentReceived { .. } => { },
706                 _ => panic!("Unexpected event"),
707         };
708
709         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
710
711         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
712         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
713         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
714 }
715
716 #[test]
717 fn test_update_fee() {
718         let chanmon_cfgs = create_chanmon_cfgs(2);
719         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
720         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
721         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
722         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
723         let channel_id = chan.2;
724
725         // A                                        B
726         // (1) update_fee/commitment_signed      ->
727         //                                       <- (2) revoke_and_ack
728         //                                       .- send (3) commitment_signed
729         // (4) update_fee/commitment_signed      ->
730         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
731         //                                       <- (3) commitment_signed delivered
732         // send (6) revoke_and_ack               -.
733         //                                       <- (5) deliver revoke_and_ack
734         // (6) deliver revoke_and_ack            ->
735         //                                       .- send (7) commitment_signed in response to (4)
736         //                                       <- (7) deliver commitment_signed
737         // revoke_and_ack                        ->
738
739         // Create and deliver (1)...
740         let feerate = get_feerate!(nodes[0], channel_id);
741         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
742         check_added_monitors!(nodes[0], 1);
743
744         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
745         assert_eq!(events_0.len(), 1);
746         let (update_msg, commitment_signed) = match events_0[0] {
747                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
748                         (update_fee.as_ref(), commitment_signed)
749                 },
750                 _ => panic!("Unexpected event"),
751         };
752         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
753
754         // Generate (2) and (3):
755         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
756         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
757         check_added_monitors!(nodes[1], 1);
758
759         // Deliver (2):
760         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
761         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
762         check_added_monitors!(nodes[0], 1);
763
764         // Create and deliver (4)...
765         nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
766         check_added_monitors!(nodes[0], 1);
767         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
768         assert_eq!(events_0.len(), 1);
769         let (update_msg, commitment_signed) = match events_0[0] {
770                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
771                         (update_fee.as_ref(), commitment_signed)
772                 },
773                 _ => panic!("Unexpected event"),
774         };
775
776         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
777         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
778         check_added_monitors!(nodes[1], 1);
779         // ... creating (5)
780         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
781         // No commitment_signed so get_event_msg's assert(len == 1) passes
782
783         // Handle (3), creating (6):
784         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
785         check_added_monitors!(nodes[0], 1);
786         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
787         // No commitment_signed so get_event_msg's assert(len == 1) passes
788
789         // Deliver (5):
790         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
791         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
792         check_added_monitors!(nodes[0], 1);
793
794         // Deliver (6), creating (7):
795         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
796         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
797         assert!(commitment_update.update_add_htlcs.is_empty());
798         assert!(commitment_update.update_fulfill_htlcs.is_empty());
799         assert!(commitment_update.update_fail_htlcs.is_empty());
800         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
801         assert!(commitment_update.update_fee.is_none());
802         check_added_monitors!(nodes[1], 1);
803
804         // Deliver (7)
805         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
806         check_added_monitors!(nodes[0], 1);
807         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
808         // No commitment_signed so get_event_msg's assert(len == 1) passes
809
810         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
811         check_added_monitors!(nodes[1], 1);
812         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
813
814         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
815         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
816         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
817 }
818
819 #[test]
820 fn pre_funding_lock_shutdown_test() {
821         // Test sending a shutdown prior to funding_locked after funding generation
822         let chanmon_cfgs = create_chanmon_cfgs(2);
823         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
824         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
825         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
826         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
827         mine_transaction(&nodes[0], &tx);
828         mine_transaction(&nodes[1], &tx);
829
830         nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
831         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
832         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
833         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
834         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
835
836         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
837         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
838         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
839         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
840         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
841         assert!(node_0_none.is_none());
842
843         assert!(nodes[0].node.list_channels().is_empty());
844         assert!(nodes[1].node.list_channels().is_empty());
845 }
846
847 #[test]
848 fn updates_shutdown_wait() {
849         // Test sending a shutdown with outstanding updates pending
850         let chanmon_cfgs = create_chanmon_cfgs(3);
851         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
852         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
853         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
854         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
855         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
856         let logger = test_utils::TestLogger::new();
857
858         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
859
860         nodes[0].node.close_channel(&chan_1.2).unwrap();
861         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
862         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
863         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
864         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
865
866         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
867         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
868
869         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
870
871         let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
872         let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
873         let route_1 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler0.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
874         let route_2 = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler1.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
875         unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
876         unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
877
878         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
879         check_added_monitors!(nodes[2], 1);
880         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
881         assert!(updates.update_add_htlcs.is_empty());
882         assert!(updates.update_fail_htlcs.is_empty());
883         assert!(updates.update_fail_malformed_htlcs.is_empty());
884         assert!(updates.update_fee.is_none());
885         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
886         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
887         check_added_monitors!(nodes[1], 1);
888         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
889         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
890
891         assert!(updates_2.update_add_htlcs.is_empty());
892         assert!(updates_2.update_fail_htlcs.is_empty());
893         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
894         assert!(updates_2.update_fee.is_none());
895         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
896         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
897         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
898
899         let events = nodes[0].node.get_and_clear_pending_events();
900         assert_eq!(events.len(), 1);
901         match events[0] {
902                 Event::PaymentSent { ref payment_preimage } => {
903                         assert_eq!(our_payment_preimage, *payment_preimage);
904                 },
905                 _ => panic!("Unexpected event"),
906         }
907
908         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
909         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
910         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
911         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
912         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
913         assert!(node_0_none.is_none());
914
915         assert!(nodes[0].node.list_channels().is_empty());
916
917         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
918         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
919         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
920         assert!(nodes[1].node.list_channels().is_empty());
921         assert!(nodes[2].node.list_channels().is_empty());
922 }
923
924 #[test]
925 fn htlc_fail_async_shutdown() {
926         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
927         let chanmon_cfgs = create_chanmon_cfgs(3);
928         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
929         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
930         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
931         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
932         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
933         let logger = test_utils::TestLogger::new();
934
935         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
936         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
937         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
938         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
939         check_added_monitors!(nodes[0], 1);
940         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
941         assert_eq!(updates.update_add_htlcs.len(), 1);
942         assert!(updates.update_fulfill_htlcs.is_empty());
943         assert!(updates.update_fail_htlcs.is_empty());
944         assert!(updates.update_fail_malformed_htlcs.is_empty());
945         assert!(updates.update_fee.is_none());
946
947         nodes[1].node.close_channel(&chan_1.2).unwrap();
948         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
949         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
950         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
951
952         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
953         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
954         check_added_monitors!(nodes[1], 1);
955         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
956         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
957
958         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
959         assert!(updates_2.update_add_htlcs.is_empty());
960         assert!(updates_2.update_fulfill_htlcs.is_empty());
961         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
962         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
963         assert!(updates_2.update_fee.is_none());
964
965         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
966         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
967
968         expect_payment_failed!(nodes[0], our_payment_hash, false);
969
970         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
971         assert_eq!(msg_events.len(), 2);
972         let node_0_closing_signed = match msg_events[0] {
973                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
974                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
975                         (*msg).clone()
976                 },
977                 _ => panic!("Unexpected event"),
978         };
979         match msg_events[1] {
980                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
981                         assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
982                 },
983                 _ => panic!("Unexpected event"),
984         }
985
986         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
987         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
988         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
989         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
990         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
991         assert!(node_0_none.is_none());
992
993         assert!(nodes[0].node.list_channels().is_empty());
994
995         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
996         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
997         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
998         assert!(nodes[1].node.list_channels().is_empty());
999         assert!(nodes[2].node.list_channels().is_empty());
1000 }
1001
1002 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1003         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1004         // messages delivered prior to disconnect
1005         let chanmon_cfgs = create_chanmon_cfgs(3);
1006         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1007         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1008         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1009         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1010         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1011
1012         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1013
1014         nodes[1].node.close_channel(&chan_1.2).unwrap();
1015         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1016         if recv_count > 0 {
1017                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
1018                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1019                 if recv_count > 1 {
1020                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
1021                 }
1022         }
1023
1024         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1025         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1026
1027         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1028         let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1029         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1030         let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1031
1032         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1033         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1034         assert!(node_1_shutdown == node_1_2nd_shutdown);
1035
1036         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1037         let node_0_2nd_shutdown = if recv_count > 0 {
1038                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1039                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1040                 node_0_2nd_shutdown
1041         } else {
1042                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1043                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1044                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1045         };
1046         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_2nd_shutdown);
1047
1048         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1049         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1050
1051         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1052         check_added_monitors!(nodes[2], 1);
1053         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1054         assert!(updates.update_add_htlcs.is_empty());
1055         assert!(updates.update_fail_htlcs.is_empty());
1056         assert!(updates.update_fail_malformed_htlcs.is_empty());
1057         assert!(updates.update_fee.is_none());
1058         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1059         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1060         check_added_monitors!(nodes[1], 1);
1061         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1062         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1063
1064         assert!(updates_2.update_add_htlcs.is_empty());
1065         assert!(updates_2.update_fail_htlcs.is_empty());
1066         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1067         assert!(updates_2.update_fee.is_none());
1068         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1069         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1070         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1071
1072         let events = nodes[0].node.get_and_clear_pending_events();
1073         assert_eq!(events.len(), 1);
1074         match events[0] {
1075                 Event::PaymentSent { ref payment_preimage } => {
1076                         assert_eq!(our_payment_preimage, *payment_preimage);
1077                 },
1078                 _ => panic!("Unexpected event"),
1079         }
1080
1081         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1082         if recv_count > 0 {
1083                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1084                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1085                 assert!(node_1_closing_signed.is_some());
1086         }
1087
1088         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1089         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1090
1091         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1092         let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1093         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1094         if recv_count == 0 {
1095                 // If all closing_signeds weren't delivered we can just resume where we left off...
1096                 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1097
1098                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1099                 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1100                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1101
1102                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1103                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1104                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1105
1106                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_3rd_shutdown);
1107                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1108
1109                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_3rd_shutdown);
1110                 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1111                 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1112
1113                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1114                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1115                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1116                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1117                 assert!(node_0_none.is_none());
1118         } else {
1119                 // If one node, however, received + responded with an identical closing_signed we end
1120                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1121                 // There isn't really anything better we can do simply, but in the future we might
1122                 // explore storing a set of recently-closed channels that got disconnected during
1123                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1124                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1125                 // transaction.
1126                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1127
1128                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1129                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1130                 assert_eq!(msg_events.len(), 1);
1131                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1132                         match action {
1133                                 &ErrorAction::SendErrorMessage { ref msg } => {
1134                                         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1135                                         assert_eq!(msg.channel_id, chan_1.2);
1136                                 },
1137                                 _ => panic!("Unexpected event!"),
1138                         }
1139                 } else { panic!("Needed SendErrorMessage close"); }
1140
1141                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1142                 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1143                 // closing_signed so we do it ourselves
1144                 check_closed_broadcast!(nodes[0], false);
1145                 check_added_monitors!(nodes[0], 1);
1146         }
1147
1148         assert!(nodes[0].node.list_channels().is_empty());
1149
1150         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1151         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1152         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1153         assert!(nodes[1].node.list_channels().is_empty());
1154         assert!(nodes[2].node.list_channels().is_empty());
1155 }
1156
1157 #[test]
1158 fn test_shutdown_rebroadcast() {
1159         do_test_shutdown_rebroadcast(0);
1160         do_test_shutdown_rebroadcast(1);
1161         do_test_shutdown_rebroadcast(2);
1162 }
1163
1164 #[test]
1165 fn fake_network_test() {
1166         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1167         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1168         let chanmon_cfgs = create_chanmon_cfgs(4);
1169         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1170         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1171         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1172
1173         // Create some initial channels
1174         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1175         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1176         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1177
1178         // Rebalance the network a bit by relaying one payment through all the channels...
1179         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1180         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1181         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1182         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1183
1184         // Send some more payments
1185         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1186         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1187         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1188
1189         // Test failure packets
1190         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1191         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1192
1193         // Add a new channel that skips 3
1194         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1195
1196         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1197         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1198         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1199         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1200         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1201         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1202         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1203
1204         // Do some rebalance loop payments, simultaneously
1205         let mut hops = Vec::with_capacity(3);
1206         hops.push(RouteHop {
1207                 pubkey: nodes[2].node.get_our_node_id(),
1208                 node_features: NodeFeatures::empty(),
1209                 short_channel_id: chan_2.0.contents.short_channel_id,
1210                 channel_features: ChannelFeatures::empty(),
1211                 fee_msat: 0,
1212                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1213         });
1214         hops.push(RouteHop {
1215                 pubkey: nodes[3].node.get_our_node_id(),
1216                 node_features: NodeFeatures::empty(),
1217                 short_channel_id: chan_3.0.contents.short_channel_id,
1218                 channel_features: ChannelFeatures::empty(),
1219                 fee_msat: 0,
1220                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1221         });
1222         hops.push(RouteHop {
1223                 pubkey: nodes[1].node.get_our_node_id(),
1224                 node_features: NodeFeatures::empty(),
1225                 short_channel_id: chan_4.0.contents.short_channel_id,
1226                 channel_features: ChannelFeatures::empty(),
1227                 fee_msat: 1000000,
1228                 cltv_expiry_delta: TEST_FINAL_CLTV,
1229         });
1230         hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1231         hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1232         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1233
1234         let mut hops = Vec::with_capacity(3);
1235         hops.push(RouteHop {
1236                 pubkey: nodes[3].node.get_our_node_id(),
1237                 node_features: NodeFeatures::empty(),
1238                 short_channel_id: chan_4.0.contents.short_channel_id,
1239                 channel_features: ChannelFeatures::empty(),
1240                 fee_msat: 0,
1241                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1242         });
1243         hops.push(RouteHop {
1244                 pubkey: nodes[2].node.get_our_node_id(),
1245                 node_features: NodeFeatures::empty(),
1246                 short_channel_id: chan_3.0.contents.short_channel_id,
1247                 channel_features: ChannelFeatures::empty(),
1248                 fee_msat: 0,
1249                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1250         });
1251         hops.push(RouteHop {
1252                 pubkey: nodes[1].node.get_our_node_id(),
1253                 node_features: NodeFeatures::empty(),
1254                 short_channel_id: chan_2.0.contents.short_channel_id,
1255                 channel_features: ChannelFeatures::empty(),
1256                 fee_msat: 1000000,
1257                 cltv_expiry_delta: TEST_FINAL_CLTV,
1258         });
1259         hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1260         hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1261         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1262
1263         // Claim the rebalances...
1264         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1265         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1266
1267         // Add a duplicate new channel from 2 to 4
1268         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1269
1270         // Send some payments across both channels
1271         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1272         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1273         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1274
1275
1276         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1277         let events = nodes[0].node.get_and_clear_pending_msg_events();
1278         assert_eq!(events.len(), 0);
1279         nodes[0].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap(), 1);
1280
1281         //TODO: Test that routes work again here as we've been notified that the channel is full
1282
1283         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1284         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1285         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1286
1287         // Close down the channels...
1288         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1289         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1290         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1291         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1292         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1293 }
1294
1295 #[test]
1296 fn holding_cell_htlc_counting() {
1297         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1298         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1299         // commitment dance rounds.
1300         let chanmon_cfgs = create_chanmon_cfgs(3);
1301         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1302         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1303         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1304         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1305         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1306         let logger = test_utils::TestLogger::new();
1307
1308         let mut payments = Vec::new();
1309         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1310                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1311                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1312                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1313                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1314                 payments.push((payment_preimage, payment_hash));
1315         }
1316         check_added_monitors!(nodes[1], 1);
1317
1318         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1319         assert_eq!(events.len(), 1);
1320         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1321         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1322
1323         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1324         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1325         // another HTLC.
1326         let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1327         {
1328                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1329                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1330                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1331                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1332                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1333                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1334         }
1335
1336         // This should also be true if we try to forward a payment.
1337         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1338         {
1339                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1340                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1341                 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1342                 check_added_monitors!(nodes[0], 1);
1343         }
1344
1345         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1346         assert_eq!(events.len(), 1);
1347         let payment_event = SendEvent::from_event(events.pop().unwrap());
1348         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1349
1350         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1351         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1352         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1353         // fails), the second will process the resulting failure and fail the HTLC backward.
1354         expect_pending_htlcs_forwardable!(nodes[1]);
1355         expect_pending_htlcs_forwardable!(nodes[1]);
1356         check_added_monitors!(nodes[1], 1);
1357
1358         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1359         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1360         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1361
1362         let events = nodes[0].node.get_and_clear_pending_msg_events();
1363         assert_eq!(events.len(), 1);
1364         match events[0] {
1365                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1366                         assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1367                 },
1368                 _ => panic!("Unexpected event"),
1369         }
1370
1371         expect_payment_failed!(nodes[0], payment_hash_2, false);
1372
1373         // Now forward all the pending HTLCs and claim them back
1374         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1375         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1376         check_added_monitors!(nodes[2], 1);
1377
1378         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1379         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1380         check_added_monitors!(nodes[1], 1);
1381         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1382
1383         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1384         check_added_monitors!(nodes[1], 1);
1385         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1386
1387         for ref update in as_updates.update_add_htlcs.iter() {
1388                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1389         }
1390         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1391         check_added_monitors!(nodes[2], 1);
1392         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1393         check_added_monitors!(nodes[2], 1);
1394         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1395
1396         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1397         check_added_monitors!(nodes[1], 1);
1398         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1399         check_added_monitors!(nodes[1], 1);
1400         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1401
1402         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1403         check_added_monitors!(nodes[2], 1);
1404
1405         expect_pending_htlcs_forwardable!(nodes[2]);
1406
1407         let events = nodes[2].node.get_and_clear_pending_events();
1408         assert_eq!(events.len(), payments.len());
1409         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1410                 match event {
1411                         &Event::PaymentReceived { ref payment_hash, .. } => {
1412                                 assert_eq!(*payment_hash, *hash);
1413                         },
1414                         _ => panic!("Unexpected event"),
1415                 };
1416         }
1417
1418         for (preimage, _) in payments.drain(..) {
1419                 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1420         }
1421
1422         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1423 }
1424
1425 #[test]
1426 fn duplicate_htlc_test() {
1427         // Test that we accept duplicate payment_hash HTLCs across the network and that
1428         // claiming/failing them are all separate and don't affect each other
1429         let chanmon_cfgs = create_chanmon_cfgs(6);
1430         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1431         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1432         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1433
1434         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1435         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1436         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1437         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1438         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1439         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1440
1441         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1442
1443         *nodes[0].network_payment_count.borrow_mut() -= 1;
1444         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1445
1446         *nodes[0].network_payment_count.borrow_mut() -= 1;
1447         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1448
1449         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1450         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1451         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1452 }
1453
1454 #[test]
1455 fn test_duplicate_htlc_different_direction_onchain() {
1456         // Test that ChannelMonitor doesn't generate 2 preimage txn
1457         // when we have 2 HTLCs with same preimage that go across a node
1458         // in opposite directions.
1459         let chanmon_cfgs = create_chanmon_cfgs(2);
1460         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1461         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1462         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1463
1464         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1465         let logger = test_utils::TestLogger::new();
1466
1467         // balancing
1468         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1469
1470         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1471
1472         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1473         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 800_000, TEST_FINAL_CLTV, &logger).unwrap();
1474         send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1475
1476         // Provide preimage to node 0 by claiming payment
1477         nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1478         check_added_monitors!(nodes[0], 1);
1479
1480         // Broadcast node 1 commitment txn
1481         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1482
1483         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1484         let mut has_both_htlcs = 0; // check htlcs match ones committed
1485         for outp in remote_txn[0].output.iter() {
1486                 if outp.value == 800_000 / 1000 {
1487                         has_both_htlcs += 1;
1488                 } else if outp.value == 900_000 / 1000 {
1489                         has_both_htlcs += 1;
1490                 }
1491         }
1492         assert_eq!(has_both_htlcs, 2);
1493
1494         mine_transaction(&nodes[0], &remote_txn[0]);
1495         check_added_monitors!(nodes[0], 1);
1496
1497         // Check we only broadcast 1 timeout tx
1498         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1499         let htlc_pair = if claim_txn[0].output[0].value == 800_000 / 1000 { (claim_txn[0].clone(), claim_txn[1].clone()) } else { (claim_txn[1].clone(), claim_txn[0].clone()) };
1500         assert_eq!(claim_txn.len(), 5);
1501         check_spends!(claim_txn[2], chan_1.3);
1502         check_spends!(claim_txn[3], claim_txn[2]);
1503         assert_eq!(htlc_pair.0.input.len(), 1);
1504         assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1505         check_spends!(htlc_pair.0, remote_txn[0]);
1506         assert_eq!(htlc_pair.1.input.len(), 1);
1507         assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1508         check_spends!(htlc_pair.1, remote_txn[0]);
1509
1510         let events = nodes[0].node.get_and_clear_pending_msg_events();
1511         assert_eq!(events.len(), 2);
1512         for e in events {
1513                 match e {
1514                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1515                         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, .. } } => {
1516                                 assert!(update_add_htlcs.is_empty());
1517                                 assert!(update_fail_htlcs.is_empty());
1518                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1519                                 assert!(update_fail_malformed_htlcs.is_empty());
1520                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1521                         },
1522                         _ => panic!("Unexpected event"),
1523                 }
1524         }
1525 }
1526
1527 #[test]
1528 fn test_basic_channel_reserve() {
1529         let chanmon_cfgs = create_chanmon_cfgs(2);
1530         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1531         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1532         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1533         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1534         let logger = test_utils::TestLogger::new();
1535
1536         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1537         let channel_reserve = chan_stat.channel_reserve_msat;
1538
1539         // The 2* and +1 are for the fee spike reserve.
1540         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1541         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1542         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1543         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1544         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();
1545         let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1546         match err {
1547                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1548                         match &fails[0] {
1549                                 &APIError::ChannelUnavailable{ref err} =>
1550                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1551                                 _ => panic!("Unexpected error variant"),
1552                         }
1553                 },
1554                 _ => panic!("Unexpected error variant"),
1555         }
1556         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1557         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);
1558
1559         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1560 }
1561
1562 #[test]
1563 fn test_fee_spike_violation_fails_htlc() {
1564         let chanmon_cfgs = create_chanmon_cfgs(2);
1565         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1566         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1567         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1568         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1569         let logger = test_utils::TestLogger::new();
1570
1571         macro_rules! get_route_and_payment_hash {
1572                 ($recv_value: expr) => {{
1573                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1574                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1575                         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();
1576                         (route, payment_hash, payment_preimage)
1577                 }}
1578         }
1579
1580         let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1581         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1582         let secp_ctx = Secp256k1::new();
1583         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1584
1585         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1586
1587         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1588         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1589         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1590         let msg = msgs::UpdateAddHTLC {
1591                 channel_id: chan.2,
1592                 htlc_id: 0,
1593                 amount_msat: htlc_msat,
1594                 payment_hash: payment_hash,
1595                 cltv_expiry: htlc_cltv,
1596                 onion_routing_packet: onion_packet,
1597         };
1598
1599         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1600
1601         // Now manually create the commitment_signed message corresponding to the update_add
1602         // nodes[0] just sent. In the code for construction of this message, "local" refers
1603         // to the sender of the message, and "remote" refers to the receiver.
1604
1605         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1606
1607         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1608
1609         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1610         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1611         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point) = {
1612                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1613                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1614                 let chan_signer = local_chan.get_signer();
1615                 let pubkeys = chan_signer.pubkeys();
1616                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1617                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1618                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
1619         };
1620         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point) = {
1621                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1622                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1623                 let chan_signer = remote_chan.get_signer();
1624                 let pubkeys = chan_signer.pubkeys();
1625                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1626                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
1627         };
1628
1629         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1630         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1631                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1632
1633         // Build the remote commitment transaction so we can sign it, and then later use the
1634         // signature for the commitment_signed message.
1635         let local_chan_balance = 1313;
1636
1637         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1638                 offered: false,
1639                 amount_msat: 3460001,
1640                 cltv_expiry: htlc_cltv,
1641                 payment_hash,
1642                 transaction_output_index: Some(1),
1643         };
1644
1645         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1646
1647         let res = {
1648                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1649                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1650                 let local_chan_signer = local_chan.get_signer();
1651                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1652                         commitment_number,
1653                         95000,
1654                         local_chan_balance,
1655                         commit_tx_keys.clone(),
1656                         feerate_per_kw,
1657                         &mut vec![(accepted_htlc_info, ())],
1658                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1659                 );
1660                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1661         };
1662
1663         let commit_signed_msg = msgs::CommitmentSigned {
1664                 channel_id: chan.2,
1665                 signature: res.0,
1666                 htlc_signatures: res.1
1667         };
1668
1669         // Send the commitment_signed message to the nodes[1].
1670         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1671         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1672
1673         // Send the RAA to nodes[1].
1674         let raa_msg = msgs::RevokeAndACK {
1675                 channel_id: chan.2,
1676                 per_commitment_secret: local_secret,
1677                 next_per_commitment_point: next_local_point
1678         };
1679         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1680
1681         let events = nodes[1].node.get_and_clear_pending_msg_events();
1682         assert_eq!(events.len(), 1);
1683         // Make sure the HTLC failed in the way we expect.
1684         match events[0] {
1685                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1686                         assert_eq!(update_fail_htlcs.len(), 1);
1687                         update_fail_htlcs[0].clone()
1688                 },
1689                 _ => panic!("Unexpected event"),
1690         };
1691         nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1692
1693         check_added_monitors!(nodes[1], 2);
1694 }
1695
1696 #[test]
1697 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1698         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1699         // Set the fee rate for the channel very high, to the point where the fundee
1700         // sending any above-dust amount would result in a channel reserve violation.
1701         // In this test we check that we would be prevented from sending an HTLC in
1702         // this situation.
1703         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1704         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1705         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1706         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1707         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1708         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1709         let logger = test_utils::TestLogger::new();
1710
1711         macro_rules! get_route_and_payment_hash {
1712                 ($recv_value: expr) => {{
1713                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1714                         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1715                         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();
1716                         (route, payment_hash, payment_preimage)
1717                 }}
1718         }
1719
1720         let (route, our_payment_hash, _) = get_route_and_payment_hash!(4843000);
1721         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1722                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1723         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1724         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);
1725 }
1726
1727 #[test]
1728 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1729         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1730         // Set the fee rate for the channel very high, to the point where the funder
1731         // receiving 1 update_add_htlc would result in them closing the channel due
1732         // to channel reserve violation. This close could also happen if the fee went
1733         // up a more realistic amount, but many HTLCs were outstanding at the time of
1734         // the update_add_htlc.
1735         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1736         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1737         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1738         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1739         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1740         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1741         let logger = test_utils::TestLogger::new();
1742
1743         macro_rules! get_route_and_payment_hash {
1744                 ($recv_value: expr) => {{
1745                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1746                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1747                         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();
1748                         (route, payment_hash, payment_preimage)
1749                 }}
1750         }
1751
1752         let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1753         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1754         let secp_ctx = Secp256k1::new();
1755         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1756         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1757         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1758         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1759         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1760         let msg = msgs::UpdateAddHTLC {
1761                 channel_id: chan.2,
1762                 htlc_id: 1,
1763                 amount_msat: htlc_msat + 1,
1764                 payment_hash: payment_hash,
1765                 cltv_expiry: htlc_cltv,
1766                 onion_routing_packet: onion_packet,
1767         };
1768
1769         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1770         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1771         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);
1772         assert_eq!(nodes[0].node.list_channels().len(), 0);
1773         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1774         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1775         check_added_monitors!(nodes[0], 1);
1776 }
1777
1778 #[test]
1779 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1780         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1781         // calculating our commitment transaction fee (this was previously broken).
1782         let chanmon_cfgs = create_chanmon_cfgs(2);
1783         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1784         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1785         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1786
1787         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1788         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1789         // transaction fee with 0 HTLCs (183 sats)).
1790         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98817000, InitFeatures::known(), InitFeatures::known());
1791
1792         let dust_amt = 546000; // Dust amount
1793         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1794         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1795         // commitment transaction fee.
1796         let (_, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1797 }
1798
1799 #[test]
1800 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1801         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1802         // calculating our counterparty's commitment transaction fee (this was previously broken).
1803         let chanmon_cfgs = create_chanmon_cfgs(2);
1804         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1805         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1806         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1807         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1808
1809         let payment_amt = 46000; // Dust amount
1810         // In the previous code, these first four payments would succeed.
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         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1817         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1818         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1819         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1820         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1821         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1822
1823         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1824         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1825         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1826         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1827 }
1828
1829 #[test]
1830 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1831         let chanmon_cfgs = create_chanmon_cfgs(3);
1832         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1833         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1834         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1835         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1836         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1837         let logger = test_utils::TestLogger::new();
1838
1839         macro_rules! get_route_and_payment_hash {
1840                 ($recv_value: expr) => {{
1841                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1842                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1843                         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();
1844                         (route, payment_hash, payment_preimage)
1845                 }}
1846         }
1847
1848         let feemsat = 239;
1849         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1850         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1851         let feerate = get_feerate!(nodes[0], chan.2);
1852
1853         // Add a 2* and +1 for the fee spike reserve.
1854         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1855         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;
1856         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1857
1858         // Add a pending HTLC.
1859         let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1860         let payment_event_1 = {
1861                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1862                 check_added_monitors!(nodes[0], 1);
1863
1864                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1865                 assert_eq!(events.len(), 1);
1866                 SendEvent::from_event(events.remove(0))
1867         };
1868         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1869
1870         // Attempt to trigger a channel reserve violation --> payment failure.
1871         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1872         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;
1873         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1874         let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1875
1876         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1877         let secp_ctx = Secp256k1::new();
1878         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1879         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1880         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1881         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1882         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1883         let msg = msgs::UpdateAddHTLC {
1884                 channel_id: chan.2,
1885                 htlc_id: 1,
1886                 amount_msat: htlc_msat + 1,
1887                 payment_hash: our_payment_hash_1,
1888                 cltv_expiry: htlc_cltv,
1889                 onion_routing_packet: onion_packet,
1890         };
1891
1892         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1893         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1894         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1895         assert_eq!(nodes[1].node.list_channels().len(), 1);
1896         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1897         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1898         check_added_monitors!(nodes[1], 1);
1899 }
1900
1901 #[test]
1902 fn test_inbound_outbound_capacity_is_not_zero() {
1903         let chanmon_cfgs = create_chanmon_cfgs(2);
1904         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1905         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1906         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1907         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1908         let channels0 = node_chanmgrs[0].list_channels();
1909         let channels1 = node_chanmgrs[1].list_channels();
1910         assert_eq!(channels0.len(), 1);
1911         assert_eq!(channels1.len(), 1);
1912
1913         assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1914         assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1915
1916         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1917         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1918 }
1919
1920 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1921         (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1922 }
1923
1924 #[test]
1925 fn test_channel_reserve_holding_cell_htlcs() {
1926         let chanmon_cfgs = create_chanmon_cfgs(3);
1927         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1928         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1929         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1930         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1931         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1932         let logger = test_utils::TestLogger::new();
1933
1934         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1935         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1936
1937         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1938         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1939
1940         macro_rules! get_route_and_payment_hash {
1941                 ($recv_value: expr) => {{
1942                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1943                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1944                         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();
1945                         (route, payment_hash, payment_preimage)
1946                 }}
1947         }
1948
1949         macro_rules! expect_forward {
1950                 ($node: expr) => {{
1951                         let mut events = $node.node.get_and_clear_pending_msg_events();
1952                         assert_eq!(events.len(), 1);
1953                         check_added_monitors!($node, 1);
1954                         let payment_event = SendEvent::from_event(events.remove(0));
1955                         payment_event
1956                 }}
1957         }
1958
1959         let feemsat = 239; // somehow we know?
1960         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1961         let feerate = get_feerate!(nodes[0], chan_1.2);
1962
1963         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1964
1965         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1966         {
1967                 let (mut route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0);
1968                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1969                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1970                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1971                         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)));
1972                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1973                 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);
1974         }
1975
1976         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1977         // nodes[0]'s wealth
1978         loop {
1979                 let amt_msat = recv_value_0 + total_fee_msat;
1980                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1981                 // Also, ensure that each payment has enough to be over the dust limit to
1982                 // ensure it'll be included in each commit tx fee calculation.
1983                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1984                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1985                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1986                         break;
1987                 }
1988                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1989
1990                 let (stat01_, stat11_, stat12_, stat22_) = (
1991                         get_channel_value_stat!(nodes[0], chan_1.2),
1992                         get_channel_value_stat!(nodes[1], chan_1.2),
1993                         get_channel_value_stat!(nodes[1], chan_2.2),
1994                         get_channel_value_stat!(nodes[2], chan_2.2),
1995                 );
1996
1997                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1998                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1999                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
2000                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
2001                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
2002         }
2003
2004         // adding pending output.
2005         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
2006         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2007         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2008         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2009         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2010         // cases where 1 msat over X amount will cause a payment failure, but anything less than
2011         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2012         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2013         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2014         // policy.
2015         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2016         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2017         let amt_msat_1 = recv_value_1 + total_fee_msat;
2018
2019         let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2020         let payment_event_1 = {
2021                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
2022                 check_added_monitors!(nodes[0], 1);
2023
2024                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2025                 assert_eq!(events.len(), 1);
2026                 SendEvent::from_event(events.remove(0))
2027         };
2028         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2029
2030         // channel reserve test with htlc pending output > 0
2031         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2032         {
2033                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2034                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2035                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2036                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2037         }
2038
2039         // split the rest to test holding cell
2040         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2041         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2042         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2043         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2044         {
2045                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2046                 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);
2047         }
2048
2049         // now see if they go through on both sides
2050         let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2051         // but this will stuck in the holding cell
2052         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2053         check_added_monitors!(nodes[0], 0);
2054         let events = nodes[0].node.get_and_clear_pending_events();
2055         assert_eq!(events.len(), 0);
2056
2057         // test with outbound holding cell amount > 0
2058         {
2059                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2060                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2061                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2062                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2063                 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);
2064         }
2065
2066         let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2067         // this will also stuck in the holding cell
2068         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2069         check_added_monitors!(nodes[0], 0);
2070         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2071         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2072
2073         // flush the pending htlc
2074         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2075         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2076         check_added_monitors!(nodes[1], 1);
2077
2078         // the pending htlc should be promoted to committed
2079         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2080         check_added_monitors!(nodes[0], 1);
2081         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2082
2083         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2084         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2085         // No commitment_signed so get_event_msg's assert(len == 1) passes
2086         check_added_monitors!(nodes[0], 1);
2087
2088         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2089         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2090         check_added_monitors!(nodes[1], 1);
2091
2092         expect_pending_htlcs_forwardable!(nodes[1]);
2093
2094         let ref payment_event_11 = expect_forward!(nodes[1]);
2095         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2096         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2097
2098         expect_pending_htlcs_forwardable!(nodes[2]);
2099         expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2100
2101         // flush the htlcs in the holding cell
2102         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2103         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2104         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2105         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2106         expect_pending_htlcs_forwardable!(nodes[1]);
2107
2108         let ref payment_event_3 = expect_forward!(nodes[1]);
2109         assert_eq!(payment_event_3.msgs.len(), 2);
2110         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2111         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2112
2113         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2114         expect_pending_htlcs_forwardable!(nodes[2]);
2115
2116         let events = nodes[2].node.get_and_clear_pending_events();
2117         assert_eq!(events.len(), 2);
2118         match events[0] {
2119                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2120                         assert_eq!(our_payment_hash_21, *payment_hash);
2121                         assert_eq!(*payment_secret, None);
2122                         assert_eq!(recv_value_21, amt);
2123                 },
2124                 _ => panic!("Unexpected event"),
2125         }
2126         match events[1] {
2127                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2128                         assert_eq!(our_payment_hash_22, *payment_hash);
2129                         assert_eq!(None, *payment_secret);
2130                         assert_eq!(recv_value_22, amt);
2131                 },
2132                 _ => panic!("Unexpected event"),
2133         }
2134
2135         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2136         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2137         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2138
2139         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2140         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2141         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2142
2143         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2144         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);
2145         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2146         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2147         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2148
2149         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2150         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2151 }
2152
2153 #[test]
2154 fn channel_reserve_in_flight_removes() {
2155         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2156         // can send to its counterparty, but due to update ordering, the other side may not yet have
2157         // considered those HTLCs fully removed.
2158         // This tests that we don't count HTLCs which will not be included in the next remote
2159         // commitment transaction towards the reserve value (as it implies no commitment transaction
2160         // will be generated which violates the remote reserve value).
2161         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2162         // To test this we:
2163         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2164         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2165         //    you only consider the value of the first HTLC, it may not),
2166         //  * start routing a third HTLC from A to B,
2167         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2168         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2169         //  * deliver the first fulfill from B
2170         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2171         //    claim,
2172         //  * deliver A's response CS and RAA.
2173         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2174         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2175         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2176         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2177         let chanmon_cfgs = create_chanmon_cfgs(2);
2178         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2179         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2180         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2181         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2182         let logger = test_utils::TestLogger::new();
2183
2184         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2185         // Route the first two HTLCs.
2186         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2187         let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2188
2189         // Start routing the third HTLC (this is just used to get everyone in the right state).
2190         let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2191         let send_1 = {
2192                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2193                 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();
2194                 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2195                 check_added_monitors!(nodes[0], 1);
2196                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2197                 assert_eq!(events.len(), 1);
2198                 SendEvent::from_event(events.remove(0))
2199         };
2200
2201         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2202         // initial fulfill/CS.
2203         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2204         check_added_monitors!(nodes[1], 1);
2205         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2206
2207         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2208         // remove the second HTLC when we send the HTLC back from B to A.
2209         assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2210         check_added_monitors!(nodes[1], 1);
2211         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2212
2213         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2214         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2215         check_added_monitors!(nodes[0], 1);
2216         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2217         expect_payment_sent!(nodes[0], payment_preimage_1);
2218
2219         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2220         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2221         check_added_monitors!(nodes[1], 1);
2222         // B is already AwaitingRAA, so cant generate a CS here
2223         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2224
2225         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2226         check_added_monitors!(nodes[1], 1);
2227         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2228
2229         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2230         check_added_monitors!(nodes[0], 1);
2231         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2232
2233         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2234         check_added_monitors!(nodes[1], 1);
2235         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2236
2237         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2238         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2239         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2240         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2241         // on-chain as necessary).
2242         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2243         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2244         check_added_monitors!(nodes[0], 1);
2245         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2246         expect_payment_sent!(nodes[0], payment_preimage_2);
2247
2248         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2249         check_added_monitors!(nodes[1], 1);
2250         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2251
2252         expect_pending_htlcs_forwardable!(nodes[1]);
2253         expect_payment_received!(nodes[1], payment_hash_3, 100000);
2254
2255         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2256         // resolve the second HTLC from A's point of view.
2257         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2258         check_added_monitors!(nodes[0], 1);
2259         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2260
2261         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2262         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2263         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2264         let send_2 = {
2265                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2266                 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();
2267                 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2268                 check_added_monitors!(nodes[1], 1);
2269                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2270                 assert_eq!(events.len(), 1);
2271                 SendEvent::from_event(events.remove(0))
2272         };
2273
2274         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2275         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2276         check_added_monitors!(nodes[0], 1);
2277         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2278
2279         // Now just resolve all the outstanding messages/HTLCs for completeness...
2280
2281         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2282         check_added_monitors!(nodes[1], 1);
2283         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2284
2285         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2286         check_added_monitors!(nodes[1], 1);
2287
2288         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2289         check_added_monitors!(nodes[0], 1);
2290         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2291
2292         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2293         check_added_monitors!(nodes[1], 1);
2294         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2295
2296         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2297         check_added_monitors!(nodes[0], 1);
2298
2299         expect_pending_htlcs_forwardable!(nodes[0]);
2300         expect_payment_received!(nodes[0], payment_hash_4, 10000);
2301
2302         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2303         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2304 }
2305
2306 #[test]
2307 fn channel_monitor_network_test() {
2308         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2309         // tests that ChannelMonitor is able to recover from various states.
2310         let chanmon_cfgs = create_chanmon_cfgs(5);
2311         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2312         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2313         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2314
2315         // Create some initial channels
2316         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2317         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2318         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2319         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2320
2321         // Make sure all nodes are at the same starting height
2322         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2323         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2324         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2325         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2326         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2327
2328         // Rebalance the network a bit by relaying one payment through all the channels...
2329         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2330         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2331         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2332         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2333
2334         // Simple case with no pending HTLCs:
2335         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2336         check_added_monitors!(nodes[1], 1);
2337         {
2338                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2339                 assert_eq!(node_txn.len(), 1);
2340                 mine_transaction(&nodes[0], &node_txn[0]);
2341                 check_added_monitors!(nodes[0], 1);
2342                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2343         }
2344         get_announce_close_broadcast_events(&nodes, 0, 1);
2345         assert_eq!(nodes[0].node.list_channels().len(), 0);
2346         assert_eq!(nodes[1].node.list_channels().len(), 1);
2347
2348         // One pending HTLC is discarded by the force-close:
2349         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2350
2351         // Simple case of one pending HTLC to HTLC-Timeout
2352         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2353         check_added_monitors!(nodes[1], 1);
2354         {
2355                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2356                 mine_transaction(&nodes[2], &node_txn[0]);
2357                 check_added_monitors!(nodes[2], 1);
2358                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2359         }
2360         get_announce_close_broadcast_events(&nodes, 1, 2);
2361         assert_eq!(nodes[1].node.list_channels().len(), 0);
2362         assert_eq!(nodes[2].node.list_channels().len(), 1);
2363
2364         macro_rules! claim_funds {
2365                 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2366                         {
2367                                 assert!($node.node.claim_funds($preimage, &None, $amount));
2368                                 check_added_monitors!($node, 1);
2369
2370                                 let events = $node.node.get_and_clear_pending_msg_events();
2371                                 assert_eq!(events.len(), 1);
2372                                 match events[0] {
2373                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2374                                                 assert!(update_add_htlcs.is_empty());
2375                                                 assert!(update_fail_htlcs.is_empty());
2376                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2377                                         },
2378                                         _ => panic!("Unexpected event"),
2379                                 };
2380                         }
2381                 }
2382         }
2383
2384         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2385         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2386         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2387         check_added_monitors!(nodes[2], 1);
2388         let node2_commitment_txid;
2389         {
2390                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2391                 node2_commitment_txid = node_txn[0].txid();
2392
2393                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2394                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2395                 mine_transaction(&nodes[3], &node_txn[0]);
2396                 check_added_monitors!(nodes[3], 1);
2397                 check_preimage_claim(&nodes[3], &node_txn);
2398         }
2399         get_announce_close_broadcast_events(&nodes, 2, 3);
2400         assert_eq!(nodes[2].node.list_channels().len(), 0);
2401         assert_eq!(nodes[3].node.list_channels().len(), 1);
2402
2403         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2404         // confusing us in the following tests.
2405         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().remove(&OutPoint { txid: chan_3.3.txid(), index: 0 }).unwrap();
2406
2407         // One pending HTLC to time out:
2408         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2409         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2410         // buffer space).
2411
2412         let (close_chan_update_1, close_chan_update_2) = {
2413                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2414                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2415                 assert_eq!(events.len(), 1);
2416                 let close_chan_update_1 = match events[0] {
2417                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2418                                 msg.clone()
2419                         },
2420                         _ => panic!("Unexpected event"),
2421                 };
2422                 check_added_monitors!(nodes[3], 1);
2423
2424                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2425                 {
2426                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2427                         node_txn.retain(|tx| {
2428                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2429                                         false
2430                                 } else { true }
2431                         });
2432                 }
2433
2434                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2435
2436                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2437                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2438
2439                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2440                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2441                 assert_eq!(events.len(), 1);
2442                 let close_chan_update_2 = match events[0] {
2443                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2444                                 msg.clone()
2445                         },
2446                         _ => panic!("Unexpected event"),
2447                 };
2448                 check_added_monitors!(nodes[4], 1);
2449                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2450
2451                 mine_transaction(&nodes[4], &node_txn[0]);
2452                 check_preimage_claim(&nodes[4], &node_txn);
2453                 (close_chan_update_1, close_chan_update_2)
2454         };
2455         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2456         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2457         assert_eq!(nodes[3].node.list_channels().len(), 0);
2458         assert_eq!(nodes[4].node.list_channels().len(), 0);
2459
2460         nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().insert(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon);
2461 }
2462
2463 #[test]
2464 fn test_justice_tx() {
2465         // Test justice txn built on revoked HTLC-Success tx, against both sides
2466         let mut alice_config = UserConfig::default();
2467         alice_config.channel_options.announced_channel = true;
2468         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2469         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2470         let mut bob_config = UserConfig::default();
2471         bob_config.channel_options.announced_channel = true;
2472         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2473         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2474         let user_cfgs = [Some(alice_config), Some(bob_config)];
2475         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2476         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2477         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2478         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2479         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2480         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2481         // Create some new channels:
2482         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2483
2484         // A pending HTLC which will be revoked:
2485         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2486         // Get the will-be-revoked local txn from nodes[0]
2487         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2488         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2489         assert_eq!(revoked_local_txn[0].input.len(), 1);
2490         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2491         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2492         assert_eq!(revoked_local_txn[1].input.len(), 1);
2493         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2494         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2495         // Revoke the old state
2496         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2497
2498         {
2499                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2500                 {
2501                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2502                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2503                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2504
2505                         check_spends!(node_txn[0], revoked_local_txn[0]);
2506                         node_txn.swap_remove(0);
2507                         node_txn.truncate(1);
2508                 }
2509                 check_added_monitors!(nodes[1], 1);
2510                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2511
2512                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2513                 // Verify broadcast of revoked HTLC-timeout
2514                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2515                 check_added_monitors!(nodes[0], 1);
2516                 // Broadcast revoked HTLC-timeout on node 1
2517                 mine_transaction(&nodes[1], &node_txn[1]);
2518                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2519         }
2520         get_announce_close_broadcast_events(&nodes, 0, 1);
2521
2522         assert_eq!(nodes[0].node.list_channels().len(), 0);
2523         assert_eq!(nodes[1].node.list_channels().len(), 0);
2524
2525         // We test justice_tx build by A on B's revoked HTLC-Success tx
2526         // Create some new channels:
2527         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2528         {
2529                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2530                 node_txn.clear();
2531         }
2532
2533         // A pending HTLC which will be revoked:
2534         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2535         // Get the will-be-revoked local txn from B
2536         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2537         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2538         assert_eq!(revoked_local_txn[0].input.len(), 1);
2539         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2540         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2541         // Revoke the old state
2542         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2543         {
2544                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2545                 {
2546                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2547                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2548                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2549
2550                         check_spends!(node_txn[0], revoked_local_txn[0]);
2551                         node_txn.swap_remove(0);
2552                 }
2553                 check_added_monitors!(nodes[0], 1);
2554                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2555
2556                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2557                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2558                 check_added_monitors!(nodes[1], 1);
2559                 mine_transaction(&nodes[0], &node_txn[1]);
2560                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2561         }
2562         get_announce_close_broadcast_events(&nodes, 0, 1);
2563         assert_eq!(nodes[0].node.list_channels().len(), 0);
2564         assert_eq!(nodes[1].node.list_channels().len(), 0);
2565 }
2566
2567 #[test]
2568 fn revoked_output_claim() {
2569         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2570         // transaction is broadcast by its counterparty
2571         let chanmon_cfgs = create_chanmon_cfgs(2);
2572         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2573         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2574         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2575         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2576         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2577         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2578         assert_eq!(revoked_local_txn.len(), 1);
2579         // Only output is the full channel value back to nodes[0]:
2580         assert_eq!(revoked_local_txn[0].output.len(), 1);
2581         // Send a payment through, updating everyone's latest commitment txn
2582         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2583
2584         // Inform nodes[1] that nodes[0] broadcast a stale tx
2585         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2586         check_added_monitors!(nodes[1], 1);
2587         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2588         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2589
2590         check_spends!(node_txn[0], revoked_local_txn[0]);
2591         check_spends!(node_txn[1], chan_1.3);
2592
2593         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2594         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2595         get_announce_close_broadcast_events(&nodes, 0, 1);
2596         check_added_monitors!(nodes[0], 1)
2597 }
2598
2599 #[test]
2600 fn claim_htlc_outputs_shared_tx() {
2601         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2602         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2603         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2604         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2605         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2606         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2607
2608         // Create some new channel:
2609         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2610
2611         // Rebalance the network to generate htlc in the two directions
2612         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2613         // 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
2614         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2615         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2616
2617         // Get the will-be-revoked local txn from node[0]
2618         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2619         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2620         assert_eq!(revoked_local_txn[0].input.len(), 1);
2621         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2622         assert_eq!(revoked_local_txn[1].input.len(), 1);
2623         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2624         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2625         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2626
2627         //Revoke the old state
2628         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2629
2630         {
2631                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2632                 check_added_monitors!(nodes[0], 1);
2633                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2634                 check_added_monitors!(nodes[1], 1);
2635                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2636                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2637
2638                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2639                 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2640
2641                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2642                 check_spends!(node_txn[0], revoked_local_txn[0]);
2643
2644                 let mut witness_lens = BTreeSet::new();
2645                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2646                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2647                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2648                 assert_eq!(witness_lens.len(), 3);
2649                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2650                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2651                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2652
2653                 // Next nodes[1] broadcasts its current local tx state:
2654                 assert_eq!(node_txn[1].input.len(), 1);
2655                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2656
2657                 assert_eq!(node_txn[2].input.len(), 1);
2658                 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2659                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2660                 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2661                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2662                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2663         }
2664         get_announce_close_broadcast_events(&nodes, 0, 1);
2665         assert_eq!(nodes[0].node.list_channels().len(), 0);
2666         assert_eq!(nodes[1].node.list_channels().len(), 0);
2667 }
2668
2669 #[test]
2670 fn claim_htlc_outputs_single_tx() {
2671         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2672         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2673         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2674         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2675         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2676         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2677
2678         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2679
2680         // Rebalance the network to generate htlc in the two directions
2681         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2682         // 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
2683         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2684         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2685         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2686
2687         // Get the will-be-revoked local txn from node[0]
2688         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2689
2690         //Revoke the old state
2691         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2692
2693         {
2694                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2695                 check_added_monitors!(nodes[0], 1);
2696                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2697                 check_added_monitors!(nodes[1], 1);
2698                 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2699
2700                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2701                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2702
2703                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2704                 assert_eq!(node_txn.len(), 9);
2705                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2706                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2707                 // 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)
2708                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2709
2710                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2711                 assert_eq!(node_txn[0].input.len(), 1);
2712                 check_spends!(node_txn[0], chan_1.3);
2713                 assert_eq!(node_txn[1].input.len(), 1);
2714                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2715                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2716                 check_spends!(node_txn[1], node_txn[0]);
2717
2718                 // Justice transactions are indices 1-2-4
2719                 assert_eq!(node_txn[2].input.len(), 1);
2720                 assert_eq!(node_txn[3].input.len(), 1);
2721                 assert_eq!(node_txn[4].input.len(), 1);
2722
2723                 check_spends!(node_txn[2], revoked_local_txn[0]);
2724                 check_spends!(node_txn[3], revoked_local_txn[0]);
2725                 check_spends!(node_txn[4], revoked_local_txn[0]);
2726
2727                 let mut witness_lens = BTreeSet::new();
2728                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2729                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2730                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2731                 assert_eq!(witness_lens.len(), 3);
2732                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2733                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2734                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2735         }
2736         get_announce_close_broadcast_events(&nodes, 0, 1);
2737         assert_eq!(nodes[0].node.list_channels().len(), 0);
2738         assert_eq!(nodes[1].node.list_channels().len(), 0);
2739 }
2740
2741 #[test]
2742 fn test_htlc_on_chain_success() {
2743         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2744         // the preimage backward accordingly. So here we test that ChannelManager is
2745         // broadcasting the right event to other nodes in payment path.
2746         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2747         // A --------------------> B ----------------------> C (preimage)
2748         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2749         // commitment transaction was broadcast.
2750         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2751         // towards B.
2752         // B should be able to claim via preimage if A then broadcasts its local tx.
2753         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2754         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2755         // PaymentSent event).
2756
2757         let chanmon_cfgs = create_chanmon_cfgs(3);
2758         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2759         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2760         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2761
2762         // Create some initial channels
2763         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2764         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2765
2766         // Rebalance the network a bit by relaying one payment through all the channels...
2767         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2768         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2769
2770         let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2771         let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2772
2773         // Broadcast legit commitment tx from C on B's chain
2774         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2775         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2776         assert_eq!(commitment_tx.len(), 1);
2777         check_spends!(commitment_tx[0], chan_2.3);
2778         nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2779         nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2780         check_added_monitors!(nodes[2], 2);
2781         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2782         assert!(updates.update_add_htlcs.is_empty());
2783         assert!(updates.update_fail_htlcs.is_empty());
2784         assert!(updates.update_fail_malformed_htlcs.is_empty());
2785         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2786
2787         mine_transaction(&nodes[2], &commitment_tx[0]);
2788         check_closed_broadcast!(nodes[2], false);
2789         check_added_monitors!(nodes[2], 1);
2790         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)
2791         assert_eq!(node_txn.len(), 5);
2792         assert_eq!(node_txn[0], node_txn[3]);
2793         assert_eq!(node_txn[1], node_txn[4]);
2794         assert_eq!(node_txn[2], commitment_tx[0]);
2795         check_spends!(node_txn[0], commitment_tx[0]);
2796         check_spends!(node_txn[1], commitment_tx[0]);
2797         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2798         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2799         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2800         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2801         assert_eq!(node_txn[0].lock_time, 0);
2802         assert_eq!(node_txn[1].lock_time, 0);
2803
2804         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2805         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2806         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2807         {
2808                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2809                 assert_eq!(added_monitors.len(), 1);
2810                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2811                 added_monitors.clear();
2812         }
2813         let events = nodes[1].node.get_and_clear_pending_msg_events();
2814         {
2815                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2816                 assert_eq!(added_monitors.len(), 2);
2817                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2818                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2819                 added_monitors.clear();
2820         }
2821         assert_eq!(events.len(), 2);
2822         match events[0] {
2823                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2824                 _ => panic!("Unexpected event"),
2825         }
2826         match events[1] {
2827                 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, .. } } => {
2828                         assert!(update_add_htlcs.is_empty());
2829                         assert!(update_fail_htlcs.is_empty());
2830                         assert_eq!(update_fulfill_htlcs.len(), 1);
2831                         assert!(update_fail_malformed_htlcs.is_empty());
2832                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2833                 },
2834                 _ => panic!("Unexpected event"),
2835         };
2836         macro_rules! check_tx_local_broadcast {
2837                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2838                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2839                         assert_eq!(node_txn.len(), 5);
2840                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2841                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2842                         check_spends!(node_txn[0], $commitment_tx);
2843                         check_spends!(node_txn[1], $commitment_tx);
2844                         assert_ne!(node_txn[0].lock_time, 0);
2845                         assert_ne!(node_txn[1].lock_time, 0);
2846                         if $htlc_offered {
2847                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2848                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2849                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2850                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2851                         } else {
2852                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2853                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2854                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2855                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2856                         }
2857                         check_spends!(node_txn[2], $chan_tx);
2858                         check_spends!(node_txn[3], node_txn[2]);
2859                         check_spends!(node_txn[4], node_txn[2]);
2860                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2861                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2862                         assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2863                         assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2864                         assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2865                         assert_ne!(node_txn[3].lock_time, 0);
2866                         assert_ne!(node_txn[4].lock_time, 0);
2867                         node_txn.clear();
2868                 } }
2869         }
2870         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2871         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2872         // timeout-claim of the output that nodes[2] just claimed via success.
2873         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2874
2875         // Broadcast legit commitment tx from A on B's chain
2876         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2877         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2878         check_spends!(commitment_tx[0], chan_1.3);
2879         mine_transaction(&nodes[1], &commitment_tx[0]);
2880         check_closed_broadcast!(nodes[1], false);
2881         check_added_monitors!(nodes[1], 1);
2882         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2883         assert_eq!(node_txn.len(), 4);
2884         check_spends!(node_txn[0], commitment_tx[0]);
2885         assert_eq!(node_txn[0].input.len(), 2);
2886         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2887         assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2888         assert_eq!(node_txn[0].lock_time, 0);
2889         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2890         check_spends!(node_txn[1], chan_1.3);
2891         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2892         check_spends!(node_txn[2], node_txn[1]);
2893         check_spends!(node_txn[3], node_txn[1]);
2894         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2895         // we already checked the same situation with A.
2896
2897         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2898         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2899         connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] });
2900         check_closed_broadcast!(nodes[0], false);
2901         check_added_monitors!(nodes[0], 1);
2902         let events = nodes[0].node.get_and_clear_pending_events();
2903         assert_eq!(events.len(), 2);
2904         let mut first_claimed = false;
2905         for event in events {
2906                 match event {
2907                         Event::PaymentSent { payment_preimage } => {
2908                                 if payment_preimage == our_payment_preimage {
2909                                         assert!(!first_claimed);
2910                                         first_claimed = true;
2911                                 } else {
2912                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2913                                 }
2914                         },
2915                         _ => panic!("Unexpected event"),
2916                 }
2917         }
2918         check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2919 }
2920
2921 #[test]
2922 fn test_htlc_on_chain_timeout() {
2923         // Test that in case of a unilateral close onchain, we detect the state of output and
2924         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2925         // broadcasting the right event to other nodes in payment path.
2926         // A ------------------> B ----------------------> C (timeout)
2927         //    B's commitment tx                 C's commitment tx
2928         //            \                                  \
2929         //         B's HTLC timeout tx               B's timeout tx
2930
2931         let chanmon_cfgs = create_chanmon_cfgs(3);
2932         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2933         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2934         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2935
2936         // Create some intial channels
2937         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2938         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2939
2940         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2941         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2942         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2943
2944         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2945
2946         // Broadcast legit commitment tx from C on B's chain
2947         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2948         check_spends!(commitment_tx[0], chan_2.3);
2949         nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2950         check_added_monitors!(nodes[2], 0);
2951         expect_pending_htlcs_forwardable!(nodes[2]);
2952         check_added_monitors!(nodes[2], 1);
2953
2954         let events = nodes[2].node.get_and_clear_pending_msg_events();
2955         assert_eq!(events.len(), 1);
2956         match events[0] {
2957                 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, .. } } => {
2958                         assert!(update_add_htlcs.is_empty());
2959                         assert!(!update_fail_htlcs.is_empty());
2960                         assert!(update_fulfill_htlcs.is_empty());
2961                         assert!(update_fail_malformed_htlcs.is_empty());
2962                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2963                 },
2964                 _ => panic!("Unexpected event"),
2965         };
2966         mine_transaction(&nodes[2], &commitment_tx[0]);
2967         check_closed_broadcast!(nodes[2], false);
2968         check_added_monitors!(nodes[2], 1);
2969         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2970         assert_eq!(node_txn.len(), 1);
2971         check_spends!(node_txn[0], chan_2.3);
2972         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2973
2974         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2975         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2976         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2977         mine_transaction(&nodes[1], &commitment_tx[0]);
2978         let timeout_tx;
2979         {
2980                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2981                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2982                 assert_eq!(node_txn[0], node_txn[3]);
2983                 assert_eq!(node_txn[1], node_txn[4]);
2984
2985                 check_spends!(node_txn[2], commitment_tx[0]);
2986                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2987
2988                 check_spends!(node_txn[0], chan_2.3);
2989                 check_spends!(node_txn[1], node_txn[0]);
2990                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2991                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2992
2993                 timeout_tx = node_txn[2].clone();
2994                 node_txn.clear();
2995         }
2996
2997         mine_transaction(&nodes[1], &timeout_tx);
2998         check_added_monitors!(nodes[1], 1);
2999         check_closed_broadcast!(nodes[1], false);
3000         {
3001                 // B will rebroadcast a fee-bumped timeout transaction here.
3002                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3003                 assert_eq!(node_txn.len(), 1);
3004                 check_spends!(node_txn[0], commitment_tx[0]);
3005         }
3006
3007         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3008         {
3009                 // B will rebroadcast its own holder commitment transaction here...just because
3010                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3011                 assert_eq!(node_txn.len(), 1);
3012                 check_spends!(node_txn[0], chan_2.3);
3013         }
3014
3015         expect_pending_htlcs_forwardable!(nodes[1]);
3016         check_added_monitors!(nodes[1], 1);
3017         let events = nodes[1].node.get_and_clear_pending_msg_events();
3018         assert_eq!(events.len(), 1);
3019         match events[0] {
3020                 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, .. } } => {
3021                         assert!(update_add_htlcs.is_empty());
3022                         assert!(!update_fail_htlcs.is_empty());
3023                         assert!(update_fulfill_htlcs.is_empty());
3024                         assert!(update_fail_malformed_htlcs.is_empty());
3025                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3026                 },
3027                 _ => panic!("Unexpected event"),
3028         };
3029
3030         // Broadcast legit commitment tx from B on A's chain
3031         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3032         check_spends!(commitment_tx[0], chan_1.3);
3033
3034         mine_transaction(&nodes[0], &commitment_tx[0]);
3035
3036         check_closed_broadcast!(nodes[0], false);
3037         check_added_monitors!(nodes[0], 1);
3038         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3039         assert_eq!(node_txn.len(), 3);
3040         check_spends!(node_txn[0], commitment_tx[0]);
3041         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3042         check_spends!(node_txn[1], chan_1.3);
3043         check_spends!(node_txn[2], node_txn[1]);
3044         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3045         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3046 }
3047
3048 #[test]
3049 fn test_simple_commitment_revoked_fail_backward() {
3050         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3051         // and fail backward accordingly.
3052
3053         let chanmon_cfgs = create_chanmon_cfgs(3);
3054         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3055         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3056         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3057
3058         // Create some initial channels
3059         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3060         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3061
3062         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3063         // Get the will-be-revoked local txn from nodes[2]
3064         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3065         // Revoke the old state
3066         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3067
3068         let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3069
3070         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3071         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3072         check_added_monitors!(nodes[1], 1);
3073         check_closed_broadcast!(nodes[1], false);
3074
3075         expect_pending_htlcs_forwardable!(nodes[1]);
3076         check_added_monitors!(nodes[1], 1);
3077         let events = nodes[1].node.get_and_clear_pending_msg_events();
3078         assert_eq!(events.len(), 1);
3079         match events[0] {
3080                 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, .. } } => {
3081                         assert!(update_add_htlcs.is_empty());
3082                         assert_eq!(update_fail_htlcs.len(), 1);
3083                         assert!(update_fulfill_htlcs.is_empty());
3084                         assert!(update_fail_malformed_htlcs.is_empty());
3085                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3086
3087                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3088                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3089
3090                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3091                         assert_eq!(events.len(), 1);
3092                         match events[0] {
3093                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3094                                 _ => panic!("Unexpected event"),
3095                         }
3096                         expect_payment_failed!(nodes[0], payment_hash, false);
3097                 },
3098                 _ => panic!("Unexpected event"),
3099         }
3100 }
3101
3102 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3103         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3104         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3105         // commitment transaction anymore.
3106         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3107         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3108         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3109         // technically disallowed and we should probably handle it reasonably.
3110         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3111         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3112         // transactions:
3113         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3114         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3115         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3116         //   and once they revoke the previous commitment transaction (allowing us to send a new
3117         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3118         let chanmon_cfgs = create_chanmon_cfgs(3);
3119         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3120         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3121         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3122
3123         // Create some initial channels
3124         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3125         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3126
3127         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3128         // Get the will-be-revoked local txn from nodes[2]
3129         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3130         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3131         // Revoke the old state
3132         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3133
3134         let value = if use_dust {
3135                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3136                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3137                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3138         } else { 3000000 };
3139
3140         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3141         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3142         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3143
3144         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3145         expect_pending_htlcs_forwardable!(nodes[2]);
3146         check_added_monitors!(nodes[2], 1);
3147         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3148         assert!(updates.update_add_htlcs.is_empty());
3149         assert!(updates.update_fulfill_htlcs.is_empty());
3150         assert!(updates.update_fail_malformed_htlcs.is_empty());
3151         assert_eq!(updates.update_fail_htlcs.len(), 1);
3152         assert!(updates.update_fee.is_none());
3153         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3154         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3155         // Drop the last RAA from 3 -> 2
3156
3157         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3158         expect_pending_htlcs_forwardable!(nodes[2]);
3159         check_added_monitors!(nodes[2], 1);
3160         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3161         assert!(updates.update_add_htlcs.is_empty());
3162         assert!(updates.update_fulfill_htlcs.is_empty());
3163         assert!(updates.update_fail_malformed_htlcs.is_empty());
3164         assert_eq!(updates.update_fail_htlcs.len(), 1);
3165         assert!(updates.update_fee.is_none());
3166         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3167         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3168         check_added_monitors!(nodes[1], 1);
3169         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3170         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3171         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3172         check_added_monitors!(nodes[2], 1);
3173
3174         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3175         expect_pending_htlcs_forwardable!(nodes[2]);
3176         check_added_monitors!(nodes[2], 1);
3177         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3178         assert!(updates.update_add_htlcs.is_empty());
3179         assert!(updates.update_fulfill_htlcs.is_empty());
3180         assert!(updates.update_fail_malformed_htlcs.is_empty());
3181         assert_eq!(updates.update_fail_htlcs.len(), 1);
3182         assert!(updates.update_fee.is_none());
3183         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3184         // At this point first_payment_hash has dropped out of the latest two commitment
3185         // transactions that nodes[1] is tracking...
3186         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3187         check_added_monitors!(nodes[1], 1);
3188         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3189         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3190         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3191         check_added_monitors!(nodes[2], 1);
3192
3193         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3194         // on nodes[2]'s RAA.
3195         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3196         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3197         let logger = test_utils::TestLogger::new();
3198         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();
3199         nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3200         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3201         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3202         check_added_monitors!(nodes[1], 0);
3203
3204         if deliver_bs_raa {
3205                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3206                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3207                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3208                 check_added_monitors!(nodes[1], 1);
3209                 let events = nodes[1].node.get_and_clear_pending_events();
3210                 assert_eq!(events.len(), 1);
3211                 match events[0] {
3212                         Event::PendingHTLCsForwardable { .. } => { },
3213                         _ => panic!("Unexpected event"),
3214                 };
3215                 // Deliberately don't process the pending fail-back so they all fail back at once after
3216                 // block connection just like the !deliver_bs_raa case
3217         }
3218
3219         let mut failed_htlcs = HashSet::new();
3220         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3221
3222         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3223         check_added_monitors!(nodes[1], 1);
3224         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3225
3226         let events = nodes[1].node.get_and_clear_pending_events();
3227         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3228         match events[0] {
3229                 Event::PaymentFailed { ref payment_hash, .. } => {
3230                         assert_eq!(*payment_hash, fourth_payment_hash);
3231                 },
3232                 _ => panic!("Unexpected event"),
3233         }
3234         if !deliver_bs_raa {
3235                 match events[1] {
3236                         Event::PendingHTLCsForwardable { .. } => { },
3237                         _ => panic!("Unexpected event"),
3238                 };
3239         }
3240         nodes[1].node.process_pending_htlc_forwards();
3241         check_added_monitors!(nodes[1], 1);
3242
3243         let events = nodes[1].node.get_and_clear_pending_msg_events();
3244         assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3245         match events[if deliver_bs_raa { 1 } else { 0 }] {
3246                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3247                 _ => panic!("Unexpected event"),
3248         }
3249         if deliver_bs_raa {
3250                 match events[0] {
3251                         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, .. } } => {
3252                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3253                                 assert_eq!(update_add_htlcs.len(), 1);
3254                                 assert!(update_fulfill_htlcs.is_empty());
3255                                 assert!(update_fail_htlcs.is_empty());
3256                                 assert!(update_fail_malformed_htlcs.is_empty());
3257                         },
3258                         _ => panic!("Unexpected event"),
3259                 }
3260         }
3261         match events[if deliver_bs_raa { 2 } else { 1 }] {
3262                 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, .. } } => {
3263                         assert!(update_add_htlcs.is_empty());
3264                         assert_eq!(update_fail_htlcs.len(), 3);
3265                         assert!(update_fulfill_htlcs.is_empty());
3266                         assert!(update_fail_malformed_htlcs.is_empty());
3267                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3268
3269                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3270                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3271                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3272
3273                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3274
3275                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3276                         // If we delivered B's RAA we got an unknown preimage error, not something
3277                         // that we should update our routing table for.
3278                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3279                         for event in events {
3280                                 match event {
3281                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3282                                         _ => panic!("Unexpected event"),
3283                                 }
3284                         }
3285                         let events = nodes[0].node.get_and_clear_pending_events();
3286                         assert_eq!(events.len(), 3);
3287                         match events[0] {
3288                                 Event::PaymentFailed { ref payment_hash, .. } => {
3289                                         assert!(failed_htlcs.insert(payment_hash.0));
3290                                 },
3291                                 _ => panic!("Unexpected event"),
3292                         }
3293                         match events[1] {
3294                                 Event::PaymentFailed { ref payment_hash, .. } => {
3295                                         assert!(failed_htlcs.insert(payment_hash.0));
3296                                 },
3297                                 _ => panic!("Unexpected event"),
3298                         }
3299                         match events[2] {
3300                                 Event::PaymentFailed { ref payment_hash, .. } => {
3301                                         assert!(failed_htlcs.insert(payment_hash.0));
3302                                 },
3303                                 _ => panic!("Unexpected event"),
3304                         }
3305                 },
3306                 _ => panic!("Unexpected event"),
3307         }
3308
3309         assert!(failed_htlcs.contains(&first_payment_hash.0));
3310         assert!(failed_htlcs.contains(&second_payment_hash.0));
3311         assert!(failed_htlcs.contains(&third_payment_hash.0));
3312 }
3313
3314 #[test]
3315 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3316         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3317         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3318         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3319         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3320 }
3321
3322 #[test]
3323 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3324         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3325         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3326         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3327         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3328 }
3329
3330 #[test]
3331 fn fail_backward_pending_htlc_upon_channel_failure() {
3332         let chanmon_cfgs = create_chanmon_cfgs(2);
3333         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3334         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3335         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3336         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3337         let logger = test_utils::TestLogger::new();
3338
3339         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3340         {
3341                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3342                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3343                 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();
3344                 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3345                 check_added_monitors!(nodes[0], 1);
3346
3347                 let payment_event = {
3348                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3349                         assert_eq!(events.len(), 1);
3350                         SendEvent::from_event(events.remove(0))
3351                 };
3352                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3353                 assert_eq!(payment_event.msgs.len(), 1);
3354         }
3355
3356         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3357         let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3358         {
3359                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3360                 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();
3361                 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3362                 check_added_monitors!(nodes[0], 0);
3363
3364                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3365         }
3366
3367         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3368         {
3369                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3370
3371                 let secp_ctx = Secp256k1::new();
3372                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3373                 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3374                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3375                 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();
3376                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3377                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3378                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3379
3380                 // Send a 0-msat update_add_htlc to fail the channel.
3381                 let update_add_htlc = msgs::UpdateAddHTLC {
3382                         channel_id: chan.2,
3383                         htlc_id: 0,
3384                         amount_msat: 0,
3385                         payment_hash,
3386                         cltv_expiry,
3387                         onion_routing_packet,
3388                 };
3389                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3390         }
3391
3392         // Check that Alice fails backward the pending HTLC from the second payment.
3393         expect_payment_failed!(nodes[0], failed_payment_hash, true);
3394         check_closed_broadcast!(nodes[0], true);
3395         check_added_monitors!(nodes[0], 1);
3396 }
3397
3398 #[test]
3399 fn test_htlc_ignore_latest_remote_commitment() {
3400         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3401         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3402         let chanmon_cfgs = create_chanmon_cfgs(2);
3403         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3404         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3405         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3406         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3407
3408         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3409         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3410         check_closed_broadcast!(nodes[0], false);
3411         check_added_monitors!(nodes[0], 1);
3412
3413         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3414         assert_eq!(node_txn.len(), 2);
3415
3416         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3417         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3418         check_closed_broadcast!(nodes[1], false);
3419         check_added_monitors!(nodes[1], 1);
3420
3421         // Duplicate the connect_block call since this may happen due to other listeners
3422         // registering new transactions
3423         header.prev_blockhash = header.block_hash();
3424         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3425 }
3426
3427 #[test]
3428 fn test_force_close_fail_back() {
3429         // Check which HTLCs are failed-backwards on channel force-closure
3430         let chanmon_cfgs = create_chanmon_cfgs(3);
3431         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3432         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3433         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3434         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3435         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3436         let logger = test_utils::TestLogger::new();
3437
3438         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3439
3440         let mut payment_event = {
3441                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3442                 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();
3443                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3444                 check_added_monitors!(nodes[0], 1);
3445
3446                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3447                 assert_eq!(events.len(), 1);
3448                 SendEvent::from_event(events.remove(0))
3449         };
3450
3451         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3452         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3453
3454         expect_pending_htlcs_forwardable!(nodes[1]);
3455
3456         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3457         assert_eq!(events_2.len(), 1);
3458         payment_event = SendEvent::from_event(events_2.remove(0));
3459         assert_eq!(payment_event.msgs.len(), 1);
3460
3461         check_added_monitors!(nodes[1], 1);
3462         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3463         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3464         check_added_monitors!(nodes[2], 1);
3465         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3466
3467         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3468         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3469         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3470
3471         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3472         check_closed_broadcast!(nodes[2], false);
3473         check_added_monitors!(nodes[2], 1);
3474         let tx = {
3475                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3476                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3477                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3478                 // back to nodes[1] upon timeout otherwise.
3479                 assert_eq!(node_txn.len(), 1);
3480                 node_txn.remove(0)
3481         };
3482
3483         mine_transaction(&nodes[1], &tx);
3484
3485         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3486         check_closed_broadcast!(nodes[1], false);
3487         check_added_monitors!(nodes[1], 1);
3488
3489         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3490         {
3491                 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3492                 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3493                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3494         }
3495         mine_transaction(&nodes[2], &tx);
3496         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3497         assert_eq!(node_txn.len(), 1);
3498         assert_eq!(node_txn[0].input.len(), 1);
3499         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3500         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3501         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3502
3503         check_spends!(node_txn[0], tx);
3504 }
3505
3506 #[test]
3507 fn test_simple_peer_disconnect() {
3508         // Test that we can reconnect when there are no lost messages
3509         let chanmon_cfgs = create_chanmon_cfgs(3);
3510         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3511         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3512         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3513         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3514         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3515
3516         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3517         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3518         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3519
3520         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3521         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3522         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3523         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3524
3525         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3526         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3527         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3528
3529         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3530         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3531         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3532         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3533
3534         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3535         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3536
3537         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3538         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3539
3540         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3541         {
3542                 let events = nodes[0].node.get_and_clear_pending_events();
3543                 assert_eq!(events.len(), 2);
3544                 match events[0] {
3545                         Event::PaymentSent { payment_preimage } => {
3546                                 assert_eq!(payment_preimage, payment_preimage_3);
3547                         },
3548                         _ => panic!("Unexpected event"),
3549                 }
3550                 match events[1] {
3551                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3552                                 assert_eq!(payment_hash, payment_hash_5);
3553                                 assert!(rejected_by_dest);
3554                         },
3555                         _ => panic!("Unexpected event"),
3556                 }
3557         }
3558
3559         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3560         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3561 }
3562
3563 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3564         // Test that we can reconnect when in-flight HTLC updates get dropped
3565         let chanmon_cfgs = create_chanmon_cfgs(2);
3566         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3567         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3568         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3569         if messages_delivered == 0 {
3570                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3571                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3572         } else {
3573                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3574         }
3575
3576         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3577
3578         let logger = test_utils::TestLogger::new();
3579         let payment_event = {
3580                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3581                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3582                         &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3583                         &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3584                 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3585                 check_added_monitors!(nodes[0], 1);
3586
3587                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3588                 assert_eq!(events.len(), 1);
3589                 SendEvent::from_event(events.remove(0))
3590         };
3591         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3592
3593         if messages_delivered < 2 {
3594                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3595         } else {
3596                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3597                 if messages_delivered >= 3 {
3598                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3599                         check_added_monitors!(nodes[1], 1);
3600                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3601
3602                         if messages_delivered >= 4 {
3603                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3604                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3605                                 check_added_monitors!(nodes[0], 1);
3606
3607                                 if messages_delivered >= 5 {
3608                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3609                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3610                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3611                                         check_added_monitors!(nodes[0], 1);
3612
3613                                         if messages_delivered >= 6 {
3614                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3615                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3616                                                 check_added_monitors!(nodes[1], 1);
3617                                         }
3618                                 }
3619                         }
3620                 }
3621         }
3622
3623         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3624         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3625         if messages_delivered < 3 {
3626                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3627                 // received on either side, both sides will need to resend them.
3628                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3629         } else if messages_delivered == 3 {
3630                 // nodes[0] still wants its RAA + commitment_signed
3631                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3632         } else if messages_delivered == 4 {
3633                 // nodes[0] still wants its commitment_signed
3634                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3635         } else if messages_delivered == 5 {
3636                 // nodes[1] still wants its final RAA
3637                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3638         } else if messages_delivered == 6 {
3639                 // Everything was delivered...
3640                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3641         }
3642
3643         let events_1 = nodes[1].node.get_and_clear_pending_events();
3644         assert_eq!(events_1.len(), 1);
3645         match events_1[0] {
3646                 Event::PendingHTLCsForwardable { .. } => { },
3647                 _ => panic!("Unexpected event"),
3648         };
3649
3650         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3651         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3652         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3653
3654         nodes[1].node.process_pending_htlc_forwards();
3655
3656         let events_2 = nodes[1].node.get_and_clear_pending_events();
3657         assert_eq!(events_2.len(), 1);
3658         match events_2[0] {
3659                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3660                         assert_eq!(payment_hash_1, *payment_hash);
3661                         assert_eq!(*payment_secret, None);
3662                         assert_eq!(amt, 1000000);
3663                 },
3664                 _ => panic!("Unexpected event"),
3665         }
3666
3667         nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3668         check_added_monitors!(nodes[1], 1);
3669
3670         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3671         assert_eq!(events_3.len(), 1);
3672         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3673                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3674                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3675                         assert!(updates.update_add_htlcs.is_empty());
3676                         assert!(updates.update_fail_htlcs.is_empty());
3677                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3678                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3679                         assert!(updates.update_fee.is_none());
3680                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3681                 },
3682                 _ => panic!("Unexpected event"),
3683         };
3684
3685         if messages_delivered >= 1 {
3686                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3687
3688                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3689                 assert_eq!(events_4.len(), 1);
3690                 match events_4[0] {
3691                         Event::PaymentSent { ref payment_preimage } => {
3692                                 assert_eq!(payment_preimage_1, *payment_preimage);
3693                         },
3694                         _ => panic!("Unexpected event"),
3695                 }
3696
3697                 if messages_delivered >= 2 {
3698                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3699                         check_added_monitors!(nodes[0], 1);
3700                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3701
3702                         if messages_delivered >= 3 {
3703                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3704                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3705                                 check_added_monitors!(nodes[1], 1);
3706
3707                                 if messages_delivered >= 4 {
3708                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3709                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3710                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3711                                         check_added_monitors!(nodes[1], 1);
3712
3713                                         if messages_delivered >= 5 {
3714                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3715                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3716                                                 check_added_monitors!(nodes[0], 1);
3717                                         }
3718                                 }
3719                         }
3720                 }
3721         }
3722
3723         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3724         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3725         if messages_delivered < 2 {
3726                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3727                 //TODO: Deduplicate PaymentSent events, then enable this if:
3728                 //if messages_delivered < 1 {
3729                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3730                         assert_eq!(events_4.len(), 1);
3731                         match events_4[0] {
3732                                 Event::PaymentSent { ref payment_preimage } => {
3733                                         assert_eq!(payment_preimage_1, *payment_preimage);
3734                                 },
3735                                 _ => panic!("Unexpected event"),
3736                         }
3737                 //}
3738         } else if messages_delivered == 2 {
3739                 // nodes[0] still wants its RAA + commitment_signed
3740                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3741         } else if messages_delivered == 3 {
3742                 // nodes[0] still wants its commitment_signed
3743                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3744         } else if messages_delivered == 4 {
3745                 // nodes[1] still wants its final RAA
3746                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3747         } else if messages_delivered == 5 {
3748                 // Everything was delivered...
3749                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3750         }
3751
3752         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3753         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3754         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3755
3756         // Channel should still work fine...
3757         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3758         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3759                 &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3760                 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3761         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3762         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3763 }
3764
3765 #[test]
3766 fn test_drop_messages_peer_disconnect_a() {
3767         do_test_drop_messages_peer_disconnect(0);
3768         do_test_drop_messages_peer_disconnect(1);
3769         do_test_drop_messages_peer_disconnect(2);
3770         do_test_drop_messages_peer_disconnect(3);
3771 }
3772
3773 #[test]
3774 fn test_drop_messages_peer_disconnect_b() {
3775         do_test_drop_messages_peer_disconnect(4);
3776         do_test_drop_messages_peer_disconnect(5);
3777         do_test_drop_messages_peer_disconnect(6);
3778 }
3779
3780 #[test]
3781 fn test_funding_peer_disconnect() {
3782         // Test that we can lock in our funding tx while disconnected
3783         let chanmon_cfgs = create_chanmon_cfgs(2);
3784         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3785         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3786         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3787         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3788
3789         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3790         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3791
3792         confirm_transaction(&nodes[0], &tx);
3793         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3794         assert_eq!(events_1.len(), 1);
3795         match events_1[0] {
3796                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3797                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3798                 },
3799                 _ => panic!("Unexpected event"),
3800         }
3801
3802         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3803
3804         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3805         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3806
3807         confirm_transaction(&nodes[1], &tx);
3808         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3809         assert_eq!(events_2.len(), 2);
3810         let funding_locked = match events_2[0] {
3811                 MessageSendEvent::SendFundingLocked { 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         let bs_announcement_sigs = match events_2[1] {
3818                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3819                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3820                         msg.clone()
3821                 },
3822                 _ => panic!("Unexpected event"),
3823         };
3824
3825         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3826
3827         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3828         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3829         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3830         assert_eq!(events_3.len(), 2);
3831         let as_announcement_sigs = match events_3[0] {
3832                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3833                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3834                         msg.clone()
3835                 },
3836                 _ => panic!("Unexpected event"),
3837         };
3838         let (as_announcement, as_update) = match events_3[1] {
3839                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3840                         (msg.clone(), update_msg.clone())
3841                 },
3842                 _ => panic!("Unexpected event"),
3843         };
3844
3845         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3846         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3847         assert_eq!(events_4.len(), 1);
3848         let (_, bs_update) = match events_4[0] {
3849                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3850                         (msg.clone(), update_msg.clone())
3851                 },
3852                 _ => panic!("Unexpected event"),
3853         };
3854
3855         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3856         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3857         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3858
3859         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3860         let logger = test_utils::TestLogger::new();
3861         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();
3862         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3863         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3864 }
3865
3866 #[test]
3867 fn test_drop_messages_peer_disconnect_dual_htlc() {
3868         // Test that we can handle reconnecting when both sides of a channel have pending
3869         // commitment_updates when we disconnect.
3870         let chanmon_cfgs = create_chanmon_cfgs(2);
3871         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3872         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3873         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3874         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3875         let logger = test_utils::TestLogger::new();
3876
3877         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3878
3879         // Now try to send a second payment which will fail to send
3880         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3881         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3882         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();
3883         nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3884         check_added_monitors!(nodes[0], 1);
3885
3886         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3887         assert_eq!(events_1.len(), 1);
3888         match events_1[0] {
3889                 MessageSendEvent::UpdateHTLCs { .. } => {},
3890                 _ => panic!("Unexpected event"),
3891         }
3892
3893         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3894         check_added_monitors!(nodes[1], 1);
3895
3896         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3897         assert_eq!(events_2.len(), 1);
3898         match events_2[0] {
3899                 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 } } => {
3900                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3901                         assert!(update_add_htlcs.is_empty());
3902                         assert_eq!(update_fulfill_htlcs.len(), 1);
3903                         assert!(update_fail_htlcs.is_empty());
3904                         assert!(update_fail_malformed_htlcs.is_empty());
3905                         assert!(update_fee.is_none());
3906
3907                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3908                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3909                         assert_eq!(events_3.len(), 1);
3910                         match events_3[0] {
3911                                 Event::PaymentSent { ref payment_preimage } => {
3912                                         assert_eq!(*payment_preimage, payment_preimage_1);
3913                                 },
3914                                 _ => panic!("Unexpected event"),
3915                         }
3916
3917                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3918                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3919                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3920                         check_added_monitors!(nodes[0], 1);
3921                 },
3922                 _ => panic!("Unexpected event"),
3923         }
3924
3925         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3926         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3927
3928         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3929         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3930         assert_eq!(reestablish_1.len(), 1);
3931         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3932         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3933         assert_eq!(reestablish_2.len(), 1);
3934
3935         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3936         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3937         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3938         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3939
3940         assert!(as_resp.0.is_none());
3941         assert!(bs_resp.0.is_none());
3942
3943         assert!(bs_resp.1.is_none());
3944         assert!(bs_resp.2.is_none());
3945
3946         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3947
3948         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3949         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3950         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3951         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3952         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3953         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3954         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3955         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3956         // No commitment_signed so get_event_msg's assert(len == 1) passes
3957         check_added_monitors!(nodes[1], 1);
3958
3959         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3960         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3961         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3962         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3963         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3964         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3965         assert!(bs_second_commitment_signed.update_fee.is_none());
3966         check_added_monitors!(nodes[1], 1);
3967
3968         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3969         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3970         assert!(as_commitment_signed.update_add_htlcs.is_empty());
3971         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3972         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3973         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3974         assert!(as_commitment_signed.update_fee.is_none());
3975         check_added_monitors!(nodes[0], 1);
3976
3977         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3978         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3979         // No commitment_signed so get_event_msg's assert(len == 1) passes
3980         check_added_monitors!(nodes[0], 1);
3981
3982         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3983         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3984         // No commitment_signed so get_event_msg's assert(len == 1) passes
3985         check_added_monitors!(nodes[1], 1);
3986
3987         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3988         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3989         check_added_monitors!(nodes[1], 1);
3990
3991         expect_pending_htlcs_forwardable!(nodes[1]);
3992
3993         let events_5 = nodes[1].node.get_and_clear_pending_events();
3994         assert_eq!(events_5.len(), 1);
3995         match events_5[0] {
3996                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
3997                         assert_eq!(payment_hash_2, *payment_hash);
3998                         assert_eq!(*payment_secret, None);
3999                 },
4000                 _ => panic!("Unexpected event"),
4001         }
4002
4003         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4004         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4005         check_added_monitors!(nodes[0], 1);
4006
4007         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4008 }
4009
4010 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4011         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4012         // to avoid our counterparty failing the channel.
4013         let chanmon_cfgs = create_chanmon_cfgs(2);
4014         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4015         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4016         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4017
4018         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4019         let logger = test_utils::TestLogger::new();
4020
4021         let our_payment_hash = if send_partial_mpp {
4022                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4023                 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();
4024                 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4025                 let payment_secret = PaymentSecret([0xdb; 32]);
4026                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4027                 // indicates there are more HTLCs coming.
4028                 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.
4029                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height).unwrap();
4030                 check_added_monitors!(nodes[0], 1);
4031                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4032                 assert_eq!(events.len(), 1);
4033                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4034                 // hop should *not* yet generate any PaymentReceived event(s).
4035                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4036                 our_payment_hash
4037         } else {
4038                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4039         };
4040
4041         let mut block = Block {
4042                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4043                 txdata: vec![],
4044         };
4045         connect_block(&nodes[0], &block);
4046         connect_block(&nodes[1], &block);
4047         for _ in CHAN_CONFIRM_DEPTH + 2 ..TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4048                 block.header.prev_blockhash = block.block_hash();
4049                 connect_block(&nodes[0], &block);
4050                 connect_block(&nodes[1], &block);
4051         }
4052
4053         expect_pending_htlcs_forwardable!(nodes[1]);
4054
4055         check_added_monitors!(nodes[1], 1);
4056         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4057         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4058         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4059         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4060         assert!(htlc_timeout_updates.update_fee.is_none());
4061
4062         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4063         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4064         // 100_000 msat as u64, followed by a height of TEST_FINAL_CLTV + 2 as u32
4065         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4066         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(TEST_FINAL_CLTV + 2));
4067         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4068 }
4069
4070 #[test]
4071 fn test_htlc_timeout() {
4072         do_test_htlc_timeout(true);
4073         do_test_htlc_timeout(false);
4074 }
4075
4076 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4077         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4078         let chanmon_cfgs = create_chanmon_cfgs(3);
4079         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4080         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4081         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4082         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4083         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4084
4085         // Make sure all nodes are at the same starting height
4086         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4087         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4088         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4089
4090         let logger = test_utils::TestLogger::new();
4091
4092         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4093         let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4094         {
4095                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4096                 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();
4097                 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4098         }
4099         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4100         check_added_monitors!(nodes[1], 1);
4101
4102         // Now attempt to route a second payment, which should be placed in the holding cell
4103         let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4104         if forwarded_htlc {
4105                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4106                 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();
4107                 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4108                 check_added_monitors!(nodes[0], 1);
4109                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4110                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4111                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4112                 expect_pending_htlcs_forwardable!(nodes[1]);
4113                 check_added_monitors!(nodes[1], 0);
4114         } else {
4115                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4116                 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();
4117                 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4118                 check_added_monitors!(nodes[1], 0);
4119         }
4120
4121         connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4122         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4123         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4124         connect_blocks(&nodes[1], 1);
4125
4126         if forwarded_htlc {
4127                 expect_pending_htlcs_forwardable!(nodes[1]);
4128                 check_added_monitors!(nodes[1], 1);
4129                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4130                 assert_eq!(fail_commit.len(), 1);
4131                 match fail_commit[0] {
4132                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4133                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4134                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4135                         },
4136                         _ => unreachable!(),
4137                 }
4138                 expect_payment_failed!(nodes[0], second_payment_hash, false);
4139                 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4140                         match update {
4141                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4142                                 _ => panic!("Unexpected event"),
4143                         }
4144                 } else {
4145                         panic!("Unexpected event");
4146                 }
4147         } else {
4148                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4149         }
4150 }
4151
4152 #[test]
4153 fn test_holding_cell_htlc_add_timeouts() {
4154         do_test_holding_cell_htlc_add_timeouts(false);
4155         do_test_holding_cell_htlc_add_timeouts(true);
4156 }
4157
4158 #[test]
4159 fn test_invalid_channel_announcement() {
4160         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4161         let secp_ctx = Secp256k1::new();
4162         let chanmon_cfgs = create_chanmon_cfgs(2);
4163         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4164         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4165         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4166
4167         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4168
4169         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4170         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4171         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4172         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4173
4174         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 } );
4175
4176         let as_bitcoin_key = as_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4177         let bs_bitcoin_key = bs_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4178
4179         let as_network_key = nodes[0].node.get_our_node_id();
4180         let bs_network_key = nodes[1].node.get_our_node_id();
4181
4182         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4183
4184         let mut chan_announcement;
4185
4186         macro_rules! dummy_unsigned_msg {
4187                 () => {
4188                         msgs::UnsignedChannelAnnouncement {
4189                                 features: ChannelFeatures::known(),
4190                                 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4191                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4192                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4193                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4194                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4195                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4196                                 excess_data: Vec::new(),
4197                         };
4198                 }
4199         }
4200
4201         macro_rules! sign_msg {
4202                 ($unsigned_msg: expr) => {
4203                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4204                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_signer().inner.funding_key);
4205                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_signer().inner.funding_key);
4206                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4207                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4208                         chan_announcement = msgs::ChannelAnnouncement {
4209                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4210                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4211                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4212                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4213                                 contents: $unsigned_msg
4214                         }
4215                 }
4216         }
4217
4218         let unsigned_msg = dummy_unsigned_msg!();
4219         sign_msg!(unsigned_msg);
4220         assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4221         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 } );
4222
4223         // Configured with Network::Testnet
4224         let mut unsigned_msg = dummy_unsigned_msg!();
4225         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4226         sign_msg!(unsigned_msg);
4227         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4228
4229         let mut unsigned_msg = dummy_unsigned_msg!();
4230         unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4231         sign_msg!(unsigned_msg);
4232         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4233 }
4234
4235 #[test]
4236 fn test_no_txn_manager_serialize_deserialize() {
4237         let chanmon_cfgs = create_chanmon_cfgs(2);
4238         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4239         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4240         let logger: test_utils::TestLogger;
4241         let fee_estimator: test_utils::TestFeeEstimator;
4242         let persister: test_utils::TestPersister;
4243         let new_chain_monitor: test_utils::TestChainMonitor;
4244         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4245         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4246
4247         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4248
4249         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4250
4251         let nodes_0_serialized = nodes[0].node.encode();
4252         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4253         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4254
4255         logger = test_utils::TestLogger::new();
4256         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4257         persister = test_utils::TestPersister::new();
4258         let keys_manager = &chanmon_cfgs[0].keys_manager;
4259         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4260         nodes[0].chain_monitor = &new_chain_monitor;
4261         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4262         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4263                 &mut chan_0_monitor_read, keys_manager).unwrap();
4264         assert!(chan_0_monitor_read.is_empty());
4265
4266         let mut nodes_0_read = &nodes_0_serialized[..];
4267         let config = UserConfig::default();
4268         let (_, nodes_0_deserialized_tmp) = {
4269                 let mut channel_monitors = HashMap::new();
4270                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4271                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4272                         default_config: config,
4273                         keys_manager,
4274                         fee_estimator: &fee_estimator,
4275                         chain_monitor: nodes[0].chain_monitor,
4276                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4277                         logger: &logger,
4278                         channel_monitors,
4279                 }).unwrap()
4280         };
4281         nodes_0_deserialized = nodes_0_deserialized_tmp;
4282         assert!(nodes_0_read.is_empty());
4283
4284         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4285         nodes[0].node = &nodes_0_deserialized;
4286         assert_eq!(nodes[0].node.list_channels().len(), 1);
4287         check_added_monitors!(nodes[0], 1);
4288
4289         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4290         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4291         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4292         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4293
4294         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4295         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4296         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4297         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4298
4299         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4300         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4301         for node in nodes.iter() {
4302                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4303                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4304                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4305         }
4306
4307         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4308 }
4309
4310 #[test]
4311 fn test_manager_serialize_deserialize_events() {
4312         // This test makes sure the events field in ChannelManager survives de/serialization
4313         let chanmon_cfgs = create_chanmon_cfgs(2);
4314         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4315         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4316         let fee_estimator: test_utils::TestFeeEstimator;
4317         let persister: test_utils::TestPersister;
4318         let logger: test_utils::TestLogger;
4319         let new_chain_monitor: test_utils::TestChainMonitor;
4320         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4321         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4322
4323         // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4324         let channel_value = 100000;
4325         let push_msat = 10001;
4326         let a_flags = InitFeatures::known();
4327         let b_flags = InitFeatures::known();
4328         let node_a = nodes.remove(0);
4329         let node_b = nodes.remove(0);
4330         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4331         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()));
4332         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()));
4333
4334         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4335
4336         node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4337         check_added_monitors!(node_a, 0);
4338
4339         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()));
4340         {
4341                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4342                 assert_eq!(added_monitors.len(), 1);
4343                 assert_eq!(added_monitors[0].0, funding_output);
4344                 added_monitors.clear();
4345         }
4346
4347         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()));
4348         {
4349                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4350                 assert_eq!(added_monitors.len(), 1);
4351                 assert_eq!(added_monitors[0].0, funding_output);
4352                 added_monitors.clear();
4353         }
4354         // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4355
4356         nodes.push(node_a);
4357         nodes.push(node_b);
4358
4359         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4360         let nodes_0_serialized = nodes[0].node.encode();
4361         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4362         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4363
4364         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4365         logger = test_utils::TestLogger::new();
4366         persister = test_utils::TestPersister::new();
4367         let keys_manager = &chanmon_cfgs[0].keys_manager;
4368         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4369         nodes[0].chain_monitor = &new_chain_monitor;
4370         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4371         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4372                 &mut chan_0_monitor_read, keys_manager).unwrap();
4373         assert!(chan_0_monitor_read.is_empty());
4374
4375         let mut nodes_0_read = &nodes_0_serialized[..];
4376         let config = UserConfig::default();
4377         let (_, nodes_0_deserialized_tmp) = {
4378                 let mut channel_monitors = HashMap::new();
4379                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4380                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4381                         default_config: config,
4382                         keys_manager,
4383                         fee_estimator: &fee_estimator,
4384                         chain_monitor: nodes[0].chain_monitor,
4385                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4386                         logger: &logger,
4387                         channel_monitors,
4388                 }).unwrap()
4389         };
4390         nodes_0_deserialized = nodes_0_deserialized_tmp;
4391         assert!(nodes_0_read.is_empty());
4392
4393         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4394
4395         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4396         nodes[0].node = &nodes_0_deserialized;
4397
4398         // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4399         let events_4 = nodes[0].node.get_and_clear_pending_events();
4400         assert_eq!(events_4.len(), 1);
4401         match events_4[0] {
4402                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4403                         assert_eq!(user_channel_id, 42);
4404                         assert_eq!(*funding_txo, funding_output);
4405                 },
4406                 _ => panic!("Unexpected event"),
4407         };
4408
4409         // Make sure the channel is functioning as though the de/serialization never happened
4410         assert_eq!(nodes[0].node.list_channels().len(), 1);
4411         check_added_monitors!(nodes[0], 1);
4412
4413         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4414         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4415         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4416         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4417
4418         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4419         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4420         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4421         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4422
4423         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4424         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4425         for node in nodes.iter() {
4426                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4427                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4428                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4429         }
4430
4431         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4432 }
4433
4434 #[test]
4435 fn test_simple_manager_serialize_deserialize() {
4436         let chanmon_cfgs = create_chanmon_cfgs(2);
4437         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4438         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4439         let logger: test_utils::TestLogger;
4440         let fee_estimator: test_utils::TestFeeEstimator;
4441         let persister: test_utils::TestPersister;
4442         let new_chain_monitor: test_utils::TestChainMonitor;
4443         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4444         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4445         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4446
4447         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4448         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4449
4450         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4451
4452         let nodes_0_serialized = nodes[0].node.encode();
4453         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4454         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4455
4456         logger = test_utils::TestLogger::new();
4457         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4458         persister = test_utils::TestPersister::new();
4459         let keys_manager = &chanmon_cfgs[0].keys_manager;
4460         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4461         nodes[0].chain_monitor = &new_chain_monitor;
4462         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4463         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4464                 &mut chan_0_monitor_read, keys_manager).unwrap();
4465         assert!(chan_0_monitor_read.is_empty());
4466
4467         let mut nodes_0_read = &nodes_0_serialized[..];
4468         let (_, nodes_0_deserialized_tmp) = {
4469                 let mut channel_monitors = HashMap::new();
4470                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4471                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4472                         default_config: UserConfig::default(),
4473                         keys_manager,
4474                         fee_estimator: &fee_estimator,
4475                         chain_monitor: nodes[0].chain_monitor,
4476                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4477                         logger: &logger,
4478                         channel_monitors,
4479                 }).unwrap()
4480         };
4481         nodes_0_deserialized = nodes_0_deserialized_tmp;
4482         assert!(nodes_0_read.is_empty());
4483
4484         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4485         nodes[0].node = &nodes_0_deserialized;
4486         check_added_monitors!(nodes[0], 1);
4487
4488         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4489
4490         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4491         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4492 }
4493
4494 #[test]
4495 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4496         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4497         let chanmon_cfgs = create_chanmon_cfgs(4);
4498         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4499         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4500         let logger: test_utils::TestLogger;
4501         let fee_estimator: test_utils::TestFeeEstimator;
4502         let persister: test_utils::TestPersister;
4503         let new_chain_monitor: test_utils::TestChainMonitor;
4504         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4505         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4506         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4507         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4508         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4509
4510         let mut node_0_stale_monitors_serialized = Vec::new();
4511         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4512                 let mut writer = test_utils::TestVecWriter(Vec::new());
4513                 monitor.1.write(&mut writer).unwrap();
4514                 node_0_stale_monitors_serialized.push(writer.0);
4515         }
4516
4517         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4518
4519         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4520         let nodes_0_serialized = nodes[0].node.encode();
4521
4522         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4523         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4524         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4525         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4526
4527         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4528         // nodes[3])
4529         let mut node_0_monitors_serialized = Vec::new();
4530         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4531                 let mut writer = test_utils::TestVecWriter(Vec::new());
4532                 monitor.1.write(&mut writer).unwrap();
4533                 node_0_monitors_serialized.push(writer.0);
4534         }
4535
4536         logger = test_utils::TestLogger::new();
4537         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4538         persister = test_utils::TestPersister::new();
4539         let keys_manager = &chanmon_cfgs[0].keys_manager;
4540         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4541         nodes[0].chain_monitor = &new_chain_monitor;
4542
4543
4544         let mut node_0_stale_monitors = Vec::new();
4545         for serialized in node_0_stale_monitors_serialized.iter() {
4546                 let mut read = &serialized[..];
4547                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4548                 assert!(read.is_empty());
4549                 node_0_stale_monitors.push(monitor);
4550         }
4551
4552         let mut node_0_monitors = Vec::new();
4553         for serialized in node_0_monitors_serialized.iter() {
4554                 let mut read = &serialized[..];
4555                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4556                 assert!(read.is_empty());
4557                 node_0_monitors.push(monitor);
4558         }
4559
4560         let mut nodes_0_read = &nodes_0_serialized[..];
4561         if let Err(msgs::DecodeError::InvalidValue) =
4562                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4563                 default_config: UserConfig::default(),
4564                 keys_manager,
4565                 fee_estimator: &fee_estimator,
4566                 chain_monitor: nodes[0].chain_monitor,
4567                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4568                 logger: &logger,
4569                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4570         }) { } else {
4571                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4572         };
4573
4574         let mut nodes_0_read = &nodes_0_serialized[..];
4575         let (_, nodes_0_deserialized_tmp) =
4576                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4577                 default_config: UserConfig::default(),
4578                 keys_manager,
4579                 fee_estimator: &fee_estimator,
4580                 chain_monitor: nodes[0].chain_monitor,
4581                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4582                 logger: &logger,
4583                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4584         }).unwrap();
4585         nodes_0_deserialized = nodes_0_deserialized_tmp;
4586         assert!(nodes_0_read.is_empty());
4587
4588         { // Channel close should result in a commitment tx and an HTLC tx
4589                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4590                 assert_eq!(txn.len(), 2);
4591                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4592                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4593         }
4594
4595         for monitor in node_0_monitors.drain(..) {
4596                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4597                 check_added_monitors!(nodes[0], 1);
4598         }
4599         nodes[0].node = &nodes_0_deserialized;
4600
4601         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4602         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4603         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4604         //... and we can even still claim the payment!
4605         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4606
4607         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4608         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4609         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4610         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4611         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4612         assert_eq!(msg_events.len(), 1);
4613         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4614                 match action {
4615                         &ErrorAction::SendErrorMessage { ref msg } => {
4616                                 assert_eq!(msg.channel_id, channel_id);
4617                         },
4618                         _ => panic!("Unexpected event!"),
4619                 }
4620         }
4621 }
4622
4623 macro_rules! check_spendable_outputs {
4624         ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4625                 {
4626                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4627                         let mut txn = Vec::new();
4628                         let mut all_outputs = Vec::new();
4629                         let secp_ctx = Secp256k1::new();
4630                         for event in events.drain(..) {
4631                                 match event {
4632                                         Event::SpendableOutputs { mut outputs } => {
4633                                                 for outp in outputs.drain(..) {
4634                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4635                                                         all_outputs.push(outp);
4636                                                 }
4637                                         },
4638                                         _ => panic!("Unexpected event"),
4639                                 };
4640                         }
4641                         if all_outputs.len() > 1 {
4642                                 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) {
4643                                         txn.push(tx);
4644                                 }
4645                         }
4646                         txn
4647                 }
4648         }
4649 }
4650
4651 #[test]
4652 fn test_claim_sizeable_push_msat() {
4653         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4654         let chanmon_cfgs = create_chanmon_cfgs(2);
4655         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4656         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4657         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4658
4659         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4660         nodes[1].node.force_close_channel(&chan.2).unwrap();
4661         check_closed_broadcast!(nodes[1], false);
4662         check_added_monitors!(nodes[1], 1);
4663         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4664         assert_eq!(node_txn.len(), 1);
4665         check_spends!(node_txn[0], chan.3);
4666         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
4667
4668         mine_transaction(&nodes[1], &node_txn[0]);
4669         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4670
4671         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4672         assert_eq!(spend_txn.len(), 1);
4673         check_spends!(spend_txn[0], node_txn[0]);
4674 }
4675
4676 #[test]
4677 fn test_claim_on_remote_sizeable_push_msat() {
4678         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4679         // to_remote output is encumbered by a P2WPKH
4680         let chanmon_cfgs = create_chanmon_cfgs(2);
4681         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4682         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4683         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4684
4685         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4686         nodes[0].node.force_close_channel(&chan.2).unwrap();
4687         check_closed_broadcast!(nodes[0], false);
4688         check_added_monitors!(nodes[0], 1);
4689
4690         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4691         assert_eq!(node_txn.len(), 1);
4692         check_spends!(node_txn[0], chan.3);
4693         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
4694
4695         mine_transaction(&nodes[1], &node_txn[0]);
4696         check_closed_broadcast!(nodes[1], false);
4697         check_added_monitors!(nodes[1], 1);
4698         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4699
4700         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4701         assert_eq!(spend_txn.len(), 1);
4702         check_spends!(spend_txn[0], node_txn[0]);
4703 }
4704
4705 #[test]
4706 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4707         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4708         // to_remote output is encumbered by a P2WPKH
4709
4710         let chanmon_cfgs = create_chanmon_cfgs(2);
4711         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4712         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4713         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4714
4715         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4716         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4717         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4718         assert_eq!(revoked_local_txn[0].input.len(), 1);
4719         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4720
4721         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4722         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4723         check_closed_broadcast!(nodes[1], false);
4724         check_added_monitors!(nodes[1], 1);
4725
4726         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4727         mine_transaction(&nodes[1], &node_txn[0]);
4728         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4729
4730         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4731         assert_eq!(spend_txn.len(), 3);
4732         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4733         check_spends!(spend_txn[1], node_txn[0]);
4734         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4735 }
4736
4737 #[test]
4738 fn test_static_spendable_outputs_preimage_tx() {
4739         let chanmon_cfgs = create_chanmon_cfgs(2);
4740         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4741         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4742         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4743
4744         // Create some initial channels
4745         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4746
4747         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4748
4749         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4750         assert_eq!(commitment_tx[0].input.len(), 1);
4751         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4752
4753         // Settle A's commitment tx on B's chain
4754         assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4755         check_added_monitors!(nodes[1], 1);
4756         mine_transaction(&nodes[1], &commitment_tx[0]);
4757         check_added_monitors!(nodes[1], 1);
4758         let events = nodes[1].node.get_and_clear_pending_msg_events();
4759         match events[0] {
4760                 MessageSendEvent::UpdateHTLCs { .. } => {},
4761                 _ => panic!("Unexpected event"),
4762         }
4763         match events[1] {
4764                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4765                 _ => panic!("Unexepected event"),
4766         }
4767
4768         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4769         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4770         assert_eq!(node_txn.len(), 3);
4771         check_spends!(node_txn[0], commitment_tx[0]);
4772         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4773         check_spends!(node_txn[1], chan_1.3);
4774         check_spends!(node_txn[2], node_txn[1]);
4775
4776         mine_transaction(&nodes[1], &node_txn[0]);
4777         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4778
4779         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4780         assert_eq!(spend_txn.len(), 1);
4781         check_spends!(spend_txn[0], node_txn[0]);
4782 }
4783
4784 #[test]
4785 fn test_static_spendable_outputs_timeout_tx() {
4786         let chanmon_cfgs = create_chanmon_cfgs(2);
4787         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4788         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4789         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4790
4791         // Create some initial channels
4792         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4793
4794         // Rebalance the network a bit by relaying one payment through all the channels ...
4795         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4796
4797         let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4798
4799         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4800         assert_eq!(commitment_tx[0].input.len(), 1);
4801         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4802
4803         // Settle A's commitment tx on B' chain
4804         mine_transaction(&nodes[1], &commitment_tx[0]);
4805         check_added_monitors!(nodes[1], 1);
4806         let events = nodes[1].node.get_and_clear_pending_msg_events();
4807         match events[0] {
4808                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4809                 _ => panic!("Unexpected event"),
4810         }
4811
4812         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4813         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4814         assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4815         check_spends!(node_txn[0],  commitment_tx[0].clone());
4816         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4817         check_spends!(node_txn[1], chan_1.3.clone());
4818         check_spends!(node_txn[2], node_txn[1]);
4819
4820         mine_transaction(&nodes[1], &node_txn[0]);
4821         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4822         expect_payment_failed!(nodes[1], our_payment_hash, true);
4823
4824         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4825         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4826         check_spends!(spend_txn[0], commitment_tx[0]);
4827         check_spends!(spend_txn[1], node_txn[0]);
4828         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4829 }
4830
4831 #[test]
4832 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4833         let chanmon_cfgs = create_chanmon_cfgs(2);
4834         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4835         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4836         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4837
4838         // Create some initial channels
4839         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4840
4841         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4842         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4843         assert_eq!(revoked_local_txn[0].input.len(), 1);
4844         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4845
4846         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4847
4848         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4849         check_closed_broadcast!(nodes[1], false);
4850         check_added_monitors!(nodes[1], 1);
4851
4852         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4853         assert_eq!(node_txn.len(), 2);
4854         assert_eq!(node_txn[0].input.len(), 2);
4855         check_spends!(node_txn[0], revoked_local_txn[0]);
4856
4857         mine_transaction(&nodes[1], &node_txn[0]);
4858         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4859
4860         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4861         assert_eq!(spend_txn.len(), 1);
4862         check_spends!(spend_txn[0], node_txn[0]);
4863 }
4864
4865 #[test]
4866 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4867         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4868         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4869         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4870         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4871         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4872
4873         // Create some initial channels
4874         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4875
4876         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4877         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4878         assert_eq!(revoked_local_txn[0].input.len(), 1);
4879         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4880
4881         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4882
4883         // A will generate HTLC-Timeout from revoked commitment tx
4884         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4885         check_closed_broadcast!(nodes[0], false);
4886         check_added_monitors!(nodes[0], 1);
4887
4888         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4889         assert_eq!(revoked_htlc_txn.len(), 2);
4890         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4891         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4892         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4893         check_spends!(revoked_htlc_txn[1], chan_1.3);
4894
4895         // B will generate justice tx from A's revoked commitment/HTLC tx
4896         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4897         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4898         check_closed_broadcast!(nodes[1], false);
4899         check_added_monitors!(nodes[1], 1);
4900
4901         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4902         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4903         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4904         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4905         // transactions next...
4906         assert_eq!(node_txn[0].input.len(), 3);
4907         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4908
4909         assert_eq!(node_txn[1].input.len(), 2);
4910         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4911         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4912                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4913         } else {
4914                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4915                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4916         }
4917
4918         assert_eq!(node_txn[2].input.len(), 1);
4919         check_spends!(node_txn[2], chan_1.3);
4920
4921         mine_transaction(&nodes[1], &node_txn[1]);
4922         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4923
4924         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4925         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4926         assert_eq!(spend_txn.len(), 1);
4927         assert_eq!(spend_txn[0].input.len(), 1);
4928         check_spends!(spend_txn[0], node_txn[1]);
4929 }
4930
4931 #[test]
4932 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4933         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4934         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4935         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4936         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4937         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4938
4939         // Create some initial channels
4940         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4941
4942         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4943         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4944         assert_eq!(revoked_local_txn[0].input.len(), 1);
4945         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4946
4947         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4948         assert_eq!(revoked_local_txn[0].output.len(), 2);
4949
4950         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4951
4952         // B will generate HTLC-Success from revoked commitment tx
4953         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4954         check_closed_broadcast!(nodes[1], false);
4955         check_added_monitors!(nodes[1], 1);
4956         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4957
4958         assert_eq!(revoked_htlc_txn.len(), 2);
4959         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4960         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4961         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4962
4963         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4964         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4965         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4966
4967         // A will generate justice tx from B's revoked commitment/HTLC tx
4968         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4969         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4970         check_closed_broadcast!(nodes[0], false);
4971         check_added_monitors!(nodes[0], 1);
4972
4973         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4974         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4975
4976         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4977         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4978         // transactions next...
4979         assert_eq!(node_txn[0].input.len(), 2);
4980         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4981         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4982                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4983         } else {
4984                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4985                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4986         }
4987
4988         assert_eq!(node_txn[1].input.len(), 1);
4989         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4990
4991         check_spends!(node_txn[2], chan_1.3);
4992
4993         mine_transaction(&nodes[0], &node_txn[1]);
4994         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4995
4996         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4997         // didn't try to generate any new transactions.
4998
4999         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5000         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5001         assert_eq!(spend_txn.len(), 3);
5002         assert_eq!(spend_txn[0].input.len(), 1);
5003         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5004         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5005         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5006         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5007 }
5008
5009 #[test]
5010 fn test_onchain_to_onchain_claim() {
5011         // Test that in case of channel closure, we detect the state of output and claim HTLC
5012         // on downstream peer's remote commitment tx.
5013         // First, have C claim an HTLC against its own latest commitment transaction.
5014         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5015         // channel.
5016         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5017         // gets broadcast.
5018
5019         let chanmon_cfgs = create_chanmon_cfgs(3);
5020         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5021         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5022         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5023
5024         // Create some initial channels
5025         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5026         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5027
5028         // Rebalance the network a bit by relaying one payment through all the channels ...
5029         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5030         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5031
5032         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5033         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5034         check_spends!(commitment_tx[0], chan_2.3);
5035         nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5036         check_added_monitors!(nodes[2], 1);
5037         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5038         assert!(updates.update_add_htlcs.is_empty());
5039         assert!(updates.update_fail_htlcs.is_empty());
5040         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5041         assert!(updates.update_fail_malformed_htlcs.is_empty());
5042
5043         mine_transaction(&nodes[2], &commitment_tx[0]);
5044         check_closed_broadcast!(nodes[2], false);
5045         check_added_monitors!(nodes[2], 1);
5046
5047         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5048         assert_eq!(c_txn.len(), 3);
5049         assert_eq!(c_txn[0], c_txn[2]);
5050         assert_eq!(commitment_tx[0], c_txn[1]);
5051         check_spends!(c_txn[1], chan_2.3);
5052         check_spends!(c_txn[2], c_txn[1]);
5053         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5054         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5055         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5056         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5057
5058         // 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
5059         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5060         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5061         {
5062                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5063                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5064                 assert_eq!(b_txn.len(), 3);
5065                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5066                 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5067                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5068                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5069                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5070                 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5071                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5072                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5073                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5074                 b_txn.clear();
5075         }
5076         check_added_monitors!(nodes[1], 1);
5077         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5078         check_added_monitors!(nodes[1], 1);
5079         match msg_events[0] {
5080                 MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
5081                 _ => panic!("Unexpected event"),
5082         }
5083         match msg_events[1] {
5084                 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, .. } } => {
5085                         assert!(update_add_htlcs.is_empty());
5086                         assert!(update_fail_htlcs.is_empty());
5087                         assert_eq!(update_fulfill_htlcs.len(), 1);
5088                         assert!(update_fail_malformed_htlcs.is_empty());
5089                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5090                 },
5091                 _ => panic!("Unexpected event"),
5092         };
5093         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5094         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5095         mine_transaction(&nodes[1], &commitment_tx[0]);
5096         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5097         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5098         assert_eq!(b_txn.len(), 3);
5099         check_spends!(b_txn[1], chan_1.3);
5100         check_spends!(b_txn[2], b_txn[1]);
5101         check_spends!(b_txn[0], commitment_tx[0]);
5102         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5103         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5104         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5105
5106         check_closed_broadcast!(nodes[1], false);
5107         check_added_monitors!(nodes[1], 1);
5108 }
5109
5110 #[test]
5111 fn test_duplicate_payment_hash_one_failure_one_success() {
5112         // Topology : A --> B --> C
5113         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5114         let chanmon_cfgs = create_chanmon_cfgs(3);
5115         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5116         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5117         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5118
5119         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5120         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5121
5122         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5123         *nodes[0].network_payment_count.borrow_mut() -= 1;
5124         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5125
5126         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5127         assert_eq!(commitment_txn[0].input.len(), 1);
5128         check_spends!(commitment_txn[0], chan_2.3);
5129
5130         mine_transaction(&nodes[1], &commitment_txn[0]);
5131         check_closed_broadcast!(nodes[1], false);
5132         check_added_monitors!(nodes[1], 1);
5133
5134         let htlc_timeout_tx;
5135         { // Extract one of the two HTLC-Timeout transaction
5136                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5137                 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5138                 assert_eq!(node_txn.len(), 5);
5139                 check_spends!(node_txn[0], commitment_txn[0]);
5140                 assert_eq!(node_txn[0].input.len(), 1);
5141                 check_spends!(node_txn[1], commitment_txn[0]);
5142                 assert_eq!(node_txn[1].input.len(), 1);
5143                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5144                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5145                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5146                 check_spends!(node_txn[2], chan_2.3);
5147                 check_spends!(node_txn[3], node_txn[2]);
5148                 check_spends!(node_txn[4], node_txn[2]);
5149                 htlc_timeout_tx = node_txn[1].clone();
5150         }
5151
5152         nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5153         mine_transaction(&nodes[2], &commitment_txn[0]);
5154         check_added_monitors!(nodes[2], 3);
5155         let events = nodes[2].node.get_and_clear_pending_msg_events();
5156         match events[0] {
5157                 MessageSendEvent::UpdateHTLCs { .. } => {},
5158                 _ => panic!("Unexpected event"),
5159         }
5160         match events[1] {
5161                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5162                 _ => panic!("Unexepected event"),
5163         }
5164         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5165         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)
5166         check_spends!(htlc_success_txn[2], chan_2.3);
5167         check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5168         check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5169         assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5170         assert_eq!(htlc_success_txn[0].input.len(), 1);
5171         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5172         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5173         assert_eq!(htlc_success_txn[1].input.len(), 1);
5174         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5175         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5176         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5177         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5178
5179         mine_transaction(&nodes[1], &htlc_timeout_tx);
5180         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5181         expect_pending_htlcs_forwardable!(nodes[1]);
5182         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5183         assert!(htlc_updates.update_add_htlcs.is_empty());
5184         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5185         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5186         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5187         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5188         check_added_monitors!(nodes[1], 1);
5189
5190         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5191         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5192         {
5193                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5194                 let events = nodes[0].node.get_and_clear_pending_msg_events();
5195                 assert_eq!(events.len(), 1);
5196                 match events[0] {
5197                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
5198                         },
5199                         _ => { panic!("Unexpected event"); }
5200                 }
5201         }
5202         expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5203
5204         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5205         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5206         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5207         assert!(updates.update_add_htlcs.is_empty());
5208         assert!(updates.update_fail_htlcs.is_empty());
5209         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5210         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5211         assert!(updates.update_fail_malformed_htlcs.is_empty());
5212         check_added_monitors!(nodes[1], 1);
5213
5214         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5215         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5216
5217         let events = nodes[0].node.get_and_clear_pending_events();
5218         match events[0] {
5219                 Event::PaymentSent { ref payment_preimage } => {
5220                         assert_eq!(*payment_preimage, our_payment_preimage);
5221                 }
5222                 _ => panic!("Unexpected event"),
5223         }
5224 }
5225
5226 #[test]
5227 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5228         let chanmon_cfgs = create_chanmon_cfgs(2);
5229         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5230         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5231         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5232
5233         // Create some initial channels
5234         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5235
5236         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5237         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5238         assert_eq!(local_txn.len(), 1);
5239         assert_eq!(local_txn[0].input.len(), 1);
5240         check_spends!(local_txn[0], chan_1.3);
5241
5242         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5243         nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5244         check_added_monitors!(nodes[1], 1);
5245         mine_transaction(&nodes[1], &local_txn[0]);
5246         check_added_monitors!(nodes[1], 1);
5247         let events = nodes[1].node.get_and_clear_pending_msg_events();
5248         match events[0] {
5249                 MessageSendEvent::UpdateHTLCs { .. } => {},
5250                 _ => panic!("Unexpected event"),
5251         }
5252         match events[1] {
5253                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5254                 _ => panic!("Unexepected event"),
5255         }
5256         let node_tx = {
5257                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5258                 assert_eq!(node_txn.len(), 3);
5259                 assert_eq!(node_txn[0], node_txn[2]);
5260                 assert_eq!(node_txn[1], local_txn[0]);
5261                 assert_eq!(node_txn[0].input.len(), 1);
5262                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5263                 check_spends!(node_txn[0], local_txn[0]);
5264                 node_txn[0].clone()
5265         };
5266
5267         mine_transaction(&nodes[1], &node_tx);
5268         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5269
5270         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5271         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5272         assert_eq!(spend_txn.len(), 1);
5273         check_spends!(spend_txn[0], node_tx);
5274 }
5275
5276 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5277         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5278         // unrevoked commitment transaction.
5279         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5280         // a remote RAA before they could be failed backwards (and combinations thereof).
5281         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5282         // use the same payment hashes.
5283         // Thus, we use a six-node network:
5284         //
5285         // A \         / E
5286         //    - C - D -
5287         // B /         \ F
5288         // And test where C fails back to A/B when D announces its latest commitment transaction
5289         let chanmon_cfgs = create_chanmon_cfgs(6);
5290         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5291         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5292         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5293         let logger = test_utils::TestLogger::new();
5294
5295         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5296         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5297         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5298         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5299         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5300
5301         // Rebalance and check output sanity...
5302         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5303         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5304         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5305
5306         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5307         // 0th HTLC:
5308         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
5309         // 1st HTLC:
5310         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
5311         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5312         let our_node_id = &nodes[1].node.get_our_node_id();
5313         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();
5314         // 2nd HTLC:
5315         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
5316         // 3rd HTLC:
5317         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
5318         // 4th HTLC:
5319         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5320         // 5th HTLC:
5321         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5322         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();
5323         // 6th HTLC:
5324         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5325         // 7th HTLC:
5326         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5327
5328         // 8th HTLC:
5329         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5330         // 9th HTLC:
5331         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();
5332         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
5333
5334         // 10th HTLC:
5335         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
5336         // 11th HTLC:
5337         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();
5338         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5339
5340         // Double-check that six of the new HTLC were added
5341         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5342         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5343         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5344         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5345
5346         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5347         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5348         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5349         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5350         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5351         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5352         check_added_monitors!(nodes[4], 0);
5353         expect_pending_htlcs_forwardable!(nodes[4]);
5354         check_added_monitors!(nodes[4], 1);
5355
5356         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5357         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5358         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5359         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5360         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5361         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5362
5363         // Fail 3rd below-dust and 7th above-dust HTLCs
5364         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5365         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5366         check_added_monitors!(nodes[5], 0);
5367         expect_pending_htlcs_forwardable!(nodes[5]);
5368         check_added_monitors!(nodes[5], 1);
5369
5370         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5371         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5372         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5373         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5374
5375         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5376
5377         expect_pending_htlcs_forwardable!(nodes[3]);
5378         check_added_monitors!(nodes[3], 1);
5379         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5380         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5381         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5382         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5383         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5384         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5385         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5386         if deliver_last_raa {
5387                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5388         } else {
5389                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5390         }
5391
5392         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5393         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5394         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5395         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5396         //
5397         // We now broadcast the latest commitment transaction, which *should* result in failures for
5398         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5399         // the non-broadcast above-dust HTLCs.
5400         //
5401         // Alternatively, we may broadcast the previous commitment transaction, which should only
5402         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5403         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5404
5405         if announce_latest {
5406                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5407         } else {
5408                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5409         }
5410         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5411         check_closed_broadcast!(nodes[2], false);
5412         expect_pending_htlcs_forwardable!(nodes[2]);
5413         check_added_monitors!(nodes[2], 3);
5414
5415         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5416         assert_eq!(cs_msgs.len(), 2);
5417         let mut a_done = false;
5418         for msg in cs_msgs {
5419                 match msg {
5420                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5421                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5422                                 // should be failed-backwards here.
5423                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5424                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5425                                         for htlc in &updates.update_fail_htlcs {
5426                                                 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 });
5427                                         }
5428                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5429                                         assert!(!a_done);
5430                                         a_done = true;
5431                                         &nodes[0]
5432                                 } else {
5433                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5434                                         for htlc in &updates.update_fail_htlcs {
5435                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5436                                         }
5437                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5438                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5439                                         &nodes[1]
5440                                 };
5441                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5442                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5443                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5444                                 if announce_latest {
5445                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5446                                         if *node_id == nodes[0].node.get_our_node_id() {
5447                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5448                                         }
5449                                 }
5450                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5451                         },
5452                         _ => panic!("Unexpected event"),
5453                 }
5454         }
5455
5456         let as_events = nodes[0].node.get_and_clear_pending_events();
5457         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5458         let mut as_failds = HashSet::new();
5459         for event in as_events.iter() {
5460                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5461                         assert!(as_failds.insert(*payment_hash));
5462                         if *payment_hash != payment_hash_2 {
5463                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5464                         } else {
5465                                 assert!(!rejected_by_dest);
5466                         }
5467                 } else { panic!("Unexpected event"); }
5468         }
5469         assert!(as_failds.contains(&payment_hash_1));
5470         assert!(as_failds.contains(&payment_hash_2));
5471         if announce_latest {
5472                 assert!(as_failds.contains(&payment_hash_3));
5473                 assert!(as_failds.contains(&payment_hash_5));
5474         }
5475         assert!(as_failds.contains(&payment_hash_6));
5476
5477         let bs_events = nodes[1].node.get_and_clear_pending_events();
5478         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5479         let mut bs_failds = HashSet::new();
5480         for event in bs_events.iter() {
5481                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5482                         assert!(bs_failds.insert(*payment_hash));
5483                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5484                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5485                         } else {
5486                                 assert!(!rejected_by_dest);
5487                         }
5488                 } else { panic!("Unexpected event"); }
5489         }
5490         assert!(bs_failds.contains(&payment_hash_1));
5491         assert!(bs_failds.contains(&payment_hash_2));
5492         if announce_latest {
5493                 assert!(bs_failds.contains(&payment_hash_4));
5494         }
5495         assert!(bs_failds.contains(&payment_hash_5));
5496
5497         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5498         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5499         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5500         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5501         // PaymentFailureNetworkUpdates.
5502         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5503         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5504         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5505         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5506         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5507                 match event {
5508                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5509                         _ => panic!("Unexpected event"),
5510                 }
5511         }
5512 }
5513
5514 #[test]
5515 fn test_fail_backwards_latest_remote_announce_a() {
5516         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5517 }
5518
5519 #[test]
5520 fn test_fail_backwards_latest_remote_announce_b() {
5521         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5522 }
5523
5524 #[test]
5525 fn test_fail_backwards_previous_remote_announce() {
5526         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5527         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5528         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5529 }
5530
5531 #[test]
5532 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5533         let chanmon_cfgs = create_chanmon_cfgs(2);
5534         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5535         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5536         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5537
5538         // Create some initial channels
5539         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5540
5541         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5542         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5543         assert_eq!(local_txn[0].input.len(), 1);
5544         check_spends!(local_txn[0], chan_1.3);
5545
5546         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5547         mine_transaction(&nodes[0], &local_txn[0]);
5548         check_closed_broadcast!(nodes[0], false);
5549         check_added_monitors!(nodes[0], 1);
5550
5551         let htlc_timeout = {
5552                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5553                 assert_eq!(node_txn[0].input.len(), 1);
5554                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5555                 check_spends!(node_txn[0], local_txn[0]);
5556                 node_txn[0].clone()
5557         };
5558
5559         mine_transaction(&nodes[0], &htlc_timeout);
5560         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5561         expect_payment_failed!(nodes[0], our_payment_hash, true);
5562
5563         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5564         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5565         assert_eq!(spend_txn.len(), 3);
5566         check_spends!(spend_txn[0], local_txn[0]);
5567         check_spends!(spend_txn[1], htlc_timeout);
5568         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5569 }
5570
5571 #[test]
5572 fn test_key_derivation_params() {
5573         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5574         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5575         // let us re-derive the channel key set to then derive a delayed_payment_key.
5576
5577         let chanmon_cfgs = create_chanmon_cfgs(3);
5578
5579         // We manually create the node configuration to backup the seed.
5580         let seed = [42; 32];
5581         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5582         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);
5583         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 };
5584         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5585         node_cfgs.remove(0);
5586         node_cfgs.insert(0, node);
5587
5588         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5589         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5590
5591         // Create some initial channels
5592         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5593         // for node 0
5594         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5595         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5596         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5597
5598         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5599         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5600         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5601         assert_eq!(local_txn_1[0].input.len(), 1);
5602         check_spends!(local_txn_1[0], chan_1.3);
5603
5604         // We check funding pubkey are unique
5605         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]));
5606         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]));
5607         if from_0_funding_key_0 == from_1_funding_key_0
5608             || from_0_funding_key_0 == from_1_funding_key_1
5609             || from_0_funding_key_1 == from_1_funding_key_0
5610             || from_0_funding_key_1 == from_1_funding_key_1 {
5611                 panic!("Funding pubkeys aren't unique");
5612         }
5613
5614         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5615         mine_transaction(&nodes[0], &local_txn_1[0]);
5616         check_closed_broadcast!(nodes[0], false);
5617         check_added_monitors!(nodes[0], 1);
5618
5619         let htlc_timeout = {
5620                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5621                 assert_eq!(node_txn[0].input.len(), 1);
5622                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5623                 check_spends!(node_txn[0], local_txn_1[0]);
5624                 node_txn[0].clone()
5625         };
5626
5627         mine_transaction(&nodes[0], &htlc_timeout);
5628         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5629         expect_payment_failed!(nodes[0], our_payment_hash, true);
5630
5631         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5632         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5633         let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5634         assert_eq!(spend_txn.len(), 3);
5635         check_spends!(spend_txn[0], local_txn_1[0]);
5636         check_spends!(spend_txn[1], htlc_timeout);
5637         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5638 }
5639
5640 #[test]
5641 fn test_static_output_closing_tx() {
5642         let chanmon_cfgs = create_chanmon_cfgs(2);
5643         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5644         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5645         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5646
5647         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5648
5649         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5650         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5651
5652         mine_transaction(&nodes[0], &closing_tx);
5653         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5654
5655         let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5656         assert_eq!(spend_txn.len(), 1);
5657         check_spends!(spend_txn[0], closing_tx);
5658
5659         mine_transaction(&nodes[1], &closing_tx);
5660         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5661
5662         let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5663         assert_eq!(spend_txn.len(), 1);
5664         check_spends!(spend_txn[0], closing_tx);
5665 }
5666
5667 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5668         let chanmon_cfgs = create_chanmon_cfgs(2);
5669         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5670         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5671         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5672         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5673
5674         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5675
5676         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5677         // present in B's local commitment transaction, but none of A's commitment transactions.
5678         assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5679         check_added_monitors!(nodes[1], 1);
5680
5681         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5682         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5683         let events = nodes[0].node.get_and_clear_pending_events();
5684         assert_eq!(events.len(), 1);
5685         match events[0] {
5686                 Event::PaymentSent { payment_preimage } => {
5687                         assert_eq!(payment_preimage, our_payment_preimage);
5688                 },
5689                 _ => panic!("Unexpected event"),
5690         }
5691
5692         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5693         check_added_monitors!(nodes[0], 1);
5694         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5695         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5696         check_added_monitors!(nodes[1], 1);
5697
5698         let starting_block = nodes[1].best_block_info();
5699         let mut block = Block {
5700                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5701                 txdata: vec![],
5702         };
5703         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5704                 connect_block(&nodes[1], &block);
5705                 block.header.prev_blockhash = block.block_hash();
5706         }
5707         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5708         check_closed_broadcast!(nodes[1], false);
5709         check_added_monitors!(nodes[1], 1);
5710 }
5711
5712 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5713         let chanmon_cfgs = create_chanmon_cfgs(2);
5714         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5715         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5716         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5717         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5718         let logger = test_utils::TestLogger::new();
5719
5720         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5721         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5722         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();
5723         nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5724         check_added_monitors!(nodes[0], 1);
5725
5726         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5727
5728         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5729         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5730         // to "time out" the HTLC.
5731
5732         let starting_block = nodes[1].best_block_info();
5733         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5734
5735         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5736                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5737                 header.prev_blockhash = header.block_hash();
5738         }
5739         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5740         check_closed_broadcast!(nodes[0], false);
5741         check_added_monitors!(nodes[0], 1);
5742 }
5743
5744 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5745         let chanmon_cfgs = create_chanmon_cfgs(3);
5746         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5747         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5748         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5749         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5750
5751         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5752         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5753         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5754         // actually revoked.
5755         let htlc_value = if use_dust { 50000 } else { 3000000 };
5756         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5757         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5758         expect_pending_htlcs_forwardable!(nodes[1]);
5759         check_added_monitors!(nodes[1], 1);
5760
5761         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5762         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5763         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5764         check_added_monitors!(nodes[0], 1);
5765         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5766         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5767         check_added_monitors!(nodes[1], 1);
5768         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5769         check_added_monitors!(nodes[1], 1);
5770         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5771
5772         if check_revoke_no_close {
5773                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5774                 check_added_monitors!(nodes[0], 1);
5775         }
5776
5777         let starting_block = nodes[1].best_block_info();
5778         let mut block = Block {
5779                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5780                 txdata: vec![],
5781         };
5782         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5783                 connect_block(&nodes[0], &block);
5784                 block.header.prev_blockhash = block.block_hash();
5785         }
5786         if !check_revoke_no_close {
5787                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5788                 check_closed_broadcast!(nodes[0], false);
5789                 check_added_monitors!(nodes[0], 1);
5790         } else {
5791                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5792         }
5793 }
5794
5795 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5796 // There are only a few cases to test here:
5797 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5798 //    broadcastable commitment transactions result in channel closure,
5799 //  * its included in an unrevoked-but-previous remote commitment transaction,
5800 //  * its included in the latest remote or local commitment transactions.
5801 // We test each of the three possible commitment transactions individually and use both dust and
5802 // non-dust HTLCs.
5803 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5804 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5805 // tested for at least one of the cases in other tests.
5806 #[test]
5807 fn htlc_claim_single_commitment_only_a() {
5808         do_htlc_claim_local_commitment_only(true);
5809         do_htlc_claim_local_commitment_only(false);
5810
5811         do_htlc_claim_current_remote_commitment_only(true);
5812         do_htlc_claim_current_remote_commitment_only(false);
5813 }
5814
5815 #[test]
5816 fn htlc_claim_single_commitment_only_b() {
5817         do_htlc_claim_previous_remote_commitment_only(true, false);
5818         do_htlc_claim_previous_remote_commitment_only(false, false);
5819         do_htlc_claim_previous_remote_commitment_only(true, true);
5820         do_htlc_claim_previous_remote_commitment_only(false, true);
5821 }
5822
5823 #[test]
5824 #[should_panic]
5825 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5826         let chanmon_cfgs = create_chanmon_cfgs(2);
5827         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5828         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5829         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5830         //Force duplicate channel ids
5831         for node in nodes.iter() {
5832                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5833         }
5834
5835         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5836         let channel_value_satoshis=10000;
5837         let push_msat=10001;
5838         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5839         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5840         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5841
5842         //Create a second channel with a channel_id collision
5843         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5844 }
5845
5846 #[test]
5847 fn bolt2_open_channel_sending_node_checks_part2() {
5848         let chanmon_cfgs = create_chanmon_cfgs(2);
5849         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5850         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5851         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5852
5853         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5854         let channel_value_satoshis=2^24;
5855         let push_msat=10001;
5856         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5857
5858         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5859         let channel_value_satoshis=10000;
5860         // Test when push_msat is equal to 1000 * funding_satoshis.
5861         let push_msat=1000*channel_value_satoshis+1;
5862         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5863
5864         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5865         let channel_value_satoshis=10000;
5866         let push_msat=10001;
5867         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
5868         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5869         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5870
5871         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5872         // 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
5873         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5874
5875         // 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.
5876         assert!(BREAKDOWN_TIMEOUT>0);
5877         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5878
5879         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5880         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5881         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5882
5883         // 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.
5884         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5885         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5886         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5887         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5888         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5889 }
5890
5891 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5892 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5893 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5894 // is no longer affordable once it's freed.
5895 #[test]
5896 fn test_fail_holding_cell_htlc_upon_free() {
5897         let chanmon_cfgs = create_chanmon_cfgs(2);
5898         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5899         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5900         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5901         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5902         let logger = test_utils::TestLogger::new();
5903
5904         // First nodes[0] generates an update_fee, setting the channel's
5905         // pending_update_fee.
5906         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
5907         check_added_monitors!(nodes[0], 1);
5908
5909         let events = nodes[0].node.get_and_clear_pending_msg_events();
5910         assert_eq!(events.len(), 1);
5911         let (update_msg, commitment_signed) = match events[0] {
5912                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5913                         (update_fee.as_ref(), commitment_signed)
5914                 },
5915                 _ => panic!("Unexpected event"),
5916         };
5917
5918         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5919
5920         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5921         let channel_reserve = chan_stat.channel_reserve_msat;
5922         let feerate = get_feerate!(nodes[0], chan.2);
5923
5924         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5925         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5926         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5927         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5928         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();
5929
5930         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5931         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5932         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5933         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5934
5935         // Flush the pending fee update.
5936         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5937         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5938         check_added_monitors!(nodes[1], 1);
5939         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5940         check_added_monitors!(nodes[0], 1);
5941
5942         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5943         // HTLC, but now that the fee has been raised the payment will now fail, causing
5944         // us to surface its failure to the user.
5945         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5946         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5947         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
5948         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);
5949         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5950
5951         // Check that the payment failed to be sent out.
5952         let events = nodes[0].node.get_and_clear_pending_events();
5953         assert_eq!(events.len(), 1);
5954         match &events[0] {
5955                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
5956                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5957                         assert_eq!(*rejected_by_dest, false);
5958                         assert_eq!(*error_code, None);
5959                         assert_eq!(*error_data, None);
5960                 },
5961                 _ => panic!("Unexpected event"),
5962         }
5963 }
5964
5965 // Test that if multiple HTLCs are released from the holding cell and one is
5966 // valid but the other is no longer valid upon release, the valid HTLC can be
5967 // successfully completed while the other one fails as expected.
5968 #[test]
5969 fn test_free_and_fail_holding_cell_htlcs() {
5970         let chanmon_cfgs = create_chanmon_cfgs(2);
5971         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5972         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5973         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5974         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5975         let logger = test_utils::TestLogger::new();
5976
5977         // First nodes[0] generates an update_fee, setting the channel's
5978         // pending_update_fee.
5979         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
5980         check_added_monitors!(nodes[0], 1);
5981
5982         let events = nodes[0].node.get_and_clear_pending_msg_events();
5983         assert_eq!(events.len(), 1);
5984         let (update_msg, commitment_signed) = match events[0] {
5985                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5986                         (update_fee.as_ref(), commitment_signed)
5987                 },
5988                 _ => panic!("Unexpected event"),
5989         };
5990
5991         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5992
5993         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5994         let channel_reserve = chan_stat.channel_reserve_msat;
5995         let feerate = get_feerate!(nodes[0], chan.2);
5996
5997         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5998         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
5999         let amt_1 = 20000;
6000         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6001         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6002         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6003         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();
6004         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();
6005
6006         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6007         nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6008         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6009         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6010         nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6011         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6012         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6013
6014         // Flush the pending fee update.
6015         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6016         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6017         check_added_monitors!(nodes[1], 1);
6018         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6019         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6020         check_added_monitors!(nodes[0], 2);
6021
6022         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6023         // but now that the fee has been raised the second payment will now fail, causing us
6024         // to surface its failure to the user. The first payment should succeed.
6025         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6026         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6027         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6028         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);
6029         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6030
6031         // Check that the second payment failed to be sent out.
6032         let events = nodes[0].node.get_and_clear_pending_events();
6033         assert_eq!(events.len(), 1);
6034         match &events[0] {
6035                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6036                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6037                         assert_eq!(*rejected_by_dest, false);
6038                         assert_eq!(*error_code, None);
6039                         assert_eq!(*error_data, None);
6040                 },
6041                 _ => panic!("Unexpected event"),
6042         }
6043
6044         // Complete the first payment and the RAA from the fee update.
6045         let (payment_event, send_raa_event) = {
6046                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6047                 assert_eq!(msgs.len(), 2);
6048                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6049         };
6050         let raa = match send_raa_event {
6051                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6052                 _ => panic!("Unexpected event"),
6053         };
6054         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6055         check_added_monitors!(nodes[1], 1);
6056         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6057         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6058         let events = nodes[1].node.get_and_clear_pending_events();
6059         assert_eq!(events.len(), 1);
6060         match events[0] {
6061                 Event::PendingHTLCsForwardable { .. } => {},
6062                 _ => panic!("Unexpected event"),
6063         }
6064         nodes[1].node.process_pending_htlc_forwards();
6065         let events = nodes[1].node.get_and_clear_pending_events();
6066         assert_eq!(events.len(), 1);
6067         match events[0] {
6068                 Event::PaymentReceived { .. } => {},
6069                 _ => panic!("Unexpected event"),
6070         }
6071         nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6072         check_added_monitors!(nodes[1], 1);
6073         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6074         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6075         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6076         let events = nodes[0].node.get_and_clear_pending_events();
6077         assert_eq!(events.len(), 1);
6078         match events[0] {
6079                 Event::PaymentSent { ref payment_preimage } => {
6080                         assert_eq!(*payment_preimage, payment_preimage_1);
6081                 }
6082                 _ => panic!("Unexpected event"),
6083         }
6084 }
6085
6086 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6087 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6088 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6089 // once it's freed.
6090 #[test]
6091 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6092         let chanmon_cfgs = create_chanmon_cfgs(3);
6093         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6094         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6095         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6096         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6097         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6098         let logger = test_utils::TestLogger::new();
6099
6100         // First nodes[1] generates an update_fee, setting the channel's
6101         // pending_update_fee.
6102         nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6103         check_added_monitors!(nodes[1], 1);
6104
6105         let events = nodes[1].node.get_and_clear_pending_msg_events();
6106         assert_eq!(events.len(), 1);
6107         let (update_msg, commitment_signed) = match events[0] {
6108                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6109                         (update_fee.as_ref(), commitment_signed)
6110                 },
6111                 _ => panic!("Unexpected event"),
6112         };
6113
6114         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6115
6116         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6117         let channel_reserve = chan_stat.channel_reserve_msat;
6118         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6119
6120         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6121         let feemsat = 239;
6122         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6123         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6124         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6125         let payment_event = {
6126                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6127                 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();
6128                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6129                 check_added_monitors!(nodes[0], 1);
6130
6131                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6132                 assert_eq!(events.len(), 1);
6133
6134                 SendEvent::from_event(events.remove(0))
6135         };
6136         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6137         check_added_monitors!(nodes[1], 0);
6138         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6139         expect_pending_htlcs_forwardable!(nodes[1]);
6140
6141         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6142         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6143
6144         // Flush the pending fee update.
6145         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6146         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6147         check_added_monitors!(nodes[2], 1);
6148         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6149         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6150         check_added_monitors!(nodes[1], 2);
6151
6152         // A final RAA message is generated to finalize the fee update.
6153         let events = nodes[1].node.get_and_clear_pending_msg_events();
6154         assert_eq!(events.len(), 1);
6155
6156         let raa_msg = match &events[0] {
6157                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6158                         msg.clone()
6159                 },
6160                 _ => panic!("Unexpected event"),
6161         };
6162
6163         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6164         check_added_monitors!(nodes[2], 1);
6165         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6166
6167         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6168         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6169         assert_eq!(process_htlc_forwards_event.len(), 1);
6170         match &process_htlc_forwards_event[0] {
6171                 &Event::PendingHTLCsForwardable { .. } => {},
6172                 _ => panic!("Unexpected event"),
6173         }
6174
6175         // In response, we call ChannelManager's process_pending_htlc_forwards
6176         nodes[1].node.process_pending_htlc_forwards();
6177         check_added_monitors!(nodes[1], 1);
6178
6179         // This causes the HTLC to be failed backwards.
6180         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6181         assert_eq!(fail_event.len(), 1);
6182         let (fail_msg, commitment_signed) = match &fail_event[0] {
6183                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6184                         assert_eq!(updates.update_add_htlcs.len(), 0);
6185                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6186                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6187                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6188                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6189                 },
6190                 _ => panic!("Unexpected event"),
6191         };
6192
6193         // Pass the failure messages back to nodes[0].
6194         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6195         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6196
6197         // Complete the HTLC failure+removal process.
6198         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6199         check_added_monitors!(nodes[0], 1);
6200         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6201         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6202         check_added_monitors!(nodes[1], 2);
6203         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6204         assert_eq!(final_raa_event.len(), 1);
6205         let raa = match &final_raa_event[0] {
6206                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6207                 _ => panic!("Unexpected event"),
6208         };
6209         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6210         let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6211         assert_eq!(fail_msg_event.len(), 1);
6212         match &fail_msg_event[0] {
6213                 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6214                 _ => panic!("Unexpected event"),
6215         }
6216         let failure_event = nodes[0].node.get_and_clear_pending_events();
6217         assert_eq!(failure_event.len(), 1);
6218         match &failure_event[0] {
6219                 &Event::PaymentFailed { rejected_by_dest, .. } => {
6220                         assert!(!rejected_by_dest);
6221                 },
6222                 _ => panic!("Unexpected event"),
6223         }
6224         check_added_monitors!(nodes[0], 1);
6225 }
6226
6227 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6228 // 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.
6229 //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.
6230
6231 #[test]
6232 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6233         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6234         let chanmon_cfgs = create_chanmon_cfgs(2);
6235         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6236         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6237         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6238         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6239
6240         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6241         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6242         let logger = test_utils::TestLogger::new();
6243         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();
6244         route.paths[0][0].fee_msat = 100;
6245
6246         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6247                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6248         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6249         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6250 }
6251
6252 #[test]
6253 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6254         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6255         let chanmon_cfgs = create_chanmon_cfgs(2);
6256         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6257         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6258         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6259         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6260         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6261
6262         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6263         let logger = test_utils::TestLogger::new();
6264         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();
6265         route.paths[0][0].fee_msat = 0;
6266         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6267                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6268
6269         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6270         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6271 }
6272
6273 #[test]
6274 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6275         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6276         let chanmon_cfgs = create_chanmon_cfgs(2);
6277         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6278         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6279         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6280         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6281
6282         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6283         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6284         let logger = test_utils::TestLogger::new();
6285         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6286         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6287         check_added_monitors!(nodes[0], 1);
6288         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6289         updates.update_add_htlcs[0].amount_msat = 0;
6290
6291         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6292         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6293         check_closed_broadcast!(nodes[1], true).unwrap();
6294         check_added_monitors!(nodes[1], 1);
6295 }
6296
6297 #[test]
6298 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6299         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6300         //It is enforced when constructing a route.
6301         let chanmon_cfgs = create_chanmon_cfgs(2);
6302         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6303         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6304         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6305         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6306         let logger = test_utils::TestLogger::new();
6307
6308         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6309
6310         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6311         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();
6312         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6313                 assert_eq!(err, &"Channel CLTV overflowed?"));
6314 }
6315
6316 #[test]
6317 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6318         //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.
6319         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6320         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6321         let chanmon_cfgs = create_chanmon_cfgs(2);
6322         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6323         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6324         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6325         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6326         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6327
6328         let logger = test_utils::TestLogger::new();
6329         for i in 0..max_accepted_htlcs {
6330                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6331                 let payment_event = {
6332                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6333                         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();
6334                         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6335                         check_added_monitors!(nodes[0], 1);
6336
6337                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6338                         assert_eq!(events.len(), 1);
6339                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6340                                 assert_eq!(htlcs[0].htlc_id, i);
6341                         } else {
6342                                 assert!(false);
6343                         }
6344                         SendEvent::from_event(events.remove(0))
6345                 };
6346                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6347                 check_added_monitors!(nodes[1], 0);
6348                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6349
6350                 expect_pending_htlcs_forwardable!(nodes[1]);
6351                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6352         }
6353         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6354         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6355         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();
6356         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6357                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6358
6359         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6360         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6361 }
6362
6363 #[test]
6364 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6365         //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.
6366         let chanmon_cfgs = create_chanmon_cfgs(2);
6367         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6368         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6369         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6370         let channel_value = 100000;
6371         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6372         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6373
6374         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6375
6376         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6377         // Manually create a route over our max in flight (which our router normally automatically
6378         // limits us to.
6379         let route = Route { paths: vec![vec![RouteHop {
6380            pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6381            short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6382            fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6383         }]] };
6384         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6385                 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)));
6386
6387         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6388         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);
6389
6390         send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6391 }
6392
6393 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6394 #[test]
6395 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6396         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6397         let chanmon_cfgs = create_chanmon_cfgs(2);
6398         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6399         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6400         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6401         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6402         let htlc_minimum_msat: u64;
6403         {
6404                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6405                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6406                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6407         }
6408
6409         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6410         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6411         let logger = test_utils::TestLogger::new();
6412         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();
6413         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6414         check_added_monitors!(nodes[0], 1);
6415         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6416         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6417         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6418         assert!(nodes[1].node.list_channels().is_empty());
6419         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6420         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()));
6421         check_added_monitors!(nodes[1], 1);
6422 }
6423
6424 #[test]
6425 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6426         //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
6427         let chanmon_cfgs = create_chanmon_cfgs(2);
6428         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6429         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6430         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6431         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6432         let logger = test_utils::TestLogger::new();
6433
6434         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6435         let channel_reserve = chan_stat.channel_reserve_msat;
6436         let feerate = get_feerate!(nodes[0], chan.2);
6437         // The 2* and +1 are for the fee spike reserve.
6438         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6439
6440         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6441         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6442         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6443         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();
6444         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6445         check_added_monitors!(nodes[0], 1);
6446         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6447
6448         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6449         // at this time channel-initiatee receivers are not required to enforce that senders
6450         // respect the fee_spike_reserve.
6451         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6452         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6453
6454         assert!(nodes[1].node.list_channels().is_empty());
6455         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6456         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6457         check_added_monitors!(nodes[1], 1);
6458 }
6459
6460 #[test]
6461 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6462         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6463         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6464         let chanmon_cfgs = create_chanmon_cfgs(2);
6465         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6466         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6467         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6468         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6469         let logger = test_utils::TestLogger::new();
6470
6471         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6472         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6473
6474         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6475         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();
6476
6477         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6478         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6479         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6480         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6481
6482         let mut msg = msgs::UpdateAddHTLC {
6483                 channel_id: chan.2,
6484                 htlc_id: 0,
6485                 amount_msat: 1000,
6486                 payment_hash: our_payment_hash,
6487                 cltv_expiry: htlc_cltv,
6488                 onion_routing_packet: onion_packet.clone(),
6489         };
6490
6491         for i in 0..super::channel::OUR_MAX_HTLCS {
6492                 msg.htlc_id = i as u64;
6493                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6494         }
6495         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6496         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6497
6498         assert!(nodes[1].node.list_channels().is_empty());
6499         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6500         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6501         check_added_monitors!(nodes[1], 1);
6502 }
6503
6504 #[test]
6505 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6506         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6507         let chanmon_cfgs = create_chanmon_cfgs(2);
6508         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6509         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6510         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6511         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6512         let logger = test_utils::TestLogger::new();
6513
6514         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6515         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6516         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();
6517         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6518         check_added_monitors!(nodes[0], 1);
6519         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6520         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6521         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6522
6523         assert!(nodes[1].node.list_channels().is_empty());
6524         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6525         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6526         check_added_monitors!(nodes[1], 1);
6527 }
6528
6529 #[test]
6530 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6531         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6532         let chanmon_cfgs = create_chanmon_cfgs(2);
6533         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6534         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6535         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6536         let logger = test_utils::TestLogger::new();
6537
6538         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6539         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6540         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6541         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();
6542         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6543         check_added_monitors!(nodes[0], 1);
6544         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6545         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6546         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6547
6548         assert!(nodes[1].node.list_channels().is_empty());
6549         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6550         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6551         check_added_monitors!(nodes[1], 1);
6552 }
6553
6554 #[test]
6555 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6556         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6557         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6558         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6559         let chanmon_cfgs = create_chanmon_cfgs(2);
6560         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6561         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6562         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6563         let logger = test_utils::TestLogger::new();
6564
6565         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6566         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6567         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6568         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();
6569         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6570         check_added_monitors!(nodes[0], 1);
6571         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6572         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6573
6574         //Disconnect and Reconnect
6575         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6576         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6577         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6578         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6579         assert_eq!(reestablish_1.len(), 1);
6580         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6581         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6582         assert_eq!(reestablish_2.len(), 1);
6583         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6584         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6585         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6586         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6587
6588         //Resend HTLC
6589         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6590         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6591         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6592         check_added_monitors!(nodes[1], 1);
6593         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6594
6595         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6596
6597         assert!(nodes[1].node.list_channels().is_empty());
6598         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6599         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6600         check_added_monitors!(nodes[1], 1);
6601 }
6602
6603 #[test]
6604 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6605         //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.
6606
6607         let chanmon_cfgs = create_chanmon_cfgs(2);
6608         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6609         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6610         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6611         let logger = test_utils::TestLogger::new();
6612         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6613         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6614         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6615         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();
6616         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6617
6618         check_added_monitors!(nodes[0], 1);
6619         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6620         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6621
6622         let update_msg = msgs::UpdateFulfillHTLC{
6623                 channel_id: chan.2,
6624                 htlc_id: 0,
6625                 payment_preimage: our_payment_preimage,
6626         };
6627
6628         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6629
6630         assert!(nodes[0].node.list_channels().is_empty());
6631         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6632         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()));
6633         check_added_monitors!(nodes[0], 1);
6634 }
6635
6636 #[test]
6637 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6638         //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.
6639
6640         let chanmon_cfgs = create_chanmon_cfgs(2);
6641         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6642         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6643         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6644         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6645         let logger = test_utils::TestLogger::new();
6646
6647         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6648         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6649         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();
6650         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6651         check_added_monitors!(nodes[0], 1);
6652         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6653         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6654
6655         let update_msg = msgs::UpdateFailHTLC{
6656                 channel_id: chan.2,
6657                 htlc_id: 0,
6658                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6659         };
6660
6661         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6662
6663         assert!(nodes[0].node.list_channels().is_empty());
6664         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6665         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()));
6666         check_added_monitors!(nodes[0], 1);
6667 }
6668
6669 #[test]
6670 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6671         //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.
6672
6673         let chanmon_cfgs = create_chanmon_cfgs(2);
6674         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6675         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6676         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6677         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6678         let logger = test_utils::TestLogger::new();
6679
6680         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6681         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6682         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();
6683         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6684         check_added_monitors!(nodes[0], 1);
6685         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6686         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6687         let update_msg = msgs::UpdateFailMalformedHTLC{
6688                 channel_id: chan.2,
6689                 htlc_id: 0,
6690                 sha256_of_onion: [1; 32],
6691                 failure_code: 0x8000,
6692         };
6693
6694         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6695
6696         assert!(nodes[0].node.list_channels().is_empty());
6697         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6698         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()));
6699         check_added_monitors!(nodes[0], 1);
6700 }
6701
6702 #[test]
6703 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6704         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6705
6706         let chanmon_cfgs = create_chanmon_cfgs(2);
6707         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6708         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6709         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6710         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6711
6712         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6713
6714         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6715         check_added_monitors!(nodes[1], 1);
6716
6717         let events = nodes[1].node.get_and_clear_pending_msg_events();
6718         assert_eq!(events.len(), 1);
6719         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6720                 match events[0] {
6721                         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, .. } } => {
6722                                 assert!(update_add_htlcs.is_empty());
6723                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6724                                 assert!(update_fail_htlcs.is_empty());
6725                                 assert!(update_fail_malformed_htlcs.is_empty());
6726                                 assert!(update_fee.is_none());
6727                                 update_fulfill_htlcs[0].clone()
6728                         },
6729                         _ => panic!("Unexpected event"),
6730                 }
6731         };
6732
6733         update_fulfill_msg.htlc_id = 1;
6734
6735         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6736
6737         assert!(nodes[0].node.list_channels().is_empty());
6738         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6739         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6740         check_added_monitors!(nodes[0], 1);
6741 }
6742
6743 #[test]
6744 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6745         //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.
6746
6747         let chanmon_cfgs = create_chanmon_cfgs(2);
6748         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6749         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6750         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6751         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6752
6753         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6754
6755         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6756         check_added_monitors!(nodes[1], 1);
6757
6758         let events = nodes[1].node.get_and_clear_pending_msg_events();
6759         assert_eq!(events.len(), 1);
6760         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6761                 match events[0] {
6762                         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, .. } } => {
6763                                 assert!(update_add_htlcs.is_empty());
6764                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6765                                 assert!(update_fail_htlcs.is_empty());
6766                                 assert!(update_fail_malformed_htlcs.is_empty());
6767                                 assert!(update_fee.is_none());
6768                                 update_fulfill_htlcs[0].clone()
6769                         },
6770                         _ => panic!("Unexpected event"),
6771                 }
6772         };
6773
6774         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6775
6776         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6777
6778         assert!(nodes[0].node.list_channels().is_empty());
6779         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6780         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6781         check_added_monitors!(nodes[0], 1);
6782 }
6783
6784 #[test]
6785 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6786         //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.
6787
6788         let chanmon_cfgs = create_chanmon_cfgs(2);
6789         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6790         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6791         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6792         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6793         let logger = test_utils::TestLogger::new();
6794
6795         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6796         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6797         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();
6798         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6799         check_added_monitors!(nodes[0], 1);
6800
6801         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6802         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6803
6804         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6805         check_added_monitors!(nodes[1], 0);
6806         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6807
6808         let events = nodes[1].node.get_and_clear_pending_msg_events();
6809
6810         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6811                 match events[0] {
6812                         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, .. } } => {
6813                                 assert!(update_add_htlcs.is_empty());
6814                                 assert!(update_fulfill_htlcs.is_empty());
6815                                 assert!(update_fail_htlcs.is_empty());
6816                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6817                                 assert!(update_fee.is_none());
6818                                 update_fail_malformed_htlcs[0].clone()
6819                         },
6820                         _ => panic!("Unexpected event"),
6821                 }
6822         };
6823         update_msg.failure_code &= !0x8000;
6824         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6825
6826         assert!(nodes[0].node.list_channels().is_empty());
6827         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6828         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6829         check_added_monitors!(nodes[0], 1);
6830 }
6831
6832 #[test]
6833 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6834         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6835         //    * 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.
6836
6837         let chanmon_cfgs = create_chanmon_cfgs(3);
6838         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6839         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6840         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6841         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6842         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6843         let logger = test_utils::TestLogger::new();
6844
6845         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6846
6847         //First hop
6848         let mut payment_event = {
6849                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6850                 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();
6851                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6852                 check_added_monitors!(nodes[0], 1);
6853                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6854                 assert_eq!(events.len(), 1);
6855                 SendEvent::from_event(events.remove(0))
6856         };
6857         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6858         check_added_monitors!(nodes[1], 0);
6859         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6860         expect_pending_htlcs_forwardable!(nodes[1]);
6861         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6862         assert_eq!(events_2.len(), 1);
6863         check_added_monitors!(nodes[1], 1);
6864         payment_event = SendEvent::from_event(events_2.remove(0));
6865         assert_eq!(payment_event.msgs.len(), 1);
6866
6867         //Second Hop
6868         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6869         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6870         check_added_monitors!(nodes[2], 0);
6871         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6872
6873         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6874         assert_eq!(events_3.len(), 1);
6875         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6876                 match events_3[0] {
6877                         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 } } => {
6878                                 assert!(update_add_htlcs.is_empty());
6879                                 assert!(update_fulfill_htlcs.is_empty());
6880                                 assert!(update_fail_htlcs.is_empty());
6881                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6882                                 assert!(update_fee.is_none());
6883                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6884                         },
6885                         _ => panic!("Unexpected event"),
6886                 }
6887         };
6888
6889         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6890
6891         check_added_monitors!(nodes[1], 0);
6892         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6893         expect_pending_htlcs_forwardable!(nodes[1]);
6894         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6895         assert_eq!(events_4.len(), 1);
6896
6897         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6898         match events_4[0] {
6899                 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, .. } } => {
6900                         assert!(update_add_htlcs.is_empty());
6901                         assert!(update_fulfill_htlcs.is_empty());
6902                         assert_eq!(update_fail_htlcs.len(), 1);
6903                         assert!(update_fail_malformed_htlcs.is_empty());
6904                         assert!(update_fee.is_none());
6905                 },
6906                 _ => panic!("Unexpected event"),
6907         };
6908
6909         check_added_monitors!(nodes[1], 1);
6910 }
6911
6912 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6913         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6914         // 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
6915         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6916
6917         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6918         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6919         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6920         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6921         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6922         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6923
6924         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6925
6926         // We route 2 dust-HTLCs between A and B
6927         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6928         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6929         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6930
6931         // Cache one local commitment tx as previous
6932         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6933
6934         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6935         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
6936         check_added_monitors!(nodes[1], 0);
6937         expect_pending_htlcs_forwardable!(nodes[1]);
6938         check_added_monitors!(nodes[1], 1);
6939
6940         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6941         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6942         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6943         check_added_monitors!(nodes[0], 1);
6944
6945         // Cache one local commitment tx as lastest
6946         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6947
6948         let events = nodes[0].node.get_and_clear_pending_msg_events();
6949         match events[0] {
6950                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6951                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6952                 },
6953                 _ => panic!("Unexpected event"),
6954         }
6955         match events[1] {
6956                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6957                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6958                 },
6959                 _ => panic!("Unexpected event"),
6960         }
6961
6962         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6963         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6964         if announce_latest {
6965                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6966         } else {
6967                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6968         }
6969
6970         check_closed_broadcast!(nodes[0], false);
6971         check_added_monitors!(nodes[0], 1);
6972
6973         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6974         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6975         let events = nodes[0].node.get_and_clear_pending_events();
6976         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
6977         assert_eq!(events.len(), 2);
6978         let mut first_failed = false;
6979         for event in events {
6980                 match event {
6981                         Event::PaymentFailed { payment_hash, .. } => {
6982                                 if payment_hash == payment_hash_1 {
6983                                         assert!(!first_failed);
6984                                         first_failed = true;
6985                                 } else {
6986                                         assert_eq!(payment_hash, payment_hash_2);
6987                                 }
6988                         }
6989                         _ => panic!("Unexpected event"),
6990                 }
6991         }
6992 }
6993
6994 #[test]
6995 fn test_failure_delay_dust_htlc_local_commitment() {
6996         do_test_failure_delay_dust_htlc_local_commitment(true);
6997         do_test_failure_delay_dust_htlc_local_commitment(false);
6998 }
6999
7000 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7001         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7002         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7003         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7004         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7005         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7006         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7007
7008         let chanmon_cfgs = create_chanmon_cfgs(3);
7009         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7010         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7011         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7012         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7013
7014         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7015
7016         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7017         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7018
7019         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7020         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7021
7022         // We revoked bs_commitment_tx
7023         if revoked {
7024                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7025                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7026         }
7027
7028         let mut timeout_tx = Vec::new();
7029         if local {
7030                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7031                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7032                 check_closed_broadcast!(nodes[0], false);
7033                 check_added_monitors!(nodes[0], 1);
7034                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7035                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7036                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7037                 expect_payment_failed!(nodes[0], dust_hash, true);
7038                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7039                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7040                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7041                 mine_transaction(&nodes[0], &timeout_tx[0]);
7042                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7043                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7044         } else {
7045                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7046                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7047                 check_closed_broadcast!(nodes[0], false);
7048                 check_added_monitors!(nodes[0], 1);
7049                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7050                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7051                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7052                 if !revoked {
7053                         expect_payment_failed!(nodes[0], dust_hash, true);
7054                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7055                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7056                         mine_transaction(&nodes[0], &timeout_tx[0]);
7057                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7058                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7059                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7060                 } else {
7061                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7062                         // commitment tx
7063                         let events = nodes[0].node.get_and_clear_pending_events();
7064                         assert_eq!(events.len(), 2);
7065                         let first;
7066                         match events[0] {
7067                                 Event::PaymentFailed { payment_hash, .. } => {
7068                                         if payment_hash == dust_hash { first = true; }
7069                                         else { first = false; }
7070                                 },
7071                                 _ => panic!("Unexpected event"),
7072                         }
7073                         match events[1] {
7074                                 Event::PaymentFailed { payment_hash, .. } => {
7075                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7076                                         else { assert_eq!(payment_hash, dust_hash); }
7077                                 },
7078                                 _ => panic!("Unexpected event"),
7079                         }
7080                 }
7081         }
7082 }
7083
7084 #[test]
7085 fn test_sweep_outbound_htlc_failure_update() {
7086         do_test_sweep_outbound_htlc_failure_update(false, true);
7087         do_test_sweep_outbound_htlc_failure_update(false, false);
7088         do_test_sweep_outbound_htlc_failure_update(true, false);
7089 }
7090
7091 #[test]
7092 fn test_upfront_shutdown_script() {
7093         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7094         // enforce it at shutdown message
7095
7096         let mut config = UserConfig::default();
7097         config.channel_options.announced_channel = true;
7098         config.peer_channel_config_limits.force_announced_channel_preference = false;
7099         config.channel_options.commit_upfront_shutdown_pubkey = false;
7100         let user_cfgs = [None, Some(config), None];
7101         let chanmon_cfgs = create_chanmon_cfgs(3);
7102         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7103         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7104         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7105
7106         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7107         let flags = InitFeatures::known();
7108         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7109         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7110         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7111         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7112         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
7113         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7114     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()));
7115         check_added_monitors!(nodes[2], 1);
7116
7117         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7118         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7119         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7120         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7121         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7122         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7123         let events = nodes[2].node.get_and_clear_pending_msg_events();
7124         assert_eq!(events.len(), 1);
7125         match events[0] {
7126                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7127                 _ => panic!("Unexpected event"),
7128         }
7129
7130         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7131         let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7132         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7133         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7134         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7135         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7136         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
7137         let events = nodes[1].node.get_and_clear_pending_msg_events();
7138         assert_eq!(events.len(), 1);
7139         match events[0] {
7140                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7141                 _ => panic!("Unexpected event"),
7142         }
7143
7144         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7145         // channel smoothly, opt-out is from channel initiator here
7146         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7147         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7148         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7149         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7150         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7151         let events = nodes[0].node.get_and_clear_pending_msg_events();
7152         assert_eq!(events.len(), 1);
7153         match events[0] {
7154                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7155                 _ => panic!("Unexpected event"),
7156         }
7157
7158         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7159         //// channel smoothly
7160         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7161         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7162         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7163         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7164         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7165         let events = nodes[0].node.get_and_clear_pending_msg_events();
7166         assert_eq!(events.len(), 2);
7167         match events[0] {
7168                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7169                 _ => panic!("Unexpected event"),
7170         }
7171         match events[1] {
7172                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7173                 _ => panic!("Unexpected event"),
7174         }
7175 }
7176
7177 #[test]
7178 fn test_upfront_shutdown_script_unsupport_segwit() {
7179         // We test that channel is closed early
7180         // if a segwit program is passed as upfront shutdown script,
7181         // but the peer does not support segwit.
7182         let chanmon_cfgs = create_chanmon_cfgs(2);
7183         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7184         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7185         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7186
7187         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
7188
7189         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7190         open_channel.shutdown_scriptpubkey = Present(Builder::new().push_int(16)
7191                 .push_slice(&[0, 0])
7192                 .into_script());
7193
7194         let features = InitFeatures::known().clear_shutdown_anysegwit();
7195         nodes[0].node.handle_open_channel(&nodes[0].node.get_our_node_id(), features, &open_channel);
7196
7197         let events = nodes[0].node.get_and_clear_pending_msg_events();
7198         assert_eq!(events.len(), 1);
7199         match events[0] {
7200                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7201                         assert_eq!(node_id, nodes[0].node.get_our_node_id());
7202                         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));
7203                 },
7204                 _ => panic!("Unexpected event"),
7205         }
7206 }
7207
7208 #[test]
7209 fn test_shutdown_script_any_segwit_allowed() {
7210         let mut config = UserConfig::default();
7211         config.channel_options.announced_channel = true;
7212         config.peer_channel_config_limits.force_announced_channel_preference = false;
7213         config.channel_options.commit_upfront_shutdown_pubkey = false;
7214         let user_cfgs = [None, Some(config), None];
7215         let chanmon_cfgs = create_chanmon_cfgs(3);
7216         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7217         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7218         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7219
7220         //// We test if the remote peer accepts opt_shutdown_anysegwit, a witness program can be used on shutdown
7221         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7222         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7223         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7224         node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7225                 .push_slice(&[0, 0])
7226                 .into_script();
7227         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7228         let events = nodes[0].node.get_and_clear_pending_msg_events();
7229         assert_eq!(events.len(), 2);
7230         match events[0] {
7231                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7232                 _ => panic!("Unexpected event"),
7233         }
7234         match events[1] {
7235                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7236                 _ => panic!("Unexpected event"),
7237         }
7238 }
7239
7240 #[test]
7241 fn test_shutdown_script_any_segwit_not_allowed() {
7242         let mut config = UserConfig::default();
7243         config.channel_options.announced_channel = true;
7244         config.peer_channel_config_limits.force_announced_channel_preference = false;
7245         config.channel_options.commit_upfront_shutdown_pubkey = false;
7246         let user_cfgs = [None, Some(config), None];
7247         let chanmon_cfgs = create_chanmon_cfgs(3);
7248         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7249         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7250         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7251
7252         //// We test that if the remote peer does not accept opt_shutdown_anysegwit, the witness program cannot be used on shutdown
7253         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7254         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7255         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7256         // Make an any segwit version script
7257         node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7258                 .push_slice(&[0, 0])
7259                 .into_script();
7260         let flags_no = InitFeatures::known().clear_shutdown_anysegwit();
7261         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &flags_no, &node_0_shutdown);
7262         let events = nodes[0].node.get_and_clear_pending_msg_events();
7263         assert_eq!(events.len(), 2);
7264         match events[1] {
7265                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7266                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7267                         assert_eq!(msg.data, "Got a nonstandard scriptpubkey (60020000) from remote peer".to_owned())
7268                 },
7269                 _ => panic!("Unexpected event"),
7270         }
7271         check_added_monitors!(nodes[0], 1);
7272 }
7273
7274 #[test]
7275 fn test_shutdown_script_segwit_but_not_anysegwit() {
7276         let mut config = UserConfig::default();
7277         config.channel_options.announced_channel = true;
7278         config.peer_channel_config_limits.force_announced_channel_preference = false;
7279         config.channel_options.commit_upfront_shutdown_pubkey = false;
7280         let user_cfgs = [None, Some(config), None];
7281         let chanmon_cfgs = create_chanmon_cfgs(3);
7282         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7283         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7284         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7285
7286         //// We test that if shutdown any segwit is supported and we send a witness script with 0 version, this is not accepted
7287         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7288         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7289         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7290         // Make a segwit script that is not a valid as any segwit
7291         node_0_shutdown.scriptpubkey = Builder::new().push_int(0)
7292                 .push_slice(&[0, 0])
7293                 .into_script();
7294         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7295         let events = nodes[0].node.get_and_clear_pending_msg_events();
7296         assert_eq!(events.len(), 2);
7297         match events[1] {
7298                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7299                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7300                         assert_eq!(msg.data, "Got a nonstandard scriptpubkey (00020000) from remote peer".to_owned())
7301                 },
7302                 _ => panic!("Unexpected event"),
7303         }
7304         check_added_monitors!(nodes[0], 1);
7305 }
7306
7307 #[test]
7308 fn test_user_configurable_csv_delay() {
7309         // We test our channel constructors yield errors when we pass them absurd csv delay
7310
7311         let mut low_our_to_self_config = UserConfig::default();
7312         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7313         let mut high_their_to_self_config = UserConfig::default();
7314         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7315         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7316         let chanmon_cfgs = create_chanmon_cfgs(2);
7317         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7318         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7319         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7320
7321         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7322         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) {
7323                 match error {
7324                         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())); },
7325                         _ => panic!("Unexpected event"),
7326                 }
7327         } else { assert!(false) }
7328
7329         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7330         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7331         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7332         open_channel.to_self_delay = 200;
7333         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) {
7334                 match error {
7335                         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()));  },
7336                         _ => panic!("Unexpected event"),
7337                 }
7338         } else { assert!(false); }
7339
7340         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7341         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7342         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()));
7343         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7344         accept_channel.to_self_delay = 200;
7345         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7346         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7347                 match action {
7348                         &ErrorAction::SendErrorMessage { ref msg } => {
7349                                 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()));
7350                         },
7351                         _ => { assert!(false); }
7352                 }
7353         } else { assert!(false); }
7354
7355         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7356         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7357         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7358         open_channel.to_self_delay = 200;
7359         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) {
7360                 match error {
7361                         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())); },
7362                         _ => panic!("Unexpected event"),
7363                 }
7364         } else { assert!(false); }
7365 }
7366
7367 #[test]
7368 fn test_data_loss_protect() {
7369         // We want to be sure that :
7370         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7371         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7372         // * we close channel in case of detecting other being fallen behind
7373         // * we are able to claim our own outputs thanks to to_remote being static
7374         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7375         let persister;
7376         let logger;
7377         let fee_estimator;
7378         let tx_broadcaster;
7379         let chain_source;
7380         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7381         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7382         // during signing due to revoked tx
7383         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7384         let keys_manager = &chanmon_cfgs[0].keys_manager;
7385         let monitor;
7386         let node_state_0;
7387         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7388         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7389         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7390
7391         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7392
7393         // Cache node A state before any channel update
7394         let previous_node_state = nodes[0].node.encode();
7395         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7396         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7397
7398         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7399         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7400
7401         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7402         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7403
7404         // Restore node A from previous state
7405         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7406         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7407         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7408         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7409         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7410         persister = test_utils::TestPersister::new();
7411         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7412         node_state_0 = {
7413                 let mut channel_monitors = HashMap::new();
7414                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7415                 <(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 {
7416                         keys_manager: keys_manager,
7417                         fee_estimator: &fee_estimator,
7418                         chain_monitor: &monitor,
7419                         logger: &logger,
7420                         tx_broadcaster: &tx_broadcaster,
7421                         default_config: UserConfig::default(),
7422                         channel_monitors,
7423                 }).unwrap().1
7424         };
7425         nodes[0].node = &node_state_0;
7426         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7427         nodes[0].chain_monitor = &monitor;
7428         nodes[0].chain_source = &chain_source;
7429
7430         check_added_monitors!(nodes[0], 1);
7431
7432         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7433         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7434
7435         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7436
7437         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7438         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7439         check_added_monitors!(nodes[0], 1);
7440
7441         {
7442                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7443                 assert_eq!(node_txn.len(), 0);
7444         }
7445
7446         let mut reestablish_1 = Vec::with_capacity(1);
7447         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7448                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7449                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7450                         reestablish_1.push(msg.clone());
7451                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7452                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7453                         match action {
7454                                 &ErrorAction::SendErrorMessage { ref msg } => {
7455                                         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");
7456                                 },
7457                                 _ => panic!("Unexpected event!"),
7458                         }
7459                 } else {
7460                         panic!("Unexpected event")
7461                 }
7462         }
7463
7464         // Check we close channel detecting A is fallen-behind
7465         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7466         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7467         check_added_monitors!(nodes[1], 1);
7468
7469
7470         // Check A is able to claim to_remote output
7471         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7472         assert_eq!(node_txn.len(), 1);
7473         check_spends!(node_txn[0], chan.3);
7474         assert_eq!(node_txn[0].output.len(), 2);
7475         mine_transaction(&nodes[0], &node_txn[0]);
7476         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7477         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 1000000);
7478         assert_eq!(spend_txn.len(), 1);
7479         check_spends!(spend_txn[0], node_txn[0]);
7480 }
7481
7482 #[test]
7483 fn test_check_htlc_underpaying() {
7484         // Send payment through A -> B but A is maliciously
7485         // sending a probe payment (i.e less than expected value0
7486         // to B, B should refuse payment.
7487
7488         let chanmon_cfgs = create_chanmon_cfgs(2);
7489         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7490         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7491         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7492
7493         // Create some initial channels
7494         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7495
7496         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7497
7498         // Node 3 is expecting payment of 100_000 but receive 10_000,
7499         // fail htlc like we didn't know the preimage.
7500         nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7501         nodes[1].node.process_pending_htlc_forwards();
7502
7503         let events = nodes[1].node.get_and_clear_pending_msg_events();
7504         assert_eq!(events.len(), 1);
7505         let (update_fail_htlc, commitment_signed) = match events[0] {
7506                 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 } } => {
7507                         assert!(update_add_htlcs.is_empty());
7508                         assert!(update_fulfill_htlcs.is_empty());
7509                         assert_eq!(update_fail_htlcs.len(), 1);
7510                         assert!(update_fail_malformed_htlcs.is_empty());
7511                         assert!(update_fee.is_none());
7512                         (update_fail_htlcs[0].clone(), commitment_signed)
7513                 },
7514                 _ => panic!("Unexpected event"),
7515         };
7516         check_added_monitors!(nodes[1], 1);
7517
7518         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7519         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7520
7521         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7522         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7523         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7524         expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7525         nodes[1].node.get_and_clear_pending_events();
7526 }
7527
7528 #[test]
7529 fn test_announce_disable_channels() {
7530         // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7531         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7532
7533         let chanmon_cfgs = create_chanmon_cfgs(2);
7534         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7535         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7536         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7537
7538         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7539         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7540         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7541
7542         // Disconnect peers
7543         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7544         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7545
7546         nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7547         nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7548         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7549         assert_eq!(msg_events.len(), 3);
7550         for e in msg_events {
7551                 match e {
7552                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7553                                 let short_id = msg.contents.short_channel_id;
7554                                 // Check generated channel_update match list in PendingChannelUpdate
7555                                 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7556                                         panic!("Generated ChannelUpdate for wrong chan!");
7557                                 }
7558                         },
7559                         _ => panic!("Unexpected event"),
7560                 }
7561         }
7562         // Reconnect peers
7563         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7564         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7565         assert_eq!(reestablish_1.len(), 3);
7566         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7567         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7568         assert_eq!(reestablish_2.len(), 3);
7569
7570         // Reestablish chan_1
7571         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7572         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7573         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7574         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7575         // Reestablish chan_2
7576         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7577         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7578         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7579         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7580         // Reestablish chan_3
7581         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7582         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7583         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7584         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7585
7586         nodes[0].node.timer_chan_freshness_every_min();
7587         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7588 }
7589
7590 #[test]
7591 fn test_bump_penalty_txn_on_revoked_commitment() {
7592         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7593         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7594
7595         let chanmon_cfgs = create_chanmon_cfgs(2);
7596         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7597         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7598         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7599
7600         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7601         let logger = test_utils::TestLogger::new();
7602
7603         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7604         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7605         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();
7606         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7607
7608         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7609         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7610         assert_eq!(revoked_txn[0].output.len(), 4);
7611         assert_eq!(revoked_txn[0].input.len(), 1);
7612         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7613         let revoked_txid = revoked_txn[0].txid();
7614
7615         let mut penalty_sum = 0;
7616         for outp in revoked_txn[0].output.iter() {
7617                 if outp.script_pubkey.is_v0_p2wsh() {
7618                         penalty_sum += outp.value;
7619                 }
7620         }
7621
7622         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7623         let header_114 = connect_blocks(&nodes[1], 14);
7624
7625         // Actually revoke tx by claiming a HTLC
7626         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7627         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7628         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7629         check_added_monitors!(nodes[1], 1);
7630
7631         // One or more justice tx should have been broadcast, check it
7632         let penalty_1;
7633         let feerate_1;
7634         {
7635                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7636                 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7637                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7638                 assert_eq!(node_txn[0].output.len(), 1);
7639                 check_spends!(node_txn[0], revoked_txn[0]);
7640                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7641                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7642                 penalty_1 = node_txn[0].txid();
7643                 node_txn.clear();
7644         };
7645
7646         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7647         connect_blocks(&nodes[1], 15);
7648         let mut penalty_2 = penalty_1;
7649         let mut feerate_2 = 0;
7650         {
7651                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7652                 assert_eq!(node_txn.len(), 1);
7653                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7654                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7655                         assert_eq!(node_txn[0].output.len(), 1);
7656                         check_spends!(node_txn[0], revoked_txn[0]);
7657                         penalty_2 = node_txn[0].txid();
7658                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7659                         assert_ne!(penalty_2, penalty_1);
7660                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7661                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7662                         // Verify 25% bump heuristic
7663                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7664                         node_txn.clear();
7665                 }
7666         }
7667         assert_ne!(feerate_2, 0);
7668
7669         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7670         connect_blocks(&nodes[1], 1);
7671         let penalty_3;
7672         let mut feerate_3 = 0;
7673         {
7674                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7675                 assert_eq!(node_txn.len(), 1);
7676                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7677                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7678                         assert_eq!(node_txn[0].output.len(), 1);
7679                         check_spends!(node_txn[0], revoked_txn[0]);
7680                         penalty_3 = node_txn[0].txid();
7681                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7682                         assert_ne!(penalty_3, penalty_2);
7683                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7684                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7685                         // Verify 25% bump heuristic
7686                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7687                         node_txn.clear();
7688                 }
7689         }
7690         assert_ne!(feerate_3, 0);
7691
7692         nodes[1].node.get_and_clear_pending_events();
7693         nodes[1].node.get_and_clear_pending_msg_events();
7694 }
7695
7696 #[test]
7697 fn test_bump_penalty_txn_on_revoked_htlcs() {
7698         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7699         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7700
7701         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7702         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7703         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7704         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7705         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7706
7707         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7708         // Lock HTLC in both directions
7709         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7710         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7711
7712         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7713         assert_eq!(revoked_local_txn[0].input.len(), 1);
7714         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7715
7716         // Revoke local commitment tx
7717         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7718
7719         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7720         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7721         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7722         check_closed_broadcast!(nodes[1], false);
7723         check_added_monitors!(nodes[1], 1);
7724
7725         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7726         assert_eq!(revoked_htlc_txn.len(), 4);
7727         if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7728                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7729                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7730                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7731                 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7732                 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7733                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7734         } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7735                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7736                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7737                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7738                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7739                 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7740                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7741         }
7742
7743         // Broadcast set of revoked txn on A
7744         let hash_128 = connect_blocks(&nodes[0], 40);
7745         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7746         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7747         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7748         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7749         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7750         let first;
7751         let feerate_1;
7752         let penalty_txn;
7753         {
7754                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7755                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7756                 // Verify claim tx are spending revoked HTLC txn
7757
7758                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7759                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7760                 // which are included in the same block (they are broadcasted because we scan the
7761                 // transactions linearly and generate claims as we go, they likely should be removed in the
7762                 // future).
7763                 assert_eq!(node_txn[0].input.len(), 1);
7764                 check_spends!(node_txn[0], revoked_local_txn[0]);
7765                 assert_eq!(node_txn[1].input.len(), 1);
7766                 check_spends!(node_txn[1], revoked_local_txn[0]);
7767                 assert_eq!(node_txn[2].input.len(), 1);
7768                 check_spends!(node_txn[2], revoked_local_txn[0]);
7769
7770                 // Each of the three justice transactions claim a separate (single) output of the three
7771                 // available, which we check here:
7772                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7773                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7774                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7775
7776                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7777                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7778
7779                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7780                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7781                 // a remote commitment tx has already been confirmed).
7782                 check_spends!(node_txn[3], chan.3);
7783
7784                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7785                 // output, checked above).
7786                 assert_eq!(node_txn[4].input.len(), 2);
7787                 assert_eq!(node_txn[4].output.len(), 1);
7788                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7789
7790                 first = node_txn[4].txid();
7791                 // Store both feerates for later comparison
7792                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7793                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7794                 penalty_txn = vec![node_txn[2].clone()];
7795                 node_txn.clear();
7796         }
7797
7798         // Connect one more block to see if bumped penalty are issued for HTLC txn
7799         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7800         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7801         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7802         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7803         {
7804                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7805                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7806
7807                 check_spends!(node_txn[0], revoked_local_txn[0]);
7808                 check_spends!(node_txn[1], revoked_local_txn[0]);
7809                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7810                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7811                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7812                 } else {
7813                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7814                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7815                 }
7816
7817                 node_txn.clear();
7818         };
7819
7820         // Few more blocks to confirm penalty txn
7821         connect_blocks(&nodes[0], 4);
7822         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7823         let header_144 = connect_blocks(&nodes[0], 9);
7824         let node_txn = {
7825                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7826                 assert_eq!(node_txn.len(), 1);
7827
7828                 assert_eq!(node_txn[0].input.len(), 2);
7829                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7830                 // Verify bumped tx is different and 25% bump heuristic
7831                 assert_ne!(first, node_txn[0].txid());
7832                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7833                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7834                 assert!(feerate_2 * 100 > feerate_1 * 125);
7835                 let txn = vec![node_txn[0].clone()];
7836                 node_txn.clear();
7837                 txn
7838         };
7839         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7840         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7841         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7842         connect_blocks(&nodes[0], 20);
7843         {
7844                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7845                 // We verify than no new transaction has been broadcast because previously
7846                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7847                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7848                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7849                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7850                 // up bumped justice generation.
7851                 assert_eq!(node_txn.len(), 0);
7852                 node_txn.clear();
7853         }
7854         check_closed_broadcast!(nodes[0], false);
7855         check_added_monitors!(nodes[0], 1);
7856 }
7857
7858 #[test]
7859 fn test_bump_penalty_txn_on_remote_commitment() {
7860         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7861         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7862
7863         // Create 2 HTLCs
7864         // Provide preimage for one
7865         // Check aggregation
7866
7867         let chanmon_cfgs = create_chanmon_cfgs(2);
7868         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7869         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7870         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7871
7872         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7873         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7874         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7875
7876         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7877         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7878         assert_eq!(remote_txn[0].output.len(), 4);
7879         assert_eq!(remote_txn[0].input.len(), 1);
7880         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7881
7882         // Claim a HTLC without revocation (provide B monitor with preimage)
7883         nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7884         mine_transaction(&nodes[1], &remote_txn[0]);
7885         check_added_monitors!(nodes[1], 2);
7886
7887         // One or more claim tx should have been broadcast, check it
7888         let timeout;
7889         let preimage;
7890         let feerate_timeout;
7891         let feerate_preimage;
7892         {
7893                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7894                 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7895                 assert_eq!(node_txn[0].input.len(), 1);
7896                 assert_eq!(node_txn[1].input.len(), 1);
7897                 check_spends!(node_txn[0], remote_txn[0]);
7898                 check_spends!(node_txn[1], remote_txn[0]);
7899                 check_spends!(node_txn[2], chan.3);
7900                 check_spends!(node_txn[3], node_txn[2]);
7901                 check_spends!(node_txn[4], node_txn[2]);
7902                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7903                         timeout = node_txn[0].txid();
7904                         let index = node_txn[0].input[0].previous_output.vout;
7905                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7906                         feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7907
7908                         preimage = node_txn[1].txid();
7909                         let index = node_txn[1].input[0].previous_output.vout;
7910                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7911                         feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7912                 } else {
7913                         timeout = node_txn[1].txid();
7914                         let index = node_txn[1].input[0].previous_output.vout;
7915                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7916                         feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7917
7918                         preimage = node_txn[0].txid();
7919                         let index = node_txn[0].input[0].previous_output.vout;
7920                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7921                         feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7922                 }
7923                 node_txn.clear();
7924         };
7925         assert_ne!(feerate_timeout, 0);
7926         assert_ne!(feerate_preimage, 0);
7927
7928         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7929         connect_blocks(&nodes[1], 15);
7930         {
7931                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7932                 assert_eq!(node_txn.len(), 2);
7933                 assert_eq!(node_txn[0].input.len(), 1);
7934                 assert_eq!(node_txn[1].input.len(), 1);
7935                 check_spends!(node_txn[0], remote_txn[0]);
7936                 check_spends!(node_txn[1], remote_txn[0]);
7937                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7938                         let index = node_txn[0].input[0].previous_output.vout;
7939                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7940                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7941                         assert!(new_feerate * 100 > feerate_timeout * 125);
7942                         assert_ne!(timeout, node_txn[0].txid());
7943
7944                         let index = node_txn[1].input[0].previous_output.vout;
7945                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7946                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7947                         assert!(new_feerate * 100 > feerate_preimage * 125);
7948                         assert_ne!(preimage, node_txn[1].txid());
7949                 } else {
7950                         let index = node_txn[1].input[0].previous_output.vout;
7951                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7952                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7953                         assert!(new_feerate * 100 > feerate_timeout * 125);
7954                         assert_ne!(timeout, node_txn[1].txid());
7955
7956                         let index = node_txn[0].input[0].previous_output.vout;
7957                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7958                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7959                         assert!(new_feerate * 100 > feerate_preimage * 125);
7960                         assert_ne!(preimage, node_txn[0].txid());
7961                 }
7962                 node_txn.clear();
7963         }
7964
7965         nodes[1].node.get_and_clear_pending_events();
7966         nodes[1].node.get_and_clear_pending_msg_events();
7967 }
7968
7969 #[test]
7970 fn test_counterparty_raa_skip_no_crash() {
7971         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7972         // commitment transaction, we would have happily carried on and provided them the next
7973         // commitment transaction based on one RAA forward. This would probably eventually have led to
7974         // channel closure, but it would not have resulted in funds loss. Still, our
7975         // EnforcingSigner would have paniced as it doesn't like jumps into the future. Here, we
7976         // check simply that the channel is closed in response to such an RAA, but don't check whether
7977         // we decide to punish our counterparty for revoking their funds (as we don't currently
7978         // implement that).
7979         let chanmon_cfgs = create_chanmon_cfgs(2);
7980         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7981         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7982         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7983         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7984
7985         let mut guard = nodes[0].node.channel_state.lock().unwrap();
7986         let keys = &guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7987         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7988         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7989         // Must revoke without gaps
7990         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7991         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7992                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7993
7994         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7995                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7996         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7997         check_added_monitors!(nodes[1], 1);
7998 }
7999
8000 #[test]
8001 fn test_bump_txn_sanitize_tracking_maps() {
8002         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8003         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8004
8005         let chanmon_cfgs = create_chanmon_cfgs(2);
8006         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8007         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8008         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8009
8010         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8011         // Lock HTLC in both directions
8012         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8013         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8014
8015         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8016         assert_eq!(revoked_local_txn[0].input.len(), 1);
8017         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8018
8019         // Revoke local commitment tx
8020         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8021
8022         // Broadcast set of revoked txn on A
8023         connect_blocks(&nodes[0], 52 - CHAN_CONFIRM_DEPTH);
8024         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8025         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8026
8027         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8028         check_closed_broadcast!(nodes[0], false);
8029         check_added_monitors!(nodes[0], 1);
8030         let penalty_txn = {
8031                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8032                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8033                 check_spends!(node_txn[0], revoked_local_txn[0]);
8034                 check_spends!(node_txn[1], revoked_local_txn[0]);
8035                 check_spends!(node_txn[2], revoked_local_txn[0]);
8036                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8037                 node_txn.clear();
8038                 penalty_txn
8039         };
8040         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8041         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8042         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8043         {
8044                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8045                 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8046                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8047                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8048                 }
8049         }
8050 }
8051
8052 #[test]
8053 fn test_override_channel_config() {
8054         let chanmon_cfgs = create_chanmon_cfgs(2);
8055         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8056         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8057         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8058
8059         // Node0 initiates a channel to node1 using the override config.
8060         let mut override_config = UserConfig::default();
8061         override_config.own_channel_config.our_to_self_delay = 200;
8062
8063         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8064
8065         // Assert the channel created by node0 is using the override config.
8066         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8067         assert_eq!(res.channel_flags, 0);
8068         assert_eq!(res.to_self_delay, 200);
8069 }
8070
8071 #[test]
8072 fn test_override_0msat_htlc_minimum() {
8073         let mut zero_config = UserConfig::default();
8074         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8075         let chanmon_cfgs = create_chanmon_cfgs(2);
8076         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8077         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8078         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8079
8080         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8081         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8082         assert_eq!(res.htlc_minimum_msat, 1);
8083
8084         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8085         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8086         assert_eq!(res.htlc_minimum_msat, 1);
8087 }
8088
8089 #[test]
8090 fn test_simple_payment_secret() {
8091         // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8092         // features, however.
8093         let chanmon_cfgs = create_chanmon_cfgs(3);
8094         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8095         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8096         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8097
8098         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8099         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8100         let logger = test_utils::TestLogger::new();
8101
8102         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8103         let payment_secret = PaymentSecret([0xdb; 32]);
8104         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8105         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();
8106         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8107         // Claiming with all the correct values but the wrong secret should result in nothing...
8108         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8109         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8110         // ...but with the right secret we should be able to claim all the way back
8111         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8112 }
8113
8114 #[test]
8115 fn test_simple_mpp() {
8116         // Simple test of sending a multi-path payment.
8117         let chanmon_cfgs = create_chanmon_cfgs(4);
8118         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8119         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8120         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8121
8122         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8123         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8124         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8125         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8126         let logger = test_utils::TestLogger::new();
8127
8128         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8129         let payment_secret = PaymentSecret([0xdb; 32]);
8130         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8131         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();
8132         let path = route.paths[0].clone();
8133         route.paths.push(path);
8134         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8135         route.paths[0][0].short_channel_id = chan_1_id;
8136         route.paths[0][1].short_channel_id = chan_3_id;
8137         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8138         route.paths[1][0].short_channel_id = chan_2_id;
8139         route.paths[1][1].short_channel_id = chan_4_id;
8140         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8141         // Claiming with all the correct values but the wrong secret should result in nothing...
8142         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8143         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8144         // ...but with the right secret we should be able to claim all the way back
8145         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8146 }
8147
8148 #[test]
8149 fn test_update_err_monitor_lockdown() {
8150         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8151         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8152         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8153         //
8154         // This scenario may happen in a watchtower setup, where watchtower process a block height
8155         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8156         // commitment at same time.
8157
8158         let chanmon_cfgs = create_chanmon_cfgs(2);
8159         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8160         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8161         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8162
8163         // Create some initial channel
8164         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8165         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8166
8167         // Rebalance the network to generate htlc in the two directions
8168         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8169
8170         // Route a HTLC from node 0 to node 1 (but don't settle)
8171         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8172
8173         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8174         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8175         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8176         let persister = test_utils::TestPersister::new();
8177         let watchtower = {
8178                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8179                 let monitor = monitors.get(&outpoint).unwrap();
8180                 let mut w = test_utils::TestVecWriter(Vec::new());
8181                 monitor.write(&mut w).unwrap();
8182                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8183                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8184                 assert!(new_monitor == *monitor);
8185                 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);
8186                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8187                 watchtower
8188         };
8189         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8190         watchtower.chain_monitor.block_connected(&header, &[], 200);
8191
8192         // Try to update ChannelMonitor
8193         assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8194         check_added_monitors!(nodes[1], 1);
8195         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8196         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8197         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8198         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8199                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8200                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8201                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8202                 } else { assert!(false); }
8203         } else { assert!(false); };
8204         // Our local monitor is in-sync and hasn't processed yet timeout
8205         check_added_monitors!(nodes[0], 1);
8206         let events = nodes[0].node.get_and_clear_pending_events();
8207         assert_eq!(events.len(), 1);
8208 }
8209
8210 #[test]
8211 fn test_concurrent_monitor_claim() {
8212         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8213         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8214         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8215         // state N+1 confirms. Alice claims output from state N+1.
8216
8217         let chanmon_cfgs = create_chanmon_cfgs(2);
8218         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8219         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8220         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8221
8222         // Create some initial channel
8223         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8224         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8225
8226         // Rebalance the network to generate htlc in the two directions
8227         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8228
8229         // Route a HTLC from node 0 to node 1 (but don't settle)
8230         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8231
8232         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8233         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8234         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8235         let persister = test_utils::TestPersister::new();
8236         let watchtower_alice = {
8237                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8238                 let monitor = monitors.get(&outpoint).unwrap();
8239                 let mut w = test_utils::TestVecWriter(Vec::new());
8240                 monitor.write(&mut w).unwrap();
8241                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8242                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8243                 assert!(new_monitor == *monitor);
8244                 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);
8245                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8246                 watchtower
8247         };
8248         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8249         watchtower_alice.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8250
8251         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8252         {
8253                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8254                 assert_eq!(txn.len(), 2);
8255                 txn.clear();
8256         }
8257
8258         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8259         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8260         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8261         let persister = test_utils::TestPersister::new();
8262         let watchtower_bob = {
8263                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8264                 let monitor = monitors.get(&outpoint).unwrap();
8265                 let mut w = test_utils::TestVecWriter(Vec::new());
8266                 monitor.write(&mut w).unwrap();
8267                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8268                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8269                 assert!(new_monitor == *monitor);
8270                 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);
8271                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8272                 watchtower
8273         };
8274         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8275         watchtower_bob.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8276
8277         // Route another payment to generate another update with still previous HTLC pending
8278         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8279         {
8280                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8281                 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();
8282                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8283         }
8284         check_added_monitors!(nodes[1], 1);
8285
8286         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8287         assert_eq!(updates.update_add_htlcs.len(), 1);
8288         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8289         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8290                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8291                         // Watchtower Alice should already have seen the block and reject the update
8292                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8293                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8294                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8295                 } else { assert!(false); }
8296         } else { assert!(false); };
8297         // Our local monitor is in-sync and hasn't processed yet timeout
8298         check_added_monitors!(nodes[0], 1);
8299
8300         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8301         watchtower_bob.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8302
8303         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8304         let bob_state_y;
8305         {
8306                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8307                 assert_eq!(txn.len(), 2);
8308                 bob_state_y = txn[0].clone();
8309                 txn.clear();
8310         };
8311
8312         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8313         watchtower_alice.chain_monitor.block_connected(&header, &vec![(0, &bob_state_y)], CHAN_CONFIRM_DEPTH + 2 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8314         {
8315                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8316                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8317                 // the onchain detection of the HTLC output
8318                 assert_eq!(htlc_txn.len(), 2);
8319                 check_spends!(htlc_txn[0], bob_state_y);
8320                 check_spends!(htlc_txn[1], bob_state_y);
8321         }
8322 }
8323
8324 #[test]
8325 fn test_pre_lockin_no_chan_closed_update() {
8326         // Test that if a peer closes a channel in response to a funding_created message we don't
8327         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8328         // message).
8329         //
8330         // Doing so would imply a channel monitor update before the initial channel monitor
8331         // registration, violating our API guarantees.
8332         //
8333         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8334         // then opening a second channel with the same funding output as the first (which is not
8335         // rejected because the first channel does not exist in the ChannelManager) and closing it
8336         // before receiving funding_signed.
8337         let chanmon_cfgs = create_chanmon_cfgs(2);
8338         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8339         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8340         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8341
8342         // Create an initial channel
8343         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8344         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8345         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8346         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8347         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8348
8349         // Move the first channel through the funding flow...
8350         let (temporary_channel_id, _tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8351
8352         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8353         check_added_monitors!(nodes[0], 0);
8354
8355         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8356         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8357         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8358         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8359 }
8360
8361 #[test]
8362 fn test_htlc_no_detection() {
8363         // This test is a mutation to underscore the detection logic bug we had
8364         // before #653. HTLC value routed is above the remaining balance, thus
8365         // inverting HTLC and `to_remote` output. HTLC will come second and
8366         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8367         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8368         // outputs order detection for correct spending children filtring.
8369
8370         let chanmon_cfgs = create_chanmon_cfgs(2);
8371         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8372         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8373         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8374
8375         // Create some initial channels
8376         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8377
8378         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000, 1_000_000);
8379         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8380         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8381         assert_eq!(local_txn[0].input.len(), 1);
8382         assert_eq!(local_txn[0].output.len(), 3);
8383         check_spends!(local_txn[0], chan_1.3);
8384
8385         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8386         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8387         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8388         // We deliberately connect the local tx twice as this should provoke a failure calling
8389         // this test before #653 fix.
8390         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);
8391         check_closed_broadcast!(nodes[0], false);
8392         check_added_monitors!(nodes[0], 1);
8393
8394         let htlc_timeout = {
8395                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8396                 assert_eq!(node_txn[0].input.len(), 1);
8397                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8398                 check_spends!(node_txn[0], local_txn[0]);
8399                 node_txn[0].clone()
8400         };
8401
8402         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8403         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8404         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8405         expect_payment_failed!(nodes[0], our_payment_hash, true);
8406 }
8407
8408 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8409         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8410         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8411         // Carol, Alice would be the upstream node, and Carol the downstream.)
8412         //
8413         // Steps of the test:
8414         // 1) Alice sends a HTLC to Carol through Bob.
8415         // 2) Carol doesn't settle the HTLC.
8416         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8417         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8418         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8419         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8420         // 5) Carol release the preimage to Bob off-chain.
8421         // 6) Bob claims the offered output on the broadcasted commitment.
8422         let chanmon_cfgs = create_chanmon_cfgs(3);
8423         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8424         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8425         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8426
8427         // Create some initial channels
8428         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8429         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8430
8431         // Steps (1) and (2):
8432         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8433         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8434
8435         // Check that Alice's commitment transaction now contains an output for this HTLC.
8436         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8437         check_spends!(alice_txn[0], chan_ab.3);
8438         assert_eq!(alice_txn[0].output.len(), 2);
8439         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8440         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8441         assert_eq!(alice_txn.len(), 2);
8442
8443         // Steps (3) and (4):
8444         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8445         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8446         let mut force_closing_node = 0; // Alice force-closes
8447         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8448         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8449         check_closed_broadcast!(nodes[force_closing_node], false);
8450         check_added_monitors!(nodes[force_closing_node], 1);
8451         if go_onchain_before_fulfill {
8452                 let txn_to_broadcast = match broadcast_alice {
8453                         true => alice_txn.clone(),
8454                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8455                 };
8456                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8457                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8458                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8459                 if broadcast_alice {
8460                         check_closed_broadcast!(nodes[1], false);
8461                         check_added_monitors!(nodes[1], 1);
8462                 }
8463                 assert_eq!(bob_txn.len(), 1);
8464                 check_spends!(bob_txn[0], chan_ab.3);
8465         }
8466
8467         // Step (5):
8468         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8469         // process of removing the HTLC from their commitment transactions.
8470         assert!(nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000));
8471         check_added_monitors!(nodes[2], 1);
8472         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8473         assert!(carol_updates.update_add_htlcs.is_empty());
8474         assert!(carol_updates.update_fail_htlcs.is_empty());
8475         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8476         assert!(carol_updates.update_fee.is_none());
8477         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8478
8479         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8480         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8481         if !go_onchain_before_fulfill && broadcast_alice {
8482                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8483                 assert_eq!(events.len(), 1);
8484                 match events[0] {
8485                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8486                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8487                         },
8488                         _ => panic!("Unexpected event"),
8489                 };
8490         }
8491         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8492         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8493         // Carol<->Bob's updated commitment transaction info.
8494         check_added_monitors!(nodes[1], 2);
8495
8496         let events = nodes[1].node.get_and_clear_pending_msg_events();
8497         assert_eq!(events.len(), 2);
8498         let bob_revocation = match events[0] {
8499                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8500                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8501                         (*msg).clone()
8502                 },
8503                 _ => panic!("Unexpected event"),
8504         };
8505         let bob_updates = match events[1] {
8506                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8507                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8508                         (*updates).clone()
8509                 },
8510                 _ => panic!("Unexpected event"),
8511         };
8512
8513         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8514         check_added_monitors!(nodes[2], 1);
8515         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8516         check_added_monitors!(nodes[2], 1);
8517
8518         let events = nodes[2].node.get_and_clear_pending_msg_events();
8519         assert_eq!(events.len(), 1);
8520         let carol_revocation = match events[0] {
8521                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8522                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8523                         (*msg).clone()
8524                 },
8525                 _ => panic!("Unexpected event"),
8526         };
8527         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8528         check_added_monitors!(nodes[1], 1);
8529
8530         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8531         // here's where we put said channel's commitment tx on-chain.
8532         let mut txn_to_broadcast = alice_txn.clone();
8533         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8534         if !go_onchain_before_fulfill {
8535                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8536                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8537                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8538                 if broadcast_alice {
8539                         check_closed_broadcast!(nodes[1], false);
8540                         check_added_monitors!(nodes[1], 1);
8541                 }
8542                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8543                 if broadcast_alice {
8544                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8545                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8546                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8547                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8548                         // broadcasted.
8549                         assert_eq!(bob_txn.len(), 3);
8550                         check_spends!(bob_txn[1], chan_ab.3);
8551                 } else {
8552                         assert_eq!(bob_txn.len(), 2);
8553                         check_spends!(bob_txn[0], chan_ab.3);
8554                 }
8555         }
8556
8557         // Step (6):
8558         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8559         // broadcasted commitment transaction.
8560         {
8561                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8562                 if go_onchain_before_fulfill {
8563                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8564                         assert_eq!(bob_txn.len(), 2);
8565                 }
8566                 let script_weight = match broadcast_alice {
8567                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8568                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8569                 };
8570                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8571                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8572                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8573                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8574                 if broadcast_alice && !go_onchain_before_fulfill {
8575                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8576                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8577                 } else {
8578                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8579                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8580                 }
8581         }
8582 }
8583
8584 #[test]
8585 fn test_onchain_htlc_settlement_after_close() {
8586         do_test_onchain_htlc_settlement_after_close(true, true);
8587         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8588         do_test_onchain_htlc_settlement_after_close(true, false);
8589         do_test_onchain_htlc_settlement_after_close(false, false);
8590 }
8591
8592 #[test]
8593 fn test_duplicate_chan_id() {
8594         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8595         // already open we reject it and keep the old channel.
8596         //
8597         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8598         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8599         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8600         // updating logic for the existing channel.
8601         let chanmon_cfgs = create_chanmon_cfgs(2);
8602         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8603         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8604         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8605
8606         // Create an initial channel
8607         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8608         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8609         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8610         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()));
8611
8612         // Try to create a second channel with the same temporary_channel_id as the first and check
8613         // that it is rejected.
8614         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8615         {
8616                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8617                 assert_eq!(events.len(), 1);
8618                 match events[0] {
8619                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8620                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8621                                 // first (valid) and second (invalid) channels are closed, given they both have
8622                                 // the same non-temporary channel_id. However, currently we do not, so we just
8623                                 // move forward with it.
8624                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8625                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8626                         },
8627                         _ => panic!("Unexpected event"),
8628                 }
8629         }
8630
8631         // Move the first channel through the funding flow...
8632         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8633
8634         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8635         check_added_monitors!(nodes[0], 0);
8636
8637         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8638         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8639         {
8640                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8641                 assert_eq!(added_monitors.len(), 1);
8642                 assert_eq!(added_monitors[0].0, funding_output);
8643                 added_monitors.clear();
8644         }
8645         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8646
8647         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8648         let channel_id = funding_outpoint.to_channel_id();
8649
8650         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8651         // temporary one).
8652
8653         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8654         // Technically this is allowed by the spec, but we don't support it and there's little reason
8655         // to. Still, it shouldn't cause any other issues.
8656         open_chan_msg.temporary_channel_id = channel_id;
8657         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8658         {
8659                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8660                 assert_eq!(events.len(), 1);
8661                 match events[0] {
8662                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8663                                 // Technically, at this point, nodes[1] would be justified in thinking both
8664                                 // channels are closed, but currently we do not, so we just move forward with it.
8665                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8666                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8667                         },
8668                         _ => panic!("Unexpected event"),
8669                 }
8670         }
8671
8672         // Now try to create a second channel which has a duplicate funding output.
8673         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8674         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8675         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8676         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()));
8677         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8678
8679         let funding_created = {
8680                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8681                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8682                 let logger = test_utils::TestLogger::new();
8683                 as_chan.get_outbound_funding_created(funding_outpoint, &&logger).unwrap()
8684         };
8685         check_added_monitors!(nodes[0], 0);
8686         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8687         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8688         // still needs to be cleared here.
8689         check_added_monitors!(nodes[1], 1);
8690
8691         // ...still, nodes[1] will reject the duplicate channel.
8692         {
8693                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8694                 assert_eq!(events.len(), 1);
8695                 match events[0] {
8696                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8697                                 // Technically, at this point, nodes[1] would be justified in thinking both
8698                                 // channels are closed, but currently we do not, so we just move forward with it.
8699                                 assert_eq!(msg.channel_id, channel_id);
8700                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8701                         },
8702                         _ => panic!("Unexpected event"),
8703                 }
8704         }
8705
8706         // finally, finish creating the original channel and send a payment over it to make sure
8707         // everything is functional.
8708         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8709         {
8710                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8711                 assert_eq!(added_monitors.len(), 1);
8712                 assert_eq!(added_monitors[0].0, funding_output);
8713                 added_monitors.clear();
8714         }
8715
8716         let events_4 = nodes[0].node.get_and_clear_pending_events();
8717         assert_eq!(events_4.len(), 1);
8718         match events_4[0] {
8719                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
8720                         assert_eq!(user_channel_id, 42);
8721                         assert_eq!(*funding_txo, funding_output);
8722                 },
8723                 _ => panic!("Unexpected event"),
8724         };
8725
8726         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8727         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8728         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8729         send_payment(&nodes[0], &[&nodes[1]], 8000000, 8_000_000);
8730 }
8731
8732 #[test]
8733 fn test_error_chans_closed() {
8734         // Test that we properly handle error messages, closing appropriate channels.
8735         //
8736         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8737         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8738         // we can test various edge cases around it to ensure we don't regress.
8739         let chanmon_cfgs = create_chanmon_cfgs(3);
8740         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8741         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8742         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8743
8744         // Create some initial channels
8745         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8746         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8747         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8748
8749         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8750         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8751         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8752
8753         // Closing a channel from a different peer has no effect
8754         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8755         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8756
8757         // Closing one channel doesn't impact others
8758         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8759         check_added_monitors!(nodes[0], 1);
8760         check_closed_broadcast!(nodes[0], false);
8761         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8762         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);
8763         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);
8764
8765         // A null channel ID should close all channels
8766         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8767         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8768         check_added_monitors!(nodes[0], 2);
8769         let events = nodes[0].node.get_and_clear_pending_msg_events();
8770         assert_eq!(events.len(), 2);
8771         match events[0] {
8772                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8773                         assert_eq!(msg.contents.flags & 2, 2);
8774                 },
8775                 _ => panic!("Unexpected event"),
8776         }
8777         match events[1] {
8778                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8779                         assert_eq!(msg.contents.flags & 2, 2);
8780                 },
8781                 _ => panic!("Unexpected event"),
8782         }
8783         // Note that at this point users of a standard PeerHandler will end up calling
8784         // peer_disconnected with no_connection_possible set to false, duplicating the
8785         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8786         // users with their own peer handling logic. We duplicate the call here, however.
8787         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8788         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8789
8790         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8791         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8792         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8793 }