b88ee21a68dc106816b685005f65120ed47f5db0
[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::Listen;
16 use chain::Watch;
17 use chain::channelmonitor;
18 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use chain::transaction::OutPoint;
20 use chain::keysinterface::{KeysInterface, BaseSign};
21 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
23 use ln::channel::{Channel, ChannelError};
24 use ln::{chan_utils, onion_utils};
25 use routing::router::{Route, RouteHop, get_route};
26 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
27 use ln::msgs;
28 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
29 use util::enforcing_trait_impls::EnforcingSigner;
30 use util::{byte_utils, test_utils};
31 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
32 use util::errors::APIError;
33 use util::ser::{Writeable, ReadableArgs};
34 use util::config::UserConfig;
35
36 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
37 use bitcoin::hash_types::{Txid, BlockHash};
38 use bitcoin::blockdata::block::{Block, BlockHeader};
39 use bitcoin::blockdata::script::Builder;
40 use bitcoin::blockdata::opcodes;
41 use bitcoin::blockdata::constants::genesis_block;
42 use bitcoin::network::constants::Network;
43
44 use bitcoin::hashes::sha256::Hash as Sha256;
45 use bitcoin::hashes::Hash;
46
47 use bitcoin::secp256k1::{Secp256k1, Message};
48 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
49
50 use regex;
51
52 use std::collections::{BTreeSet, HashMap, HashSet};
53 use std::default::Default;
54 use std::sync::Mutex;
55
56 use ln::functional_test_utils::*;
57 use ln::chan_utils::CommitmentTransaction;
58 use ln::msgs::OptionalField::Present;
59
60 #[test]
61 fn test_insane_channel_opens() {
62         // Stand up a network of 2 nodes
63         let chanmon_cfgs = create_chanmon_cfgs(2);
64         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
65         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
66         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
67
68         // Instantiate channel parameters where we push the maximum msats given our
69         // funding satoshis
70         let channel_value_sat = 31337; // same as funding satoshis
71         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
72         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
73
74         // Have node0 initiate a channel to node1 with aforementioned parameters
75         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
76
77         // Extract the channel open message from node0 to node1
78         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
79
80         // Test helper that asserts we get the correct error string given a mutator
81         // that supposedly makes the channel open message insane
82         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
83                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
84                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
85                 assert_eq!(msg_events.len(), 1);
86                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
87                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
88                         match action {
89                                 &ErrorAction::SendErrorMessage { .. } => {
90                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
91                                 },
92                                 _ => panic!("unexpected event!"),
93                         }
94                 } else { assert!(false); }
95         };
96
97         use ln::channel::MAX_FUNDING_SATOSHIS;
98         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
99
100         // Test all mutations that would make the channel open message insane
101         insane_open_helper(format!("Funding must be smaller than {}. It was {}", MAX_FUNDING_SATOSHIS, MAX_FUNDING_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
102
103         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
104
105         insane_open_helper(r"push_msat \d+ was larger than funding value \d+", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
106
107         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
108
109         insane_open_helper(r"Bogus; channel reserve \(\d+\) is less than dust limit \(\d+\)", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
110
111         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
112
113         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
114
115         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
116
117         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
118 }
119
120 #[test]
121 fn test_async_inbound_update_fee() {
122         let chanmon_cfgs = create_chanmon_cfgs(2);
123         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
124         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
125         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
126         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
127         let logger = test_utils::TestLogger::new();
128         let channel_id = chan.2;
129
130         // balancing
131         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
132
133         // A                                        B
134         // update_fee                            ->
135         // send (1) commitment_signed            -.
136         //                                       <- update_add_htlc/commitment_signed
137         // send (2) RAA (awaiting remote revoke) -.
138         // (1) commitment_signed is delivered    ->
139         //                                       .- send (3) RAA (awaiting remote revoke)
140         // (2) RAA is delivered                  ->
141         //                                       .- send (4) commitment_signed
142         //                                       <- (3) RAA is delivered
143         // send (5) commitment_signed            -.
144         //                                       <- (4) commitment_signed is delivered
145         // send (6) RAA                          -.
146         // (5) commitment_signed is delivered    ->
147         //                                       <- RAA
148         // (6) RAA is delivered                  ->
149
150         // First nodes[0] generates an update_fee
151         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
152         check_added_monitors!(nodes[0], 1);
153
154         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
155         assert_eq!(events_0.len(), 1);
156         let (update_msg, commitment_signed) = match events_0[0] { // (1)
157                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
158                         (update_fee.as_ref(), commitment_signed)
159                 },
160                 _ => panic!("Unexpected event"),
161         };
162
163         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
164
165         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
166         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
167         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
168         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
169         check_added_monitors!(nodes[1], 1);
170
171         let payment_event = {
172                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
173                 assert_eq!(events_1.len(), 1);
174                 SendEvent::from_event(events_1.remove(0))
175         };
176         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
177         assert_eq!(payment_event.msgs.len(), 1);
178
179         // ...now when the messages get delivered everyone should be happy
180         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
181         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
182         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
183         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
184         check_added_monitors!(nodes[0], 1);
185
186         // deliver(1), generate (3):
187         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
188         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
189         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
190         check_added_monitors!(nodes[1], 1);
191
192         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
193         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
194         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
195         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
196         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
197         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
198         assert!(bs_update.update_fee.is_none()); // (4)
199         check_added_monitors!(nodes[1], 1);
200
201         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
202         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
203         assert!(as_update.update_add_htlcs.is_empty()); // (5)
204         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
205         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
206         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
207         assert!(as_update.update_fee.is_none()); // (5)
208         check_added_monitors!(nodes[0], 1);
209
210         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
211         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
212         // only (6) so get_event_msg's assert(len == 1) passes
213         check_added_monitors!(nodes[0], 1);
214
215         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
216         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
217         check_added_monitors!(nodes[1], 1);
218
219         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
220         check_added_monitors!(nodes[0], 1);
221
222         let events_2 = nodes[0].node.get_and_clear_pending_events();
223         assert_eq!(events_2.len(), 1);
224         match events_2[0] {
225                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
226                 _ => panic!("Unexpected event"),
227         }
228
229         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
230         check_added_monitors!(nodes[1], 1);
231 }
232
233 #[test]
234 fn test_update_fee_unordered_raa() {
235         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
236         // crash in an earlier version of the update_fee patch)
237         let chanmon_cfgs = create_chanmon_cfgs(2);
238         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
239         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
240         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
241         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
242         let channel_id = chan.2;
243         let logger = test_utils::TestLogger::new();
244
245         // balancing
246         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
247
248         // First nodes[0] generates an update_fee
249         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
250         check_added_monitors!(nodes[0], 1);
251
252         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
253         assert_eq!(events_0.len(), 1);
254         let update_msg = match events_0[0] { // (1)
255                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
256                         update_fee.as_ref()
257                 },
258                 _ => panic!("Unexpected event"),
259         };
260
261         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
262
263         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
264         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
265         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
266         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
267         check_added_monitors!(nodes[1], 1);
268
269         let payment_event = {
270                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
271                 assert_eq!(events_1.len(), 1);
272                 SendEvent::from_event(events_1.remove(0))
273         };
274         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
275         assert_eq!(payment_event.msgs.len(), 1);
276
277         // ...now when the messages get delivered everyone should be happy
278         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
279         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
280         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
281         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
282         check_added_monitors!(nodes[0], 1);
283
284         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
285         check_added_monitors!(nodes[1], 1);
286
287         // We can't continue, sadly, because our (1) now has a bogus signature
288 }
289
290 #[test]
291 fn test_multi_flight_update_fee() {
292         let chanmon_cfgs = create_chanmon_cfgs(2);
293         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
294         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
295         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
296         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
297         let channel_id = chan.2;
298
299         // A                                        B
300         // update_fee/commitment_signed          ->
301         //                                       .- send (1) RAA and (2) commitment_signed
302         // update_fee (never committed)          ->
303         // (3) update_fee                        ->
304         // We have to manually generate the above update_fee, it is allowed by the protocol but we
305         // don't track which updates correspond to which revoke_and_ack responses so we're in
306         // AwaitingRAA mode and will not generate the update_fee yet.
307         //                                       <- (1) RAA delivered
308         // (3) is generated and send (4) CS      -.
309         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
310         // know the per_commitment_point to use for it.
311         //                                       <- (2) commitment_signed delivered
312         // revoke_and_ack                        ->
313         //                                          B should send no response here
314         // (4) commitment_signed delivered       ->
315         //                                       <- RAA/commitment_signed delivered
316         // revoke_and_ack                        ->
317
318         // First nodes[0] generates an update_fee
319         let initial_feerate = get_feerate!(nodes[0], channel_id);
320         nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
321         check_added_monitors!(nodes[0], 1);
322
323         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
324         assert_eq!(events_0.len(), 1);
325         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
326                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
327                         (update_fee.as_ref().unwrap(), commitment_signed)
328                 },
329                 _ => panic!("Unexpected event"),
330         };
331
332         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
333         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
334         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
335         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
336         check_added_monitors!(nodes[1], 1);
337
338         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
339         // transaction:
340         nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
341         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
342         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
343
344         // Create the (3) update_fee message that nodes[0] will generate before it does...
345         let mut update_msg_2 = msgs::UpdateFee {
346                 channel_id: update_msg_1.channel_id.clone(),
347                 feerate_per_kw: (initial_feerate + 30) as u32,
348         };
349
350         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
351
352         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
353         // Deliver (3)
354         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
355
356         // Deliver (1), generating (3) and (4)
357         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
358         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
359         check_added_monitors!(nodes[0], 1);
360         assert!(as_second_update.update_add_htlcs.is_empty());
361         assert!(as_second_update.update_fulfill_htlcs.is_empty());
362         assert!(as_second_update.update_fail_htlcs.is_empty());
363         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
364         // Check that the update_fee newly generated matches what we delivered:
365         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
366         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
367
368         // Deliver (2) commitment_signed
369         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
370         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
371         check_added_monitors!(nodes[0], 1);
372         // No commitment_signed so get_event_msg's assert(len == 1) passes
373
374         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
375         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
376         check_added_monitors!(nodes[1], 1);
377
378         // Delever (4)
379         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
380         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
381         check_added_monitors!(nodes[1], 1);
382
383         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
384         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
385         check_added_monitors!(nodes[0], 1);
386
387         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
388         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
389         // No commitment_signed so get_event_msg's assert(len == 1) passes
390         check_added_monitors!(nodes[0], 1);
391
392         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
393         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
394         check_added_monitors!(nodes[1], 1);
395 }
396
397 fn do_test_1_conf_open(connect_style: ConnectStyle) {
398         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
399         // tests that we properly send one in that case.
400         let mut alice_config = UserConfig::default();
401         alice_config.own_channel_config.minimum_depth = 1;
402         alice_config.channel_options.announced_channel = true;
403         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
404         let mut bob_config = UserConfig::default();
405         bob_config.own_channel_config.minimum_depth = 1;
406         bob_config.channel_options.announced_channel = true;
407         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
408         let chanmon_cfgs = create_chanmon_cfgs(2);
409         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
410         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
411         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
412         *nodes[0].connect_style.borrow_mut() = connect_style;
413
414         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
415         mine_transaction(&nodes[1], &tx);
416         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id()));
417
418         mine_transaction(&nodes[0], &tx);
419         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
420         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
421
422         for node in nodes {
423                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
424                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
425                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
426         }
427 }
428 #[test]
429 fn test_1_conf_open() {
430         do_test_1_conf_open(ConnectStyle::BestBlockFirst);
431         do_test_1_conf_open(ConnectStyle::TransactionsFirst);
432         do_test_1_conf_open(ConnectStyle::FullBlockViaListen);
433 }
434
435 fn do_test_sanity_on_in_flight_opens(steps: u8) {
436         // Previously, we had issues deserializing channels when we hadn't connected the first block
437         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
438         // serialization round-trips and simply do steps towards opening a channel and then drop the
439         // Node objects.
440
441         let chanmon_cfgs = create_chanmon_cfgs(2);
442         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
443         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
444         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
445
446         if steps & 0b1000_0000 != 0{
447                 let block = Block {
448                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
449                         txdata: vec![],
450                 };
451                 connect_block(&nodes[0], &block);
452                 connect_block(&nodes[1], &block);
453         }
454
455         if steps & 0x0f == 0 { return; }
456         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
457         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
458
459         if steps & 0x0f == 1 { return; }
460         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
461         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
462
463         if steps & 0x0f == 2 { return; }
464         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
465
466         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
467
468         if steps & 0x0f == 3 { return; }
469         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
470         check_added_monitors!(nodes[0], 0);
471         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
472
473         if steps & 0x0f == 4 { return; }
474         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
475         {
476                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
477                 assert_eq!(added_monitors.len(), 1);
478                 assert_eq!(added_monitors[0].0, funding_output);
479                 added_monitors.clear();
480         }
481         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
482
483         if steps & 0x0f == 5 { return; }
484         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
485         {
486                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
487                 assert_eq!(added_monitors.len(), 1);
488                 assert_eq!(added_monitors[0].0, funding_output);
489                 added_monitors.clear();
490         }
491
492         let events_4 = nodes[0].node.get_and_clear_pending_events();
493         assert_eq!(events_4.len(), 0);
494
495         if steps & 0x0f == 6 { return; }
496         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
497
498         if steps & 0x0f == 7 { return; }
499         confirm_transaction_at(&nodes[0], &tx, 2);
500         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
501         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
502 }
503
504 #[test]
505 fn test_sanity_on_in_flight_opens() {
506         do_test_sanity_on_in_flight_opens(0);
507         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
508         do_test_sanity_on_in_flight_opens(1);
509         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
510         do_test_sanity_on_in_flight_opens(2);
511         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
512         do_test_sanity_on_in_flight_opens(3);
513         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
514         do_test_sanity_on_in_flight_opens(4);
515         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
516         do_test_sanity_on_in_flight_opens(5);
517         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
518         do_test_sanity_on_in_flight_opens(6);
519         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
520         do_test_sanity_on_in_flight_opens(7);
521         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
522         do_test_sanity_on_in_flight_opens(8);
523         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
524 }
525
526 #[test]
527 fn test_update_fee_vanilla() {
528         let chanmon_cfgs = create_chanmon_cfgs(2);
529         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
530         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
531         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
532         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
533         let channel_id = chan.2;
534
535         let feerate = get_feerate!(nodes[0], channel_id);
536         nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
537         check_added_monitors!(nodes[0], 1);
538
539         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
540         assert_eq!(events_0.len(), 1);
541         let (update_msg, commitment_signed) = match events_0[0] {
542                         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 } } => {
543                         (update_fee.as_ref(), commitment_signed)
544                 },
545                 _ => panic!("Unexpected event"),
546         };
547         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
548
549         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
550         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
551         check_added_monitors!(nodes[1], 1);
552
553         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
554         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
555         check_added_monitors!(nodes[0], 1);
556
557         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
558         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
559         // No commitment_signed so get_event_msg's assert(len == 1) passes
560         check_added_monitors!(nodes[0], 1);
561
562         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
563         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
564         check_added_monitors!(nodes[1], 1);
565 }
566
567 #[test]
568 fn test_update_fee_that_funder_cannot_afford() {
569         let chanmon_cfgs = create_chanmon_cfgs(2);
570         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
571         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
572         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
573         let channel_value = 1888;
574         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
575         let channel_id = chan.2;
576
577         let feerate = 260;
578         nodes[0].node.update_fee(channel_id, feerate).unwrap();
579         check_added_monitors!(nodes[0], 1);
580         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
581
582         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
583
584         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
585
586         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
587         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
588         {
589                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
590
591                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
592                 let num_htlcs = commitment_tx.output.len() - 2;
593                 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
594                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
595                 actual_fee = channel_value - actual_fee;
596                 assert_eq!(total_fee, actual_fee);
597         }
598
599         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
600         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
601         nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
602         check_added_monitors!(nodes[0], 1);
603
604         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
605
606         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
607
608         //While producing the commitment_signed response after handling a received update_fee request the
609         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
610         //Should produce and error.
611         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
612         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
613         check_added_monitors!(nodes[1], 1);
614         check_closed_broadcast!(nodes[1], true);
615 }
616
617 #[test]
618 fn test_update_fee_with_fundee_update_add_htlc() {
619         let chanmon_cfgs = create_chanmon_cfgs(2);
620         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
621         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
622         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
623         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
624         let channel_id = chan.2;
625         let logger = test_utils::TestLogger::new();
626
627         // balancing
628         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
629
630         let feerate = get_feerate!(nodes[0], channel_id);
631         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
632         check_added_monitors!(nodes[0], 1);
633
634         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
635         assert_eq!(events_0.len(), 1);
636         let (update_msg, commitment_signed) = match events_0[0] {
637                         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 } } => {
638                         (update_fee.as_ref(), commitment_signed)
639                 },
640                 _ => panic!("Unexpected event"),
641         };
642         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
643         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
644         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
645         check_added_monitors!(nodes[1], 1);
646
647         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
648         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
649         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();
650
651         // nothing happens since node[1] is in AwaitingRemoteRevoke
652         nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
653         {
654                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
655                 assert_eq!(added_monitors.len(), 0);
656                 added_monitors.clear();
657         }
658         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
659         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
660         // node[1] has nothing to do
661
662         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
663         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
664         check_added_monitors!(nodes[0], 1);
665
666         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
667         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
668         // No commitment_signed so get_event_msg's assert(len == 1) passes
669         check_added_monitors!(nodes[0], 1);
670         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
671         check_added_monitors!(nodes[1], 1);
672         // AwaitingRemoteRevoke ends here
673
674         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
675         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
676         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
677         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
678         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
679         assert_eq!(commitment_update.update_fee.is_none(), true);
680
681         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
682         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
683         check_added_monitors!(nodes[0], 1);
684         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
685
686         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
687         check_added_monitors!(nodes[1], 1);
688         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
689
690         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
691         check_added_monitors!(nodes[1], 1);
692         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
693         // No commitment_signed so get_event_msg's assert(len == 1) passes
694
695         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
696         check_added_monitors!(nodes[0], 1);
697         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
698
699         expect_pending_htlcs_forwardable!(nodes[0]);
700
701         let events = nodes[0].node.get_and_clear_pending_events();
702         assert_eq!(events.len(), 1);
703         match events[0] {
704                 Event::PaymentReceived { .. } => { },
705                 _ => panic!("Unexpected event"),
706         };
707
708         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
709
710         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
711         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
712         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
713 }
714
715 #[test]
716 fn test_update_fee() {
717         let chanmon_cfgs = create_chanmon_cfgs(2);
718         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
719         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
720         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
721         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
722         let channel_id = chan.2;
723
724         // A                                        B
725         // (1) update_fee/commitment_signed      ->
726         //                                       <- (2) revoke_and_ack
727         //                                       .- send (3) commitment_signed
728         // (4) update_fee/commitment_signed      ->
729         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
730         //                                       <- (3) commitment_signed delivered
731         // send (6) revoke_and_ack               -.
732         //                                       <- (5) deliver revoke_and_ack
733         // (6) deliver revoke_and_ack            ->
734         //                                       .- send (7) commitment_signed in response to (4)
735         //                                       <- (7) deliver commitment_signed
736         // revoke_and_ack                        ->
737
738         // Create and deliver (1)...
739         let feerate = get_feerate!(nodes[0], channel_id);
740         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
741         check_added_monitors!(nodes[0], 1);
742
743         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
744         assert_eq!(events_0.len(), 1);
745         let (update_msg, commitment_signed) = match events_0[0] {
746                         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 } } => {
747                         (update_fee.as_ref(), commitment_signed)
748                 },
749                 _ => panic!("Unexpected event"),
750         };
751         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
752
753         // Generate (2) and (3):
754         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
755         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
756         check_added_monitors!(nodes[1], 1);
757
758         // Deliver (2):
759         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
760         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
761         check_added_monitors!(nodes[0], 1);
762
763         // Create and deliver (4)...
764         nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
765         check_added_monitors!(nodes[0], 1);
766         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
767         assert_eq!(events_0.len(), 1);
768         let (update_msg, commitment_signed) = match events_0[0] {
769                         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 } } => {
770                         (update_fee.as_ref(), commitment_signed)
771                 },
772                 _ => panic!("Unexpected event"),
773         };
774
775         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
776         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
777         check_added_monitors!(nodes[1], 1);
778         // ... creating (5)
779         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
780         // No commitment_signed so get_event_msg's assert(len == 1) passes
781
782         // Handle (3), creating (6):
783         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
784         check_added_monitors!(nodes[0], 1);
785         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
786         // No commitment_signed so get_event_msg's assert(len == 1) passes
787
788         // Deliver (5):
789         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
790         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
791         check_added_monitors!(nodes[0], 1);
792
793         // Deliver (6), creating (7):
794         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
795         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
796         assert!(commitment_update.update_add_htlcs.is_empty());
797         assert!(commitment_update.update_fulfill_htlcs.is_empty());
798         assert!(commitment_update.update_fail_htlcs.is_empty());
799         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
800         assert!(commitment_update.update_fee.is_none());
801         check_added_monitors!(nodes[1], 1);
802
803         // Deliver (7)
804         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
805         check_added_monitors!(nodes[0], 1);
806         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
807         // No commitment_signed so get_event_msg's assert(len == 1) passes
808
809         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
810         check_added_monitors!(nodes[1], 1);
811         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
812
813         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
814         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
815         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
816 }
817
818 #[test]
819 fn pre_funding_lock_shutdown_test() {
820         // Test sending a shutdown prior to funding_locked after funding generation
821         let chanmon_cfgs = create_chanmon_cfgs(2);
822         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
823         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
824         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
825         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
826         mine_transaction(&nodes[0], &tx);
827         mine_transaction(&nodes[1], &tx);
828
829         nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
830         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
831         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
832         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
833         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
834
835         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
836         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
837         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
838         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
839         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
840         assert!(node_0_none.is_none());
841
842         assert!(nodes[0].node.list_channels().is_empty());
843         assert!(nodes[1].node.list_channels().is_empty());
844 }
845
846 #[test]
847 fn updates_shutdown_wait() {
848         // Test sending a shutdown with outstanding updates pending
849         let chanmon_cfgs = create_chanmon_cfgs(3);
850         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
851         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
852         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
853         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
854         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
855         let logger = test_utils::TestLogger::new();
856
857         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
858
859         nodes[0].node.close_channel(&chan_1.2).unwrap();
860         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
861         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
862         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
863         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
864
865         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
866         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
867
868         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
869
870         let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
871         let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
872         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();
873         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();
874         unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
875         unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
876
877         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
878         check_added_monitors!(nodes[2], 1);
879         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
880         assert!(updates.update_add_htlcs.is_empty());
881         assert!(updates.update_fail_htlcs.is_empty());
882         assert!(updates.update_fail_malformed_htlcs.is_empty());
883         assert!(updates.update_fee.is_none());
884         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
885         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
886         check_added_monitors!(nodes[1], 1);
887         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
888         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
889
890         assert!(updates_2.update_add_htlcs.is_empty());
891         assert!(updates_2.update_fail_htlcs.is_empty());
892         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
893         assert!(updates_2.update_fee.is_none());
894         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
895         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
896         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
897
898         let events = nodes[0].node.get_and_clear_pending_events();
899         assert_eq!(events.len(), 1);
900         match events[0] {
901                 Event::PaymentSent { ref payment_preimage } => {
902                         assert_eq!(our_payment_preimage, *payment_preimage);
903                 },
904                 _ => panic!("Unexpected event"),
905         }
906
907         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
908         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
909         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
910         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
911         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
912         assert!(node_0_none.is_none());
913
914         assert!(nodes[0].node.list_channels().is_empty());
915
916         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
917         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
918         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
919         assert!(nodes[1].node.list_channels().is_empty());
920         assert!(nodes[2].node.list_channels().is_empty());
921 }
922
923 #[test]
924 fn htlc_fail_async_shutdown() {
925         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
926         let chanmon_cfgs = create_chanmon_cfgs(3);
927         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
928         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
929         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
930         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
931         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
932         let logger = test_utils::TestLogger::new();
933
934         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
935         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
936         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();
937         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
938         check_added_monitors!(nodes[0], 1);
939         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
940         assert_eq!(updates.update_add_htlcs.len(), 1);
941         assert!(updates.update_fulfill_htlcs.is_empty());
942         assert!(updates.update_fail_htlcs.is_empty());
943         assert!(updates.update_fail_malformed_htlcs.is_empty());
944         assert!(updates.update_fee.is_none());
945
946         nodes[1].node.close_channel(&chan_1.2).unwrap();
947         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
948         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
949         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
950
951         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
952         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
953         check_added_monitors!(nodes[1], 1);
954         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
955         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
956
957         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
958         assert!(updates_2.update_add_htlcs.is_empty());
959         assert!(updates_2.update_fulfill_htlcs.is_empty());
960         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
961         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
962         assert!(updates_2.update_fee.is_none());
963
964         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
965         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
966
967         expect_payment_failed!(nodes[0], our_payment_hash, false);
968
969         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
970         assert_eq!(msg_events.len(), 2);
971         let node_0_closing_signed = match msg_events[0] {
972                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
973                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
974                         (*msg).clone()
975                 },
976                 _ => panic!("Unexpected event"),
977         };
978         match msg_events[1] {
979                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
980                         assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
981                 },
982                 _ => panic!("Unexpected event"),
983         }
984
985         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
986         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
987         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
988         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
989         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
990         assert!(node_0_none.is_none());
991
992         assert!(nodes[0].node.list_channels().is_empty());
993
994         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
995         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
996         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
997         assert!(nodes[1].node.list_channels().is_empty());
998         assert!(nodes[2].node.list_channels().is_empty());
999 }
1000
1001 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1002         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1003         // messages delivered prior to disconnect
1004         let chanmon_cfgs = create_chanmon_cfgs(3);
1005         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1006         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1007         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1008         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1009         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1010
1011         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1012
1013         nodes[1].node.close_channel(&chan_1.2).unwrap();
1014         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1015         if recv_count > 0 {
1016                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
1017                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1018                 if recv_count > 1 {
1019                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
1020                 }
1021         }
1022
1023         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1024         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1025
1026         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1027         let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1028         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1029         let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1030
1031         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1032         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1033         assert!(node_1_shutdown == node_1_2nd_shutdown);
1034
1035         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1036         let node_0_2nd_shutdown = if recv_count > 0 {
1037                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1038                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1039                 node_0_2nd_shutdown
1040         } else {
1041                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1042                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1043                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1044         };
1045         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_2nd_shutdown);
1046
1047         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1048         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1049
1050         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1051         check_added_monitors!(nodes[2], 1);
1052         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1053         assert!(updates.update_add_htlcs.is_empty());
1054         assert!(updates.update_fail_htlcs.is_empty());
1055         assert!(updates.update_fail_malformed_htlcs.is_empty());
1056         assert!(updates.update_fee.is_none());
1057         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1058         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1059         check_added_monitors!(nodes[1], 1);
1060         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1061         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1062
1063         assert!(updates_2.update_add_htlcs.is_empty());
1064         assert!(updates_2.update_fail_htlcs.is_empty());
1065         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1066         assert!(updates_2.update_fee.is_none());
1067         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1068         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1069         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1070
1071         let events = nodes[0].node.get_and_clear_pending_events();
1072         assert_eq!(events.len(), 1);
1073         match events[0] {
1074                 Event::PaymentSent { ref payment_preimage } => {
1075                         assert_eq!(our_payment_preimage, *payment_preimage);
1076                 },
1077                 _ => panic!("Unexpected event"),
1078         }
1079
1080         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1081         if recv_count > 0 {
1082                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1083                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1084                 assert!(node_1_closing_signed.is_some());
1085         }
1086
1087         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1088         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1089
1090         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1091         let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1092         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1093         if recv_count == 0 {
1094                 // If all closing_signeds weren't delivered we can just resume where we left off...
1095                 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1096
1097                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1098                 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1099                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1100
1101                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1102                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1103                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1104
1105                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_3rd_shutdown);
1106                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1107
1108                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_3rd_shutdown);
1109                 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1110                 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1111
1112                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1113                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1114                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1115                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1116                 assert!(node_0_none.is_none());
1117         } else {
1118                 // If one node, however, received + responded with an identical closing_signed we end
1119                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1120                 // There isn't really anything better we can do simply, but in the future we might
1121                 // explore storing a set of recently-closed channels that got disconnected during
1122                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1123                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1124                 // transaction.
1125                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1126
1127                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1128                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1129                 assert_eq!(msg_events.len(), 1);
1130                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1131                         match action {
1132                                 &ErrorAction::SendErrorMessage { ref msg } => {
1133                                         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1134                                         assert_eq!(msg.channel_id, chan_1.2);
1135                                 },
1136                                 _ => panic!("Unexpected event!"),
1137                         }
1138                 } else { panic!("Needed SendErrorMessage close"); }
1139
1140                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1141                 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1142                 // closing_signed so we do it ourselves
1143                 check_closed_broadcast!(nodes[0], false);
1144                 check_added_monitors!(nodes[0], 1);
1145         }
1146
1147         assert!(nodes[0].node.list_channels().is_empty());
1148
1149         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1150         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1151         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1152         assert!(nodes[1].node.list_channels().is_empty());
1153         assert!(nodes[2].node.list_channels().is_empty());
1154 }
1155
1156 #[test]
1157 fn test_shutdown_rebroadcast() {
1158         do_test_shutdown_rebroadcast(0);
1159         do_test_shutdown_rebroadcast(1);
1160         do_test_shutdown_rebroadcast(2);
1161 }
1162
1163 #[test]
1164 fn fake_network_test() {
1165         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1166         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1167         let chanmon_cfgs = create_chanmon_cfgs(4);
1168         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1169         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1170         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1171
1172         // Create some initial channels
1173         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1174         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1175         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1176
1177         // Rebalance the network a bit by relaying one payment through all the channels...
1178         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
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
1183         // Send some more payments
1184         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1185         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1186         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1187
1188         // Test failure packets
1189         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1190         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1191
1192         // Add a new channel that skips 3
1193         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1194
1195         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1196         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1197         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_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
1203         // Do some rebalance loop payments, simultaneously
1204         let mut hops = Vec::with_capacity(3);
1205         hops.push(RouteHop {
1206                 pubkey: nodes[2].node.get_our_node_id(),
1207                 node_features: NodeFeatures::empty(),
1208                 short_channel_id: chan_2.0.contents.short_channel_id,
1209                 channel_features: ChannelFeatures::empty(),
1210                 fee_msat: 0,
1211                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1212         });
1213         hops.push(RouteHop {
1214                 pubkey: nodes[3].node.get_our_node_id(),
1215                 node_features: NodeFeatures::empty(),
1216                 short_channel_id: chan_3.0.contents.short_channel_id,
1217                 channel_features: ChannelFeatures::empty(),
1218                 fee_msat: 0,
1219                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1220         });
1221         hops.push(RouteHop {
1222                 pubkey: nodes[1].node.get_our_node_id(),
1223                 node_features: NodeFeatures::empty(),
1224                 short_channel_id: chan_4.0.contents.short_channel_id,
1225                 channel_features: ChannelFeatures::empty(),
1226                 fee_msat: 1000000,
1227                 cltv_expiry_delta: TEST_FINAL_CLTV,
1228         });
1229         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;
1230         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;
1231         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1232
1233         let mut hops = Vec::with_capacity(3);
1234         hops.push(RouteHop {
1235                 pubkey: nodes[3].node.get_our_node_id(),
1236                 node_features: NodeFeatures::empty(),
1237                 short_channel_id: chan_4.0.contents.short_channel_id,
1238                 channel_features: ChannelFeatures::empty(),
1239                 fee_msat: 0,
1240                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1241         });
1242         hops.push(RouteHop {
1243                 pubkey: nodes[2].node.get_our_node_id(),
1244                 node_features: NodeFeatures::empty(),
1245                 short_channel_id: chan_3.0.contents.short_channel_id,
1246                 channel_features: ChannelFeatures::empty(),
1247                 fee_msat: 0,
1248                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1249         });
1250         hops.push(RouteHop {
1251                 pubkey: nodes[1].node.get_our_node_id(),
1252                 node_features: NodeFeatures::empty(),
1253                 short_channel_id: chan_2.0.contents.short_channel_id,
1254                 channel_features: ChannelFeatures::empty(),
1255                 fee_msat: 1000000,
1256                 cltv_expiry_delta: TEST_FINAL_CLTV,
1257         });
1258         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;
1259         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;
1260         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1261
1262         // Claim the rebalances...
1263         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1264         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1265
1266         // Add a duplicate new channel from 2 to 4
1267         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1268
1269         // Send some payments across both channels
1270         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1271         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1272         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1273
1274
1275         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1276         let events = nodes[0].node.get_and_clear_pending_msg_events();
1277         assert_eq!(events.len(), 0);
1278         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);
1279
1280         //TODO: Test that routes work again here as we've been notified that the channel is full
1281
1282         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1283         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1284         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1285
1286         // Close down the channels...
1287         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1288         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1289         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1290         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1291         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1292 }
1293
1294 #[test]
1295 fn holding_cell_htlc_counting() {
1296         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1297         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1298         // commitment dance rounds.
1299         let chanmon_cfgs = create_chanmon_cfgs(3);
1300         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1301         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1302         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1303         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1304         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1305         let logger = test_utils::TestLogger::new();
1306
1307         let mut payments = Vec::new();
1308         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1309                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1310                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1311                 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();
1312                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1313                 payments.push((payment_preimage, payment_hash));
1314         }
1315         check_added_monitors!(nodes[1], 1);
1316
1317         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1318         assert_eq!(events.len(), 1);
1319         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1320         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1321
1322         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1323         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1324         // another HTLC.
1325         let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1326         {
1327                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1328                 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();
1329                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1330                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1331                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1332                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1333         }
1334
1335         // This should also be true if we try to forward a payment.
1336         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1337         {
1338                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1339                 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();
1340                 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1341                 check_added_monitors!(nodes[0], 1);
1342         }
1343
1344         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1345         assert_eq!(events.len(), 1);
1346         let payment_event = SendEvent::from_event(events.pop().unwrap());
1347         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1348
1349         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1350         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1351         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1352         // fails), the second will process the resulting failure and fail the HTLC backward.
1353         expect_pending_htlcs_forwardable!(nodes[1]);
1354         expect_pending_htlcs_forwardable!(nodes[1]);
1355         check_added_monitors!(nodes[1], 1);
1356
1357         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1358         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1359         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1360
1361         let events = nodes[0].node.get_and_clear_pending_msg_events();
1362         assert_eq!(events.len(), 1);
1363         match events[0] {
1364                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1365                         assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1366                 },
1367                 _ => panic!("Unexpected event"),
1368         }
1369
1370         expect_payment_failed!(nodes[0], payment_hash_2, false);
1371
1372         // Now forward all the pending HTLCs and claim them back
1373         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1374         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1375         check_added_monitors!(nodes[2], 1);
1376
1377         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1378         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1379         check_added_monitors!(nodes[1], 1);
1380         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1381
1382         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1383         check_added_monitors!(nodes[1], 1);
1384         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1385
1386         for ref update in as_updates.update_add_htlcs.iter() {
1387                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1388         }
1389         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1390         check_added_monitors!(nodes[2], 1);
1391         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1392         check_added_monitors!(nodes[2], 1);
1393         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1394
1395         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1396         check_added_monitors!(nodes[1], 1);
1397         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1398         check_added_monitors!(nodes[1], 1);
1399         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1400
1401         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1402         check_added_monitors!(nodes[2], 1);
1403
1404         expect_pending_htlcs_forwardable!(nodes[2]);
1405
1406         let events = nodes[2].node.get_and_clear_pending_events();
1407         assert_eq!(events.len(), payments.len());
1408         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1409                 match event {
1410                         &Event::PaymentReceived { ref payment_hash, .. } => {
1411                                 assert_eq!(*payment_hash, *hash);
1412                         },
1413                         _ => panic!("Unexpected event"),
1414                 };
1415         }
1416
1417         for (preimage, _) in payments.drain(..) {
1418                 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1419         }
1420
1421         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1422 }
1423
1424 #[test]
1425 fn duplicate_htlc_test() {
1426         // Test that we accept duplicate payment_hash HTLCs across the network and that
1427         // claiming/failing them are all separate and don't affect each other
1428         let chanmon_cfgs = create_chanmon_cfgs(6);
1429         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1430         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1431         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1432
1433         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1434         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1435         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1436         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1437         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1438         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1439
1440         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1441
1442         *nodes[0].network_payment_count.borrow_mut() -= 1;
1443         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1444
1445         *nodes[0].network_payment_count.borrow_mut() -= 1;
1446         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1447
1448         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1449         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1450         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1451 }
1452
1453 #[test]
1454 fn test_duplicate_htlc_different_direction_onchain() {
1455         // Test that ChannelMonitor doesn't generate 2 preimage txn
1456         // when we have 2 HTLCs with same preimage that go across a node
1457         // in opposite directions.
1458         let chanmon_cfgs = create_chanmon_cfgs(2);
1459         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1460         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1461         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1462
1463         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1464         let logger = test_utils::TestLogger::new();
1465
1466         // balancing
1467         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1468
1469         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1470
1471         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1472         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();
1473         send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1474
1475         // Provide preimage to node 0 by claiming payment
1476         nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1477         check_added_monitors!(nodes[0], 1);
1478
1479         // Broadcast node 1 commitment txn
1480         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1481
1482         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1483         let mut has_both_htlcs = 0; // check htlcs match ones committed
1484         for outp in remote_txn[0].output.iter() {
1485                 if outp.value == 800_000 / 1000 {
1486                         has_both_htlcs += 1;
1487                 } else if outp.value == 900_000 / 1000 {
1488                         has_both_htlcs += 1;
1489                 }
1490         }
1491         assert_eq!(has_both_htlcs, 2);
1492
1493         mine_transaction(&nodes[0], &remote_txn[0]);
1494         check_added_monitors!(nodes[0], 1);
1495
1496         // Check we only broadcast 1 timeout tx
1497         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1498         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()) };
1499         assert_eq!(claim_txn.len(), 5);
1500         check_spends!(claim_txn[2], chan_1.3);
1501         check_spends!(claim_txn[3], claim_txn[2]);
1502         assert_eq!(htlc_pair.0.input.len(), 1);
1503         assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1504         check_spends!(htlc_pair.0, remote_txn[0]);
1505         assert_eq!(htlc_pair.1.input.len(), 1);
1506         assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1507         check_spends!(htlc_pair.1, remote_txn[0]);
1508
1509         let events = nodes[0].node.get_and_clear_pending_msg_events();
1510         assert_eq!(events.len(), 3);
1511         for e in events {
1512                 match e {
1513                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1514                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1515                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1516                                 assert_eq!(msg.data, "Commitment or closing transaction was confirmed on chain.");
1517                         },
1518                         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, .. } } => {
1519                                 assert!(update_add_htlcs.is_empty());
1520                                 assert!(update_fail_htlcs.is_empty());
1521                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1522                                 assert!(update_fail_malformed_htlcs.is_empty());
1523                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1524                         },
1525                         _ => panic!("Unexpected event"),
1526                 }
1527         }
1528 }
1529
1530 #[test]
1531 fn test_basic_channel_reserve() {
1532         let chanmon_cfgs = create_chanmon_cfgs(2);
1533         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1534         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1535         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1536         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1537         let logger = test_utils::TestLogger::new();
1538
1539         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1540         let channel_reserve = chan_stat.channel_reserve_msat;
1541
1542         // The 2* and +1 are for the fee spike reserve.
1543         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1544         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1545         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1546         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1547         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();
1548         let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1549         match err {
1550                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1551                         match &fails[0] {
1552                                 &APIError::ChannelUnavailable{ref err} =>
1553                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1554                                 _ => panic!("Unexpected error variant"),
1555                         }
1556                 },
1557                 _ => panic!("Unexpected error variant"),
1558         }
1559         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1560         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);
1561
1562         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1563 }
1564
1565 #[test]
1566 fn test_fee_spike_violation_fails_htlc() {
1567         let chanmon_cfgs = create_chanmon_cfgs(2);
1568         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1569         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1570         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1571         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1572         let logger = test_utils::TestLogger::new();
1573
1574         macro_rules! get_route_and_payment_hash {
1575                 ($recv_value: expr) => {{
1576                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1577                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1578                         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();
1579                         (route, payment_hash, payment_preimage)
1580                 }}
1581         }
1582
1583         let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1584         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1585         let secp_ctx = Secp256k1::new();
1586         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1587
1588         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1589
1590         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1591         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1592         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1593         let msg = msgs::UpdateAddHTLC {
1594                 channel_id: chan.2,
1595                 htlc_id: 0,
1596                 amount_msat: htlc_msat,
1597                 payment_hash: payment_hash,
1598                 cltv_expiry: htlc_cltv,
1599                 onion_routing_packet: onion_packet,
1600         };
1601
1602         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1603
1604         // Now manually create the commitment_signed message corresponding to the update_add
1605         // nodes[0] just sent. In the code for construction of this message, "local" refers
1606         // to the sender of the message, and "remote" refers to the receiver.
1607
1608         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1609
1610         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1611
1612         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1613         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1614         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point) = {
1615                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1616                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1617                 let chan_signer = local_chan.get_signer();
1618                 let pubkeys = chan_signer.pubkeys();
1619                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1620                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1621                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
1622         };
1623         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point) = {
1624                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1625                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1626                 let chan_signer = remote_chan.get_signer();
1627                 let pubkeys = chan_signer.pubkeys();
1628                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1629                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
1630         };
1631
1632         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1633         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1634                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1635
1636         // Build the remote commitment transaction so we can sign it, and then later use the
1637         // signature for the commitment_signed message.
1638         let local_chan_balance = 1313;
1639
1640         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1641                 offered: false,
1642                 amount_msat: 3460001,
1643                 cltv_expiry: htlc_cltv,
1644                 payment_hash,
1645                 transaction_output_index: Some(1),
1646         };
1647
1648         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1649
1650         let res = {
1651                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1652                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1653                 let local_chan_signer = local_chan.get_signer();
1654                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1655                         commitment_number,
1656                         95000,
1657                         local_chan_balance,
1658                         commit_tx_keys.clone(),
1659                         feerate_per_kw,
1660                         &mut vec![(accepted_htlc_info, ())],
1661                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1662                 );
1663                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1664         };
1665
1666         let commit_signed_msg = msgs::CommitmentSigned {
1667                 channel_id: chan.2,
1668                 signature: res.0,
1669                 htlc_signatures: res.1
1670         };
1671
1672         // Send the commitment_signed message to the nodes[1].
1673         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1674         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1675
1676         // Send the RAA to nodes[1].
1677         let raa_msg = msgs::RevokeAndACK {
1678                 channel_id: chan.2,
1679                 per_commitment_secret: local_secret,
1680                 next_per_commitment_point: next_local_point
1681         };
1682         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1683
1684         let events = nodes[1].node.get_and_clear_pending_msg_events();
1685         assert_eq!(events.len(), 1);
1686         // Make sure the HTLC failed in the way we expect.
1687         match events[0] {
1688                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1689                         assert_eq!(update_fail_htlcs.len(), 1);
1690                         update_fail_htlcs[0].clone()
1691                 },
1692                 _ => panic!("Unexpected event"),
1693         };
1694         nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1695
1696         check_added_monitors!(nodes[1], 2);
1697 }
1698
1699 #[test]
1700 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1701         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1702         // Set the fee rate for the channel very high, to the point where the fundee
1703         // sending any above-dust amount would result in a channel reserve violation.
1704         // In this test we check that we would be prevented from sending an HTLC in
1705         // this situation.
1706         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1707         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1708         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1709         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1710         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1711         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1712         let logger = test_utils::TestLogger::new();
1713
1714         macro_rules! get_route_and_payment_hash {
1715                 ($recv_value: expr) => {{
1716                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1717                         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1718                         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();
1719                         (route, payment_hash, payment_preimage)
1720                 }}
1721         }
1722
1723         let (route, our_payment_hash, _) = get_route_and_payment_hash!(4843000);
1724         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1725                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1726         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1727         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);
1728 }
1729
1730 #[test]
1731 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1732         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1733         // Set the fee rate for the channel very high, to the point where the funder
1734         // receiving 1 update_add_htlc would result in them closing the channel due
1735         // to channel reserve violation. This close could also happen if the fee went
1736         // up a more realistic amount, but many HTLCs were outstanding at the time of
1737         // the update_add_htlc.
1738         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1739         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1740         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1741         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1742         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1743         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1744         let logger = test_utils::TestLogger::new();
1745
1746         macro_rules! get_route_and_payment_hash {
1747                 ($recv_value: expr) => {{
1748                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1749                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1750                         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();
1751                         (route, payment_hash, payment_preimage)
1752                 }}
1753         }
1754
1755         let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1756         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1757         let secp_ctx = Secp256k1::new();
1758         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1759         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1760         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1761         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1762         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1763         let msg = msgs::UpdateAddHTLC {
1764                 channel_id: chan.2,
1765                 htlc_id: 1,
1766                 amount_msat: htlc_msat + 1,
1767                 payment_hash: payment_hash,
1768                 cltv_expiry: htlc_cltv,
1769                 onion_routing_packet: onion_packet,
1770         };
1771
1772         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1773         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1774         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);
1775         assert_eq!(nodes[0].node.list_channels().len(), 0);
1776         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1777         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1778         check_added_monitors!(nodes[0], 1);
1779 }
1780
1781 #[test]
1782 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1783         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1784         // calculating our commitment transaction fee (this was previously broken).
1785         let chanmon_cfgs = create_chanmon_cfgs(2);
1786         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1787         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1788         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1789
1790         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1791         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1792         // transaction fee with 0 HTLCs (183 sats)).
1793         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98817000, InitFeatures::known(), InitFeatures::known());
1794
1795         let dust_amt = 329000; // Dust amount
1796         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1797         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1798         // commitment transaction fee.
1799         let (_, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1800 }
1801
1802 #[test]
1803 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1804         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1805         // calculating our counterparty's commitment transaction fee (this was previously broken).
1806         let chanmon_cfgs = create_chanmon_cfgs(2);
1807         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1808         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1809         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1810         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1811
1812         let payment_amt = 46000; // Dust amount
1813         // In the previous code, these first four payments would succeed.
1814         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1815         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1816         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1817         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1818
1819         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1820         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1821         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1822         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1823         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1824         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1825
1826         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1827         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1828         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1829         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1830 }
1831
1832 #[test]
1833 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1834         let chanmon_cfgs = create_chanmon_cfgs(3);
1835         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1836         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1837         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1838         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1839         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1840         let logger = test_utils::TestLogger::new();
1841
1842         macro_rules! get_route_and_payment_hash {
1843                 ($recv_value: expr) => {{
1844                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1845                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1846                         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();
1847                         (route, payment_hash, payment_preimage)
1848                 }}
1849         }
1850
1851         let feemsat = 239;
1852         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1853         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1854         let feerate = get_feerate!(nodes[0], chan.2);
1855
1856         // Add a 2* and +1 for the fee spike reserve.
1857         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1858         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;
1859         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1860
1861         // Add a pending HTLC.
1862         let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1863         let payment_event_1 = {
1864                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1865                 check_added_monitors!(nodes[0], 1);
1866
1867                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1868                 assert_eq!(events.len(), 1);
1869                 SendEvent::from_event(events.remove(0))
1870         };
1871         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1872
1873         // Attempt to trigger a channel reserve violation --> payment failure.
1874         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1875         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;
1876         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1877         let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1878
1879         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1880         let secp_ctx = Secp256k1::new();
1881         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1882         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1883         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1884         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1885         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1886         let msg = msgs::UpdateAddHTLC {
1887                 channel_id: chan.2,
1888                 htlc_id: 1,
1889                 amount_msat: htlc_msat + 1,
1890                 payment_hash: our_payment_hash_1,
1891                 cltv_expiry: htlc_cltv,
1892                 onion_routing_packet: onion_packet,
1893         };
1894
1895         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1896         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1897         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1898         assert_eq!(nodes[1].node.list_channels().len(), 1);
1899         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1900         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1901         check_added_monitors!(nodes[1], 1);
1902 }
1903
1904 #[test]
1905 fn test_inbound_outbound_capacity_is_not_zero() {
1906         let chanmon_cfgs = create_chanmon_cfgs(2);
1907         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1908         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1909         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1910         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1911         let channels0 = node_chanmgrs[0].list_channels();
1912         let channels1 = node_chanmgrs[1].list_channels();
1913         assert_eq!(channels0.len(), 1);
1914         assert_eq!(channels1.len(), 1);
1915
1916         assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1917         assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1918
1919         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1920         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1921 }
1922
1923 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1924         (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1925 }
1926
1927 #[test]
1928 fn test_channel_reserve_holding_cell_htlcs() {
1929         let chanmon_cfgs = create_chanmon_cfgs(3);
1930         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1931         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1932         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1933         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1934         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1935         let logger = test_utils::TestLogger::new();
1936
1937         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1938         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1939
1940         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1941         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1942
1943         macro_rules! get_route_and_payment_hash {
1944                 ($recv_value: expr) => {{
1945                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1946                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1947                         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();
1948                         (route, payment_hash, payment_preimage)
1949                 }}
1950         }
1951
1952         macro_rules! expect_forward {
1953                 ($node: expr) => {{
1954                         let mut events = $node.node.get_and_clear_pending_msg_events();
1955                         assert_eq!(events.len(), 1);
1956                         check_added_monitors!($node, 1);
1957                         let payment_event = SendEvent::from_event(events.remove(0));
1958                         payment_event
1959                 }}
1960         }
1961
1962         let feemsat = 239; // somehow we know?
1963         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1964         let feerate = get_feerate!(nodes[0], chan_1.2);
1965
1966         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1967
1968         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1969         {
1970                 let (mut route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0);
1971                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1972                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1973                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1974                         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)));
1975                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1976                 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);
1977         }
1978
1979         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1980         // nodes[0]'s wealth
1981         loop {
1982                 let amt_msat = recv_value_0 + total_fee_msat;
1983                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1984                 // Also, ensure that each payment has enough to be over the dust limit to
1985                 // ensure it'll be included in each commit tx fee calculation.
1986                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1987                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1988                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1989                         break;
1990                 }
1991                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1992
1993                 let (stat01_, stat11_, stat12_, stat22_) = (
1994                         get_channel_value_stat!(nodes[0], chan_1.2),
1995                         get_channel_value_stat!(nodes[1], chan_1.2),
1996                         get_channel_value_stat!(nodes[1], chan_2.2),
1997                         get_channel_value_stat!(nodes[2], chan_2.2),
1998                 );
1999
2000                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
2001                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
2002                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
2003                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
2004                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
2005         }
2006
2007         // adding pending output.
2008         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
2009         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2010         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2011         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2012         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2013         // cases where 1 msat over X amount will cause a payment failure, but anything less than
2014         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2015         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2016         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2017         // policy.
2018         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2019         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2020         let amt_msat_1 = recv_value_1 + total_fee_msat;
2021
2022         let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2023         let payment_event_1 = {
2024                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
2025                 check_added_monitors!(nodes[0], 1);
2026
2027                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2028                 assert_eq!(events.len(), 1);
2029                 SendEvent::from_event(events.remove(0))
2030         };
2031         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2032
2033         // channel reserve test with htlc pending output > 0
2034         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2035         {
2036                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2037                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2038                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2039                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2040         }
2041
2042         // split the rest to test holding cell
2043         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2044         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2045         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2046         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2047         {
2048                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2049                 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);
2050         }
2051
2052         // now see if they go through on both sides
2053         let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2054         // but this will stuck in the holding cell
2055         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2056         check_added_monitors!(nodes[0], 0);
2057         let events = nodes[0].node.get_and_clear_pending_events();
2058         assert_eq!(events.len(), 0);
2059
2060         // test with outbound holding cell amount > 0
2061         {
2062                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2063                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2064                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2065                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2066                 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);
2067         }
2068
2069         let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2070         // this will also stuck in the holding cell
2071         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2072         check_added_monitors!(nodes[0], 0);
2073         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2074         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2075
2076         // flush the pending htlc
2077         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2078         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2079         check_added_monitors!(nodes[1], 1);
2080
2081         // the pending htlc should be promoted to committed
2082         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2083         check_added_monitors!(nodes[0], 1);
2084         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2085
2086         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2087         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2088         // No commitment_signed so get_event_msg's assert(len == 1) passes
2089         check_added_monitors!(nodes[0], 1);
2090
2091         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2092         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2093         check_added_monitors!(nodes[1], 1);
2094
2095         expect_pending_htlcs_forwardable!(nodes[1]);
2096
2097         let ref payment_event_11 = expect_forward!(nodes[1]);
2098         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2099         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2100
2101         expect_pending_htlcs_forwardable!(nodes[2]);
2102         expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2103
2104         // flush the htlcs in the holding cell
2105         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2106         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2107         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2108         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2109         expect_pending_htlcs_forwardable!(nodes[1]);
2110
2111         let ref payment_event_3 = expect_forward!(nodes[1]);
2112         assert_eq!(payment_event_3.msgs.len(), 2);
2113         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2114         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2115
2116         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2117         expect_pending_htlcs_forwardable!(nodes[2]);
2118
2119         let events = nodes[2].node.get_and_clear_pending_events();
2120         assert_eq!(events.len(), 2);
2121         match events[0] {
2122                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2123                         assert_eq!(our_payment_hash_21, *payment_hash);
2124                         assert_eq!(*payment_secret, None);
2125                         assert_eq!(recv_value_21, amt);
2126                 },
2127                 _ => panic!("Unexpected event"),
2128         }
2129         match events[1] {
2130                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2131                         assert_eq!(our_payment_hash_22, *payment_hash);
2132                         assert_eq!(None, *payment_secret);
2133                         assert_eq!(recv_value_22, amt);
2134                 },
2135                 _ => panic!("Unexpected event"),
2136         }
2137
2138         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2139         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2140         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2141
2142         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2143         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2144         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2145
2146         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2147         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);
2148         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2149         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2150         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2151
2152         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2153         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2154 }
2155
2156 #[test]
2157 fn channel_reserve_in_flight_removes() {
2158         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2159         // can send to its counterparty, but due to update ordering, the other side may not yet have
2160         // considered those HTLCs fully removed.
2161         // This tests that we don't count HTLCs which will not be included in the next remote
2162         // commitment transaction towards the reserve value (as it implies no commitment transaction
2163         // will be generated which violates the remote reserve value).
2164         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2165         // To test this we:
2166         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2167         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2168         //    you only consider the value of the first HTLC, it may not),
2169         //  * start routing a third HTLC from A to B,
2170         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2171         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2172         //  * deliver the first fulfill from B
2173         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2174         //    claim,
2175         //  * deliver A's response CS and RAA.
2176         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2177         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2178         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2179         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2180         let chanmon_cfgs = create_chanmon_cfgs(2);
2181         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2182         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2183         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2184         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2185         let logger = test_utils::TestLogger::new();
2186
2187         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2188         // Route the first two HTLCs.
2189         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2190         let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2191
2192         // Start routing the third HTLC (this is just used to get everyone in the right state).
2193         let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2194         let send_1 = {
2195                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2196                 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();
2197                 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2198                 check_added_monitors!(nodes[0], 1);
2199                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2200                 assert_eq!(events.len(), 1);
2201                 SendEvent::from_event(events.remove(0))
2202         };
2203
2204         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2205         // initial fulfill/CS.
2206         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2207         check_added_monitors!(nodes[1], 1);
2208         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2209
2210         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2211         // remove the second HTLC when we send the HTLC back from B to A.
2212         assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2213         check_added_monitors!(nodes[1], 1);
2214         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2215
2216         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2217         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2218         check_added_monitors!(nodes[0], 1);
2219         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2220         expect_payment_sent!(nodes[0], payment_preimage_1);
2221
2222         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2223         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2224         check_added_monitors!(nodes[1], 1);
2225         // B is already AwaitingRAA, so cant generate a CS here
2226         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2227
2228         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2229         check_added_monitors!(nodes[1], 1);
2230         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2231
2232         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2233         check_added_monitors!(nodes[0], 1);
2234         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2235
2236         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2237         check_added_monitors!(nodes[1], 1);
2238         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2239
2240         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2241         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2242         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2243         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2244         // on-chain as necessary).
2245         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2246         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2247         check_added_monitors!(nodes[0], 1);
2248         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2249         expect_payment_sent!(nodes[0], payment_preimage_2);
2250
2251         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2252         check_added_monitors!(nodes[1], 1);
2253         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2254
2255         expect_pending_htlcs_forwardable!(nodes[1]);
2256         expect_payment_received!(nodes[1], payment_hash_3, 100000);
2257
2258         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2259         // resolve the second HTLC from A's point of view.
2260         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2261         check_added_monitors!(nodes[0], 1);
2262         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2263
2264         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2265         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2266         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2267         let send_2 = {
2268                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2269                 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();
2270                 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2271                 check_added_monitors!(nodes[1], 1);
2272                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2273                 assert_eq!(events.len(), 1);
2274                 SendEvent::from_event(events.remove(0))
2275         };
2276
2277         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2278         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2279         check_added_monitors!(nodes[0], 1);
2280         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2281
2282         // Now just resolve all the outstanding messages/HTLCs for completeness...
2283
2284         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2285         check_added_monitors!(nodes[1], 1);
2286         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2287
2288         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2289         check_added_monitors!(nodes[1], 1);
2290
2291         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2292         check_added_monitors!(nodes[0], 1);
2293         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2294
2295         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2296         check_added_monitors!(nodes[1], 1);
2297         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2298
2299         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2300         check_added_monitors!(nodes[0], 1);
2301
2302         expect_pending_htlcs_forwardable!(nodes[0]);
2303         expect_payment_received!(nodes[0], payment_hash_4, 10000);
2304
2305         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2306         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2307 }
2308
2309 #[test]
2310 fn channel_monitor_network_test() {
2311         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2312         // tests that ChannelMonitor is able to recover from various states.
2313         let chanmon_cfgs = create_chanmon_cfgs(5);
2314         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2315         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2316         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2317
2318         // Create some initial channels
2319         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2320         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2321         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2322         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2323
2324         // Make sure all nodes are at the same starting height
2325         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2326         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2327         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2328         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2329         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2330
2331         // Rebalance the network a bit by relaying one payment through all the channels...
2332         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2333         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2334         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2335         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2336
2337         // Simple case with no pending HTLCs:
2338         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2339         check_added_monitors!(nodes[1], 1);
2340         check_closed_broadcast!(nodes[1], false);
2341         {
2342                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2343                 assert_eq!(node_txn.len(), 1);
2344                 mine_transaction(&nodes[0], &node_txn[0]);
2345                 check_added_monitors!(nodes[0], 1);
2346                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2347         }
2348         check_closed_broadcast!(nodes[0], true);
2349         assert_eq!(nodes[0].node.list_channels().len(), 0);
2350         assert_eq!(nodes[1].node.list_channels().len(), 1);
2351
2352         // One pending HTLC is discarded by the force-close:
2353         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2354
2355         // Simple case of one pending HTLC to HTLC-Timeout
2356         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2357         check_closed_broadcast!(nodes[1], false);
2358         check_added_monitors!(nodes[1], 1);
2359         {
2360                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2361                 mine_transaction(&nodes[2], &node_txn[0]);
2362                 check_added_monitors!(nodes[2], 1);
2363                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2364         }
2365         check_closed_broadcast!(nodes[2], true);
2366         assert_eq!(nodes[1].node.list_channels().len(), 0);
2367         assert_eq!(nodes[2].node.list_channels().len(), 1);
2368
2369         macro_rules! claim_funds {
2370                 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2371                         {
2372                                 assert!($node.node.claim_funds($preimage, &None, $amount));
2373                                 check_added_monitors!($node, 1);
2374
2375                                 let events = $node.node.get_and_clear_pending_msg_events();
2376                                 assert_eq!(events.len(), 1);
2377                                 match events[0] {
2378                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2379                                                 assert!(update_add_htlcs.is_empty());
2380                                                 assert!(update_fail_htlcs.is_empty());
2381                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2382                                         },
2383                                         _ => panic!("Unexpected event"),
2384                                 };
2385                         }
2386                 }
2387         }
2388
2389         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2390         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2391         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2392         check_added_monitors!(nodes[2], 1);
2393         check_closed_broadcast!(nodes[2], false);
2394         let node2_commitment_txid;
2395         {
2396                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2397                 node2_commitment_txid = node_txn[0].txid();
2398
2399                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2400                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2401                 mine_transaction(&nodes[3], &node_txn[0]);
2402                 check_added_monitors!(nodes[3], 1);
2403                 check_preimage_claim(&nodes[3], &node_txn);
2404         }
2405         check_closed_broadcast!(nodes[3], true);
2406         assert_eq!(nodes[2].node.list_channels().len(), 0);
2407         assert_eq!(nodes[3].node.list_channels().len(), 1);
2408
2409         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2410         // confusing us in the following tests.
2411         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().remove(&OutPoint { txid: chan_3.3.txid(), index: 0 }).unwrap();
2412
2413         // One pending HTLC to time out:
2414         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2415         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2416         // buffer space).
2417
2418         let (close_chan_update_1, close_chan_update_2) = {
2419                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2420                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2421                 assert_eq!(events.len(), 2);
2422                 let close_chan_update_1 = match events[0] {
2423                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2424                                 msg.clone()
2425                         },
2426                         _ => panic!("Unexpected event"),
2427                 };
2428                 match events[1] {
2429                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2430                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2431                         },
2432                         _ => panic!("Unexpected event"),
2433                 }
2434                 check_added_monitors!(nodes[3], 1);
2435
2436                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2437                 {
2438                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2439                         node_txn.retain(|tx| {
2440                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2441                                         false
2442                                 } else { true }
2443                         });
2444                 }
2445
2446                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2447
2448                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2449                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2450
2451                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2452                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2453                 assert_eq!(events.len(), 2);
2454                 let close_chan_update_2 = match events[0] {
2455                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2456                                 msg.clone()
2457                         },
2458                         _ => panic!("Unexpected event"),
2459                 };
2460                 match events[1] {
2461                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2462                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2463                         },
2464                         _ => panic!("Unexpected event"),
2465                 }
2466                 check_added_monitors!(nodes[4], 1);
2467                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2468
2469                 mine_transaction(&nodes[4], &node_txn[0]);
2470                 check_preimage_claim(&nodes[4], &node_txn);
2471                 (close_chan_update_1, close_chan_update_2)
2472         };
2473         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2474         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2475         assert_eq!(nodes[3].node.list_channels().len(), 0);
2476         assert_eq!(nodes[4].node.list_channels().len(), 0);
2477
2478         nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().insert(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon);
2479 }
2480
2481 #[test]
2482 fn test_justice_tx() {
2483         // Test justice txn built on revoked HTLC-Success tx, against both sides
2484         let mut alice_config = UserConfig::default();
2485         alice_config.channel_options.announced_channel = true;
2486         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2487         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2488         let mut bob_config = UserConfig::default();
2489         bob_config.channel_options.announced_channel = true;
2490         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2491         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2492         let user_cfgs = [Some(alice_config), Some(bob_config)];
2493         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2494         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2495         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2496         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2497         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2498         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2499         // Create some new channels:
2500         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2501
2502         // A pending HTLC which will be revoked:
2503         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2504         // Get the will-be-revoked local txn from nodes[0]
2505         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2506         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2507         assert_eq!(revoked_local_txn[0].input.len(), 1);
2508         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2509         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2510         assert_eq!(revoked_local_txn[1].input.len(), 1);
2511         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2512         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2513         // Revoke the old state
2514         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2515
2516         {
2517                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2518                 {
2519                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2520                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2521                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2522
2523                         check_spends!(node_txn[0], revoked_local_txn[0]);
2524                         node_txn.swap_remove(0);
2525                         node_txn.truncate(1);
2526                 }
2527                 check_added_monitors!(nodes[1], 1);
2528                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2529
2530                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2531                 // Verify broadcast of revoked HTLC-timeout
2532                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2533                 check_added_monitors!(nodes[0], 1);
2534                 // Broadcast revoked HTLC-timeout on node 1
2535                 mine_transaction(&nodes[1], &node_txn[1]);
2536                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2537         }
2538         get_announce_close_broadcast_events(&nodes, 0, 1);
2539
2540         assert_eq!(nodes[0].node.list_channels().len(), 0);
2541         assert_eq!(nodes[1].node.list_channels().len(), 0);
2542
2543         // We test justice_tx build by A on B's revoked HTLC-Success tx
2544         // Create some new channels:
2545         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2546         {
2547                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2548                 node_txn.clear();
2549         }
2550
2551         // A pending HTLC which will be revoked:
2552         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2553         // Get the will-be-revoked local txn from B
2554         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2555         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2556         assert_eq!(revoked_local_txn[0].input.len(), 1);
2557         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2558         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2559         // Revoke the old state
2560         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2561         {
2562                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2563                 {
2564                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2565                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2566                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2567
2568                         check_spends!(node_txn[0], revoked_local_txn[0]);
2569                         node_txn.swap_remove(0);
2570                 }
2571                 check_added_monitors!(nodes[0], 1);
2572                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2573
2574                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2575                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2576                 check_added_monitors!(nodes[1], 1);
2577                 mine_transaction(&nodes[0], &node_txn[1]);
2578                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2579         }
2580         get_announce_close_broadcast_events(&nodes, 0, 1);
2581         assert_eq!(nodes[0].node.list_channels().len(), 0);
2582         assert_eq!(nodes[1].node.list_channels().len(), 0);
2583 }
2584
2585 #[test]
2586 fn revoked_output_claim() {
2587         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2588         // transaction is broadcast by its counterparty
2589         let chanmon_cfgs = create_chanmon_cfgs(2);
2590         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2591         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2592         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2593         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2594         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2595         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2596         assert_eq!(revoked_local_txn.len(), 1);
2597         // Only output is the full channel value back to nodes[0]:
2598         assert_eq!(revoked_local_txn[0].output.len(), 1);
2599         // Send a payment through, updating everyone's latest commitment txn
2600         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2601
2602         // Inform nodes[1] that nodes[0] broadcast a stale tx
2603         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2604         check_added_monitors!(nodes[1], 1);
2605         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2606         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2607
2608         check_spends!(node_txn[0], revoked_local_txn[0]);
2609         check_spends!(node_txn[1], chan_1.3);
2610
2611         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2612         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2613         get_announce_close_broadcast_events(&nodes, 0, 1);
2614         check_added_monitors!(nodes[0], 1)
2615 }
2616
2617 #[test]
2618 fn claim_htlc_outputs_shared_tx() {
2619         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2620         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2621         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2622         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2623         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2624         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2625
2626         // Create some new channel:
2627         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2628
2629         // Rebalance the network to generate htlc in the two directions
2630         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2631         // 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
2632         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2633         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2634
2635         // Get the will-be-revoked local txn from node[0]
2636         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2637         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2638         assert_eq!(revoked_local_txn[0].input.len(), 1);
2639         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2640         assert_eq!(revoked_local_txn[1].input.len(), 1);
2641         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2642         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2643         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2644
2645         //Revoke the old state
2646         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2647
2648         {
2649                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2650                 check_added_monitors!(nodes[0], 1);
2651                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2652                 check_added_monitors!(nodes[1], 1);
2653                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2654                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2655
2656                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2657                 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2658
2659                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2660                 check_spends!(node_txn[0], revoked_local_txn[0]);
2661
2662                 let mut witness_lens = BTreeSet::new();
2663                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2664                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2665                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2666                 assert_eq!(witness_lens.len(), 3);
2667                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2668                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2669                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2670
2671                 // Next nodes[1] broadcasts its current local tx state:
2672                 assert_eq!(node_txn[1].input.len(), 1);
2673                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2674
2675                 assert_eq!(node_txn[2].input.len(), 1);
2676                 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2677                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2678                 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2679                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2680                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2681         }
2682         get_announce_close_broadcast_events(&nodes, 0, 1);
2683         assert_eq!(nodes[0].node.list_channels().len(), 0);
2684         assert_eq!(nodes[1].node.list_channels().len(), 0);
2685 }
2686
2687 #[test]
2688 fn claim_htlc_outputs_single_tx() {
2689         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2690         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2691         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2692         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2693         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2694         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2695
2696         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2697
2698         // Rebalance the network to generate htlc in the two directions
2699         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2700         // 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
2701         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2702         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2703         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2704
2705         // Get the will-be-revoked local txn from node[0]
2706         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2707
2708         //Revoke the old state
2709         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2710
2711         {
2712                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2713                 check_added_monitors!(nodes[0], 1);
2714                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2715                 check_added_monitors!(nodes[1], 1);
2716                 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2717
2718                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2719                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2720
2721                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2722                 assert_eq!(node_txn.len(), 9);
2723                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2724                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2725                 // 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)
2726                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2727
2728                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2729                 assert_eq!(node_txn[0].input.len(), 1);
2730                 check_spends!(node_txn[0], chan_1.3);
2731                 assert_eq!(node_txn[1].input.len(), 1);
2732                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2733                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2734                 check_spends!(node_txn[1], node_txn[0]);
2735
2736                 // Justice transactions are indices 1-2-4
2737                 assert_eq!(node_txn[2].input.len(), 1);
2738                 assert_eq!(node_txn[3].input.len(), 1);
2739                 assert_eq!(node_txn[4].input.len(), 1);
2740
2741                 check_spends!(node_txn[2], revoked_local_txn[0]);
2742                 check_spends!(node_txn[3], revoked_local_txn[0]);
2743                 check_spends!(node_txn[4], revoked_local_txn[0]);
2744
2745                 let mut witness_lens = BTreeSet::new();
2746                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2747                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2748                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2749                 assert_eq!(witness_lens.len(), 3);
2750                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2751                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2752                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2753         }
2754         get_announce_close_broadcast_events(&nodes, 0, 1);
2755         assert_eq!(nodes[0].node.list_channels().len(), 0);
2756         assert_eq!(nodes[1].node.list_channels().len(), 0);
2757 }
2758
2759 #[test]
2760 fn test_htlc_on_chain_success() {
2761         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2762         // the preimage backward accordingly. So here we test that ChannelManager is
2763         // broadcasting the right event to other nodes in payment path.
2764         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2765         // A --------------------> B ----------------------> C (preimage)
2766         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2767         // commitment transaction was broadcast.
2768         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2769         // towards B.
2770         // B should be able to claim via preimage if A then broadcasts its local tx.
2771         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2772         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2773         // PaymentSent event).
2774
2775         let chanmon_cfgs = create_chanmon_cfgs(3);
2776         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2777         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2778         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2779
2780         // Create some initial channels
2781         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2782         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2783
2784         // Rebalance the network a bit by relaying one payment through all the channels...
2785         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2786         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2787
2788         let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2789         let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2790
2791         // Broadcast legit commitment tx from C on B's chain
2792         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2793         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2794         assert_eq!(commitment_tx.len(), 1);
2795         check_spends!(commitment_tx[0], chan_2.3);
2796         nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2797         nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2798         check_added_monitors!(nodes[2], 2);
2799         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2800         assert!(updates.update_add_htlcs.is_empty());
2801         assert!(updates.update_fail_htlcs.is_empty());
2802         assert!(updates.update_fail_malformed_htlcs.is_empty());
2803         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2804
2805         mine_transaction(&nodes[2], &commitment_tx[0]);
2806         check_closed_broadcast!(nodes[2], true);
2807         check_added_monitors!(nodes[2], 1);
2808         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)
2809         assert_eq!(node_txn.len(), 5);
2810         assert_eq!(node_txn[0], node_txn[3]);
2811         assert_eq!(node_txn[1], node_txn[4]);
2812         assert_eq!(node_txn[2], commitment_tx[0]);
2813         check_spends!(node_txn[0], commitment_tx[0]);
2814         check_spends!(node_txn[1], commitment_tx[0]);
2815         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2816         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2817         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2818         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2819         assert_eq!(node_txn[0].lock_time, 0);
2820         assert_eq!(node_txn[1].lock_time, 0);
2821
2822         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2823         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2824         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2825         {
2826                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2827                 assert_eq!(added_monitors.len(), 1);
2828                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2829                 added_monitors.clear();
2830         }
2831         let events = nodes[1].node.get_and_clear_pending_msg_events();
2832         {
2833                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2834                 assert_eq!(added_monitors.len(), 2);
2835                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2836                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2837                 added_monitors.clear();
2838         }
2839         assert_eq!(events.len(), 3);
2840         match events[0] {
2841                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2842                 _ => panic!("Unexpected event"),
2843         }
2844         match events[1] {
2845                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2846                 _ => panic!("Unexpected event"),
2847         }
2848
2849         match events[2] {
2850                 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, .. } } => {
2851                         assert!(update_add_htlcs.is_empty());
2852                         assert!(update_fail_htlcs.is_empty());
2853                         assert_eq!(update_fulfill_htlcs.len(), 1);
2854                         assert!(update_fail_malformed_htlcs.is_empty());
2855                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2856                 },
2857                 _ => panic!("Unexpected event"),
2858         };
2859         macro_rules! check_tx_local_broadcast {
2860                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2861                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2862                         assert_eq!(node_txn.len(), 5);
2863                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2864                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2865                         check_spends!(node_txn[0], $commitment_tx);
2866                         check_spends!(node_txn[1], $commitment_tx);
2867                         assert_ne!(node_txn[0].lock_time, 0);
2868                         assert_ne!(node_txn[1].lock_time, 0);
2869                         if $htlc_offered {
2870                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2871                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2872                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2873                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2874                         } else {
2875                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2876                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2877                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2878                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2879                         }
2880                         check_spends!(node_txn[2], $chan_tx);
2881                         check_spends!(node_txn[3], node_txn[2]);
2882                         check_spends!(node_txn[4], node_txn[2]);
2883                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2884                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2885                         assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2886                         assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2887                         assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2888                         assert_ne!(node_txn[3].lock_time, 0);
2889                         assert_ne!(node_txn[4].lock_time, 0);
2890                         node_txn.clear();
2891                 } }
2892         }
2893         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2894         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2895         // timeout-claim of the output that nodes[2] just claimed via success.
2896         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2897
2898         // Broadcast legit commitment tx from A on B's chain
2899         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2900         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2901         check_spends!(commitment_tx[0], chan_1.3);
2902         mine_transaction(&nodes[1], &commitment_tx[0]);
2903         check_closed_broadcast!(nodes[1], true);
2904         check_added_monitors!(nodes[1], 1);
2905         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2906         assert_eq!(node_txn.len(), 4);
2907         check_spends!(node_txn[0], commitment_tx[0]);
2908         assert_eq!(node_txn[0].input.len(), 2);
2909         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2910         assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2911         assert_eq!(node_txn[0].lock_time, 0);
2912         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2913         check_spends!(node_txn[1], chan_1.3);
2914         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2915         check_spends!(node_txn[2], node_txn[1]);
2916         check_spends!(node_txn[3], node_txn[1]);
2917         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2918         // we already checked the same situation with A.
2919
2920         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2921         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2922         connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] });
2923         check_closed_broadcast!(nodes[0], true);
2924         check_added_monitors!(nodes[0], 1);
2925         let events = nodes[0].node.get_and_clear_pending_events();
2926         assert_eq!(events.len(), 2);
2927         let mut first_claimed = false;
2928         for event in events {
2929                 match event {
2930                         Event::PaymentSent { payment_preimage } => {
2931                                 if payment_preimage == our_payment_preimage {
2932                                         assert!(!first_claimed);
2933                                         first_claimed = true;
2934                                 } else {
2935                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2936                                 }
2937                         },
2938                         _ => panic!("Unexpected event"),
2939                 }
2940         }
2941         check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2942 }
2943
2944 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2945         // Test that in case of a unilateral close onchain, we detect the state of output and
2946         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2947         // broadcasting the right event to other nodes in payment path.
2948         // A ------------------> B ----------------------> C (timeout)
2949         //    B's commitment tx                 C's commitment tx
2950         //            \                                  \
2951         //         B's HTLC timeout tx               B's timeout tx
2952
2953         let chanmon_cfgs = create_chanmon_cfgs(3);
2954         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2955         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2956         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2957         *nodes[0].connect_style.borrow_mut() = connect_style;
2958         *nodes[1].connect_style.borrow_mut() = connect_style;
2959         *nodes[2].connect_style.borrow_mut() = connect_style;
2960
2961         // Create some intial channels
2962         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2963         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2964
2965         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2966         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2967         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2968
2969         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2970
2971         // Broadcast legit commitment tx from C on B's chain
2972         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2973         check_spends!(commitment_tx[0], chan_2.3);
2974         nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2975         check_added_monitors!(nodes[2], 0);
2976         expect_pending_htlcs_forwardable!(nodes[2]);
2977         check_added_monitors!(nodes[2], 1);
2978
2979         let events = nodes[2].node.get_and_clear_pending_msg_events();
2980         assert_eq!(events.len(), 1);
2981         match events[0] {
2982                 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, .. } } => {
2983                         assert!(update_add_htlcs.is_empty());
2984                         assert!(!update_fail_htlcs.is_empty());
2985                         assert!(update_fulfill_htlcs.is_empty());
2986                         assert!(update_fail_malformed_htlcs.is_empty());
2987                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2988                 },
2989                 _ => panic!("Unexpected event"),
2990         };
2991         mine_transaction(&nodes[2], &commitment_tx[0]);
2992         check_closed_broadcast!(nodes[2], true);
2993         check_added_monitors!(nodes[2], 1);
2994         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2995         assert_eq!(node_txn.len(), 1);
2996         check_spends!(node_txn[0], chan_2.3);
2997         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2998
2999         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3000         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3001         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3002         mine_transaction(&nodes[1], &commitment_tx[0]);
3003         let timeout_tx;
3004         {
3005                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3006                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
3007                 assert_eq!(node_txn[0], node_txn[3]);
3008                 assert_eq!(node_txn[1], node_txn[4]);
3009
3010                 check_spends!(node_txn[2], commitment_tx[0]);
3011                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3012
3013                 check_spends!(node_txn[0], chan_2.3);
3014                 check_spends!(node_txn[1], node_txn[0]);
3015                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3016                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3017
3018                 timeout_tx = node_txn[2].clone();
3019                 node_txn.clear();
3020         }
3021
3022         mine_transaction(&nodes[1], &timeout_tx);
3023         check_added_monitors!(nodes[1], 1);
3024         check_closed_broadcast!(nodes[1], true);
3025         {
3026                 // B will rebroadcast a fee-bumped timeout transaction here.
3027                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3028                 assert_eq!(node_txn.len(), 1);
3029                 check_spends!(node_txn[0], commitment_tx[0]);
3030         }
3031
3032         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3033         {
3034                 // B will rebroadcast its own holder commitment transaction here...just because
3035                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3036                 assert_eq!(node_txn.len(), 1);
3037                 check_spends!(node_txn[0], chan_2.3);
3038         }
3039
3040         expect_pending_htlcs_forwardable!(nodes[1]);
3041         check_added_monitors!(nodes[1], 1);
3042         let events = nodes[1].node.get_and_clear_pending_msg_events();
3043         assert_eq!(events.len(), 1);
3044         match events[0] {
3045                 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, .. } } => {
3046                         assert!(update_add_htlcs.is_empty());
3047                         assert!(!update_fail_htlcs.is_empty());
3048                         assert!(update_fulfill_htlcs.is_empty());
3049                         assert!(update_fail_malformed_htlcs.is_empty());
3050                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3051                 },
3052                 _ => panic!("Unexpected event"),
3053         };
3054
3055         // Broadcast legit commitment tx from B on A's chain
3056         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3057         check_spends!(commitment_tx[0], chan_1.3);
3058
3059         mine_transaction(&nodes[0], &commitment_tx[0]);
3060
3061         check_closed_broadcast!(nodes[0], true);
3062         check_added_monitors!(nodes[0], 1);
3063         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3064         assert_eq!(node_txn.len(), 3);
3065         check_spends!(node_txn[0], commitment_tx[0]);
3066         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3067         check_spends!(node_txn[1], chan_1.3);
3068         check_spends!(node_txn[2], node_txn[1]);
3069         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3070         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3071 }
3072
3073 #[test]
3074 fn test_htlc_on_chain_timeout() {
3075         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3076         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3077         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3078 }
3079
3080 #[test]
3081 fn test_simple_commitment_revoked_fail_backward() {
3082         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3083         // and fail backward accordingly.
3084
3085         let chanmon_cfgs = create_chanmon_cfgs(3);
3086         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3087         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3088         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3089
3090         // Create some initial channels
3091         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3092         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3093
3094         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3095         // Get the will-be-revoked local txn from nodes[2]
3096         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3097         // Revoke the old state
3098         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3099
3100         let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3101
3102         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3103         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3104         check_added_monitors!(nodes[1], 1);
3105         check_closed_broadcast!(nodes[1], true);
3106
3107         expect_pending_htlcs_forwardable!(nodes[1]);
3108         check_added_monitors!(nodes[1], 1);
3109         let events = nodes[1].node.get_and_clear_pending_msg_events();
3110         assert_eq!(events.len(), 1);
3111         match events[0] {
3112                 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, .. } } => {
3113                         assert!(update_add_htlcs.is_empty());
3114                         assert_eq!(update_fail_htlcs.len(), 1);
3115                         assert!(update_fulfill_htlcs.is_empty());
3116                         assert!(update_fail_malformed_htlcs.is_empty());
3117                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3118
3119                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3120                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3121
3122                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3123                         assert_eq!(events.len(), 1);
3124                         match events[0] {
3125                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3126                                 _ => panic!("Unexpected event"),
3127                         }
3128                         expect_payment_failed!(nodes[0], payment_hash, false);
3129                 },
3130                 _ => panic!("Unexpected event"),
3131         }
3132 }
3133
3134 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3135         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3136         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3137         // commitment transaction anymore.
3138         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3139         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3140         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3141         // technically disallowed and we should probably handle it reasonably.
3142         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3143         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3144         // transactions:
3145         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3146         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3147         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3148         //   and once they revoke the previous commitment transaction (allowing us to send a new
3149         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3150         let chanmon_cfgs = create_chanmon_cfgs(3);
3151         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3152         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3153         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3154
3155         // Create some initial channels
3156         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3157         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3158
3159         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3160         // Get the will-be-revoked local txn from nodes[2]
3161         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3162         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3163         // Revoke the old state
3164         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3165
3166         let value = if use_dust {
3167                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3168                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3169                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3170         } else { 3000000 };
3171
3172         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3173         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3174         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3175
3176         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3177         expect_pending_htlcs_forwardable!(nodes[2]);
3178         check_added_monitors!(nodes[2], 1);
3179         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3180         assert!(updates.update_add_htlcs.is_empty());
3181         assert!(updates.update_fulfill_htlcs.is_empty());
3182         assert!(updates.update_fail_malformed_htlcs.is_empty());
3183         assert_eq!(updates.update_fail_htlcs.len(), 1);
3184         assert!(updates.update_fee.is_none());
3185         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3186         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3187         // Drop the last RAA from 3 -> 2
3188
3189         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3190         expect_pending_htlcs_forwardable!(nodes[2]);
3191         check_added_monitors!(nodes[2], 1);
3192         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3193         assert!(updates.update_add_htlcs.is_empty());
3194         assert!(updates.update_fulfill_htlcs.is_empty());
3195         assert!(updates.update_fail_malformed_htlcs.is_empty());
3196         assert_eq!(updates.update_fail_htlcs.len(), 1);
3197         assert!(updates.update_fee.is_none());
3198         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3199         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3200         check_added_monitors!(nodes[1], 1);
3201         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3202         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3203         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3204         check_added_monitors!(nodes[2], 1);
3205
3206         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3207         expect_pending_htlcs_forwardable!(nodes[2]);
3208         check_added_monitors!(nodes[2], 1);
3209         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3210         assert!(updates.update_add_htlcs.is_empty());
3211         assert!(updates.update_fulfill_htlcs.is_empty());
3212         assert!(updates.update_fail_malformed_htlcs.is_empty());
3213         assert_eq!(updates.update_fail_htlcs.len(), 1);
3214         assert!(updates.update_fee.is_none());
3215         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3216         // At this point first_payment_hash has dropped out of the latest two commitment
3217         // transactions that nodes[1] is tracking...
3218         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3219         check_added_monitors!(nodes[1], 1);
3220         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3221         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3222         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3223         check_added_monitors!(nodes[2], 1);
3224
3225         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3226         // on nodes[2]'s RAA.
3227         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3228         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3229         let logger = test_utils::TestLogger::new();
3230         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();
3231         nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3232         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3233         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3234         check_added_monitors!(nodes[1], 0);
3235
3236         if deliver_bs_raa {
3237                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3238                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3239                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3240                 check_added_monitors!(nodes[1], 1);
3241                 let events = nodes[1].node.get_and_clear_pending_events();
3242                 assert_eq!(events.len(), 1);
3243                 match events[0] {
3244                         Event::PendingHTLCsForwardable { .. } => { },
3245                         _ => panic!("Unexpected event"),
3246                 };
3247                 // Deliberately don't process the pending fail-back so they all fail back at once after
3248                 // block connection just like the !deliver_bs_raa case
3249         }
3250
3251         let mut failed_htlcs = HashSet::new();
3252         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3253
3254         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3255         check_added_monitors!(nodes[1], 1);
3256         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3257
3258         let events = nodes[1].node.get_and_clear_pending_events();
3259         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3260         match events[0] {
3261                 Event::PaymentFailed { ref payment_hash, .. } => {
3262                         assert_eq!(*payment_hash, fourth_payment_hash);
3263                 },
3264                 _ => panic!("Unexpected event"),
3265         }
3266         if !deliver_bs_raa {
3267                 match events[1] {
3268                         Event::PendingHTLCsForwardable { .. } => { },
3269                         _ => panic!("Unexpected event"),
3270                 };
3271         }
3272         nodes[1].node.process_pending_htlc_forwards();
3273         check_added_monitors!(nodes[1], 1);
3274
3275         let events = nodes[1].node.get_and_clear_pending_msg_events();
3276         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3277         match events[if deliver_bs_raa { 1 } else { 0 }] {
3278                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3279                 _ => panic!("Unexpected event"),
3280         }
3281         match events[if deliver_bs_raa { 2 } else { 1 }] {
3282                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3283                         assert_eq!(channel_id, chan_2.2);
3284                         assert_eq!(data.as_str(), "Commitment or closing transaction was confirmed on chain.");
3285                 },
3286                 _ => panic!("Unexpected event"),
3287         }
3288         if deliver_bs_raa {
3289                 match events[0] {
3290                         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, .. } } => {
3291                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3292                                 assert_eq!(update_add_htlcs.len(), 1);
3293                                 assert!(update_fulfill_htlcs.is_empty());
3294                                 assert!(update_fail_htlcs.is_empty());
3295                                 assert!(update_fail_malformed_htlcs.is_empty());
3296                         },
3297                         _ => panic!("Unexpected event"),
3298                 }
3299         }
3300         match events[if deliver_bs_raa { 3 } else { 2 }] {
3301                 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, .. } } => {
3302                         assert!(update_add_htlcs.is_empty());
3303                         assert_eq!(update_fail_htlcs.len(), 3);
3304                         assert!(update_fulfill_htlcs.is_empty());
3305                         assert!(update_fail_malformed_htlcs.is_empty());
3306                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3307
3308                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3309                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3310                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3311
3312                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3313
3314                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3315                         // If we delivered B's RAA we got an unknown preimage error, not something
3316                         // that we should update our routing table for.
3317                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3318                         for event in events {
3319                                 match event {
3320                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3321                                         _ => panic!("Unexpected event"),
3322                                 }
3323                         }
3324                         let events = nodes[0].node.get_and_clear_pending_events();
3325                         assert_eq!(events.len(), 3);
3326                         match events[0] {
3327                                 Event::PaymentFailed { ref payment_hash, .. } => {
3328                                         assert!(failed_htlcs.insert(payment_hash.0));
3329                                 },
3330                                 _ => panic!("Unexpected event"),
3331                         }
3332                         match events[1] {
3333                                 Event::PaymentFailed { ref payment_hash, .. } => {
3334                                         assert!(failed_htlcs.insert(payment_hash.0));
3335                                 },
3336                                 _ => panic!("Unexpected event"),
3337                         }
3338                         match events[2] {
3339                                 Event::PaymentFailed { ref payment_hash, .. } => {
3340                                         assert!(failed_htlcs.insert(payment_hash.0));
3341                                 },
3342                                 _ => panic!("Unexpected event"),
3343                         }
3344                 },
3345                 _ => panic!("Unexpected event"),
3346         }
3347
3348         assert!(failed_htlcs.contains(&first_payment_hash.0));
3349         assert!(failed_htlcs.contains(&second_payment_hash.0));
3350         assert!(failed_htlcs.contains(&third_payment_hash.0));
3351 }
3352
3353 #[test]
3354 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3355         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3356         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3357         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3358         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3359 }
3360
3361 #[test]
3362 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3363         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3364         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3365         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3366         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3367 }
3368
3369 #[test]
3370 fn fail_backward_pending_htlc_upon_channel_failure() {
3371         let chanmon_cfgs = create_chanmon_cfgs(2);
3372         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3373         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3374         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3375         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3376         let logger = test_utils::TestLogger::new();
3377
3378         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3379         {
3380                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3381                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3382                 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();
3383                 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3384                 check_added_monitors!(nodes[0], 1);
3385
3386                 let payment_event = {
3387                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3388                         assert_eq!(events.len(), 1);
3389                         SendEvent::from_event(events.remove(0))
3390                 };
3391                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3392                 assert_eq!(payment_event.msgs.len(), 1);
3393         }
3394
3395         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3396         let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3397         {
3398                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3399                 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();
3400                 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3401                 check_added_monitors!(nodes[0], 0);
3402
3403                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3404         }
3405
3406         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3407         {
3408                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3409
3410                 let secp_ctx = Secp256k1::new();
3411                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3412                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3413                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3414                 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();
3415                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3416                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3417                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3418
3419                 // Send a 0-msat update_add_htlc to fail the channel.
3420                 let update_add_htlc = msgs::UpdateAddHTLC {
3421                         channel_id: chan.2,
3422                         htlc_id: 0,
3423                         amount_msat: 0,
3424                         payment_hash,
3425                         cltv_expiry,
3426                         onion_routing_packet,
3427                 };
3428                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3429         }
3430
3431         // Check that Alice fails backward the pending HTLC from the second payment.
3432         expect_payment_failed!(nodes[0], failed_payment_hash, true);
3433         check_closed_broadcast!(nodes[0], true);
3434         check_added_monitors!(nodes[0], 1);
3435 }
3436
3437 #[test]
3438 fn test_htlc_ignore_latest_remote_commitment() {
3439         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3440         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3441         let chanmon_cfgs = create_chanmon_cfgs(2);
3442         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3443         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3444         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3445         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3446
3447         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3448         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3449         check_closed_broadcast!(nodes[0], true);
3450         check_added_monitors!(nodes[0], 1);
3451
3452         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3453         assert_eq!(node_txn.len(), 2);
3454
3455         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3456         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3457         check_closed_broadcast!(nodes[1], true);
3458         check_added_monitors!(nodes[1], 1);
3459
3460         // Duplicate the connect_block call since this may happen due to other listeners
3461         // registering new transactions
3462         header.prev_blockhash = header.block_hash();
3463         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3464 }
3465
3466 #[test]
3467 fn test_force_close_fail_back() {
3468         // Check which HTLCs are failed-backwards on channel force-closure
3469         let chanmon_cfgs = create_chanmon_cfgs(3);
3470         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3471         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3472         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3473         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3474         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3475         let logger = test_utils::TestLogger::new();
3476
3477         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3478
3479         let mut payment_event = {
3480                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3481                 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();
3482                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3483                 check_added_monitors!(nodes[0], 1);
3484
3485                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3486                 assert_eq!(events.len(), 1);
3487                 SendEvent::from_event(events.remove(0))
3488         };
3489
3490         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3491         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3492
3493         expect_pending_htlcs_forwardable!(nodes[1]);
3494
3495         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3496         assert_eq!(events_2.len(), 1);
3497         payment_event = SendEvent::from_event(events_2.remove(0));
3498         assert_eq!(payment_event.msgs.len(), 1);
3499
3500         check_added_monitors!(nodes[1], 1);
3501         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3502         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3503         check_added_monitors!(nodes[2], 1);
3504         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3505
3506         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3507         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3508         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3509
3510         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3511         check_closed_broadcast!(nodes[2], true);
3512         check_added_monitors!(nodes[2], 1);
3513         let tx = {
3514                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3515                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3516                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3517                 // back to nodes[1] upon timeout otherwise.
3518                 assert_eq!(node_txn.len(), 1);
3519                 node_txn.remove(0)
3520         };
3521
3522         mine_transaction(&nodes[1], &tx);
3523
3524         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3525         check_closed_broadcast!(nodes[1], true);
3526         check_added_monitors!(nodes[1], 1);
3527
3528         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3529         {
3530                 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3531                 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3532                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3533         }
3534         mine_transaction(&nodes[2], &tx);
3535         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3536         assert_eq!(node_txn.len(), 1);
3537         assert_eq!(node_txn[0].input.len(), 1);
3538         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3539         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3540         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3541
3542         check_spends!(node_txn[0], tx);
3543 }
3544
3545 #[test]
3546 fn test_simple_peer_disconnect() {
3547         // Test that we can reconnect when there are no lost messages
3548         let chanmon_cfgs = create_chanmon_cfgs(3);
3549         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3550         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3551         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3552         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3553         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3554
3555         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3556         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3557         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3558
3559         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3560         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3561         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3562         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3563
3564         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3565         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3566         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3567
3568         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3569         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3570         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3571         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3572
3573         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3574         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3575
3576         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3577         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3578
3579         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3580         {
3581                 let events = nodes[0].node.get_and_clear_pending_events();
3582                 assert_eq!(events.len(), 2);
3583                 match events[0] {
3584                         Event::PaymentSent { payment_preimage } => {
3585                                 assert_eq!(payment_preimage, payment_preimage_3);
3586                         },
3587                         _ => panic!("Unexpected event"),
3588                 }
3589                 match events[1] {
3590                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3591                                 assert_eq!(payment_hash, payment_hash_5);
3592                                 assert!(rejected_by_dest);
3593                         },
3594                         _ => panic!("Unexpected event"),
3595                 }
3596         }
3597
3598         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3599         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3600 }
3601
3602 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3603         // Test that we can reconnect when in-flight HTLC updates get dropped
3604         let chanmon_cfgs = create_chanmon_cfgs(2);
3605         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3606         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3607         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3608         if messages_delivered == 0 {
3609                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3610                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3611         } else {
3612                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3613         }
3614
3615         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3616
3617         let logger = test_utils::TestLogger::new();
3618         let payment_event = {
3619                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3620                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3621                         &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3622                         &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3623                 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3624                 check_added_monitors!(nodes[0], 1);
3625
3626                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3627                 assert_eq!(events.len(), 1);
3628                 SendEvent::from_event(events.remove(0))
3629         };
3630         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3631
3632         if messages_delivered < 2 {
3633                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3634         } else {
3635                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3636                 if messages_delivered >= 3 {
3637                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3638                         check_added_monitors!(nodes[1], 1);
3639                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3640
3641                         if messages_delivered >= 4 {
3642                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3643                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3644                                 check_added_monitors!(nodes[0], 1);
3645
3646                                 if messages_delivered >= 5 {
3647                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3648                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3649                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3650                                         check_added_monitors!(nodes[0], 1);
3651
3652                                         if messages_delivered >= 6 {
3653                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3654                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3655                                                 check_added_monitors!(nodes[1], 1);
3656                                         }
3657                                 }
3658                         }
3659                 }
3660         }
3661
3662         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3663         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3664         if messages_delivered < 3 {
3665                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3666                 // received on either side, both sides will need to resend them.
3667                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3668         } else if messages_delivered == 3 {
3669                 // nodes[0] still wants its RAA + commitment_signed
3670                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3671         } else if messages_delivered == 4 {
3672                 // nodes[0] still wants its commitment_signed
3673                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3674         } else if messages_delivered == 5 {
3675                 // nodes[1] still wants its final RAA
3676                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3677         } else if messages_delivered == 6 {
3678                 // Everything was delivered...
3679                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3680         }
3681
3682         let events_1 = nodes[1].node.get_and_clear_pending_events();
3683         assert_eq!(events_1.len(), 1);
3684         match events_1[0] {
3685                 Event::PendingHTLCsForwardable { .. } => { },
3686                 _ => panic!("Unexpected event"),
3687         };
3688
3689         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3690         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3691         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3692
3693         nodes[1].node.process_pending_htlc_forwards();
3694
3695         let events_2 = nodes[1].node.get_and_clear_pending_events();
3696         assert_eq!(events_2.len(), 1);
3697         match events_2[0] {
3698                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3699                         assert_eq!(payment_hash_1, *payment_hash);
3700                         assert_eq!(*payment_secret, None);
3701                         assert_eq!(amt, 1000000);
3702                 },
3703                 _ => panic!("Unexpected event"),
3704         }
3705
3706         nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3707         check_added_monitors!(nodes[1], 1);
3708
3709         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3710         assert_eq!(events_3.len(), 1);
3711         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3712                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3713                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3714                         assert!(updates.update_add_htlcs.is_empty());
3715                         assert!(updates.update_fail_htlcs.is_empty());
3716                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3717                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3718                         assert!(updates.update_fee.is_none());
3719                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3720                 },
3721                 _ => panic!("Unexpected event"),
3722         };
3723
3724         if messages_delivered >= 1 {
3725                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3726
3727                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3728                 assert_eq!(events_4.len(), 1);
3729                 match events_4[0] {
3730                         Event::PaymentSent { ref payment_preimage } => {
3731                                 assert_eq!(payment_preimage_1, *payment_preimage);
3732                         },
3733                         _ => panic!("Unexpected event"),
3734                 }
3735
3736                 if messages_delivered >= 2 {
3737                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3738                         check_added_monitors!(nodes[0], 1);
3739                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3740
3741                         if messages_delivered >= 3 {
3742                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3743                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3744                                 check_added_monitors!(nodes[1], 1);
3745
3746                                 if messages_delivered >= 4 {
3747                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3748                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3749                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3750                                         check_added_monitors!(nodes[1], 1);
3751
3752                                         if messages_delivered >= 5 {
3753                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3754                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3755                                                 check_added_monitors!(nodes[0], 1);
3756                                         }
3757                                 }
3758                         }
3759                 }
3760         }
3761
3762         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3763         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3764         if messages_delivered < 2 {
3765                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3766                 //TODO: Deduplicate PaymentSent events, then enable this if:
3767                 //if messages_delivered < 1 {
3768                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3769                         assert_eq!(events_4.len(), 1);
3770                         match events_4[0] {
3771                                 Event::PaymentSent { ref payment_preimage } => {
3772                                         assert_eq!(payment_preimage_1, *payment_preimage);
3773                                 },
3774                                 _ => panic!("Unexpected event"),
3775                         }
3776                 //}
3777         } else if messages_delivered == 2 {
3778                 // nodes[0] still wants its RAA + commitment_signed
3779                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3780         } else if messages_delivered == 3 {
3781                 // nodes[0] still wants its commitment_signed
3782                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3783         } else if messages_delivered == 4 {
3784                 // nodes[1] still wants its final RAA
3785                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3786         } else if messages_delivered == 5 {
3787                 // Everything was delivered...
3788                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3789         }
3790
3791         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3792         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3793         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3794
3795         // Channel should still work fine...
3796         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3797         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3798                 &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3799                 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3800         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3801         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3802 }
3803
3804 #[test]
3805 fn test_drop_messages_peer_disconnect_a() {
3806         do_test_drop_messages_peer_disconnect(0);
3807         do_test_drop_messages_peer_disconnect(1);
3808         do_test_drop_messages_peer_disconnect(2);
3809         do_test_drop_messages_peer_disconnect(3);
3810 }
3811
3812 #[test]
3813 fn test_drop_messages_peer_disconnect_b() {
3814         do_test_drop_messages_peer_disconnect(4);
3815         do_test_drop_messages_peer_disconnect(5);
3816         do_test_drop_messages_peer_disconnect(6);
3817 }
3818
3819 #[test]
3820 fn test_funding_peer_disconnect() {
3821         // Test that we can lock in our funding tx while disconnected
3822         let chanmon_cfgs = create_chanmon_cfgs(2);
3823         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3824         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3825         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3826         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3827
3828         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3829         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3830
3831         confirm_transaction(&nodes[0], &tx);
3832         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3833         assert_eq!(events_1.len(), 1);
3834         match events_1[0] {
3835                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3836                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3837                 },
3838                 _ => panic!("Unexpected event"),
3839         }
3840
3841         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3842
3843         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3844         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3845
3846         confirm_transaction(&nodes[1], &tx);
3847         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3848         assert_eq!(events_2.len(), 2);
3849         let funding_locked = match events_2[0] {
3850                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3851                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3852                         msg.clone()
3853                 },
3854                 _ => panic!("Unexpected event"),
3855         };
3856         let bs_announcement_sigs = match events_2[1] {
3857                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3858                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3859                         msg.clone()
3860                 },
3861                 _ => panic!("Unexpected event"),
3862         };
3863
3864         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3865
3866         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3867         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3868         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3869         assert_eq!(events_3.len(), 2);
3870         let as_announcement_sigs = match events_3[0] {
3871                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3872                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3873                         msg.clone()
3874                 },
3875                 _ => panic!("Unexpected event"),
3876         };
3877         let (as_announcement, as_update) = match events_3[1] {
3878                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3879                         (msg.clone(), update_msg.clone())
3880                 },
3881                 _ => panic!("Unexpected event"),
3882         };
3883
3884         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3885         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3886         assert_eq!(events_4.len(), 1);
3887         let (_, bs_update) = match events_4[0] {
3888                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3889                         (msg.clone(), update_msg.clone())
3890                 },
3891                 _ => panic!("Unexpected event"),
3892         };
3893
3894         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3895         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3896         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3897
3898         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3899         let logger = test_utils::TestLogger::new();
3900         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();
3901         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3902         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3903 }
3904
3905 #[test]
3906 fn test_drop_messages_peer_disconnect_dual_htlc() {
3907         // Test that we can handle reconnecting when both sides of a channel have pending
3908         // commitment_updates when we disconnect.
3909         let chanmon_cfgs = create_chanmon_cfgs(2);
3910         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3911         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3912         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3913         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3914         let logger = test_utils::TestLogger::new();
3915
3916         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3917
3918         // Now try to send a second payment which will fail to send
3919         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3920         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3921         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();
3922         nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3923         check_added_monitors!(nodes[0], 1);
3924
3925         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3926         assert_eq!(events_1.len(), 1);
3927         match events_1[0] {
3928                 MessageSendEvent::UpdateHTLCs { .. } => {},
3929                 _ => panic!("Unexpected event"),
3930         }
3931
3932         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3933         check_added_monitors!(nodes[1], 1);
3934
3935         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3936         assert_eq!(events_2.len(), 1);
3937         match events_2[0] {
3938                 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 } } => {
3939                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3940                         assert!(update_add_htlcs.is_empty());
3941                         assert_eq!(update_fulfill_htlcs.len(), 1);
3942                         assert!(update_fail_htlcs.is_empty());
3943                         assert!(update_fail_malformed_htlcs.is_empty());
3944                         assert!(update_fee.is_none());
3945
3946                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3947                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3948                         assert_eq!(events_3.len(), 1);
3949                         match events_3[0] {
3950                                 Event::PaymentSent { ref payment_preimage } => {
3951                                         assert_eq!(*payment_preimage, payment_preimage_1);
3952                                 },
3953                                 _ => panic!("Unexpected event"),
3954                         }
3955
3956                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3957                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3958                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3959                         check_added_monitors!(nodes[0], 1);
3960                 },
3961                 _ => panic!("Unexpected event"),
3962         }
3963
3964         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3965         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3966
3967         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3968         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3969         assert_eq!(reestablish_1.len(), 1);
3970         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3971         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3972         assert_eq!(reestablish_2.len(), 1);
3973
3974         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3975         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3976         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3977         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3978
3979         assert!(as_resp.0.is_none());
3980         assert!(bs_resp.0.is_none());
3981
3982         assert!(bs_resp.1.is_none());
3983         assert!(bs_resp.2.is_none());
3984
3985         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3986
3987         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3988         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3989         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3990         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3991         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3992         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3993         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3994         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3995         // No commitment_signed so get_event_msg's assert(len == 1) passes
3996         check_added_monitors!(nodes[1], 1);
3997
3998         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3999         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4000         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4001         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4002         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4003         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4004         assert!(bs_second_commitment_signed.update_fee.is_none());
4005         check_added_monitors!(nodes[1], 1);
4006
4007         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4008         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4009         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4010         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4011         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4012         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4013         assert!(as_commitment_signed.update_fee.is_none());
4014         check_added_monitors!(nodes[0], 1);
4015
4016         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4017         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4018         // No commitment_signed so get_event_msg's assert(len == 1) passes
4019         check_added_monitors!(nodes[0], 1);
4020
4021         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4022         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4023         // No commitment_signed so get_event_msg's assert(len == 1) passes
4024         check_added_monitors!(nodes[1], 1);
4025
4026         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4027         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4028         check_added_monitors!(nodes[1], 1);
4029
4030         expect_pending_htlcs_forwardable!(nodes[1]);
4031
4032         let events_5 = nodes[1].node.get_and_clear_pending_events();
4033         assert_eq!(events_5.len(), 1);
4034         match events_5[0] {
4035                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4036                         assert_eq!(payment_hash_2, *payment_hash);
4037                         assert_eq!(*payment_secret, None);
4038                 },
4039                 _ => panic!("Unexpected event"),
4040         }
4041
4042         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4043         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4044         check_added_monitors!(nodes[0], 1);
4045
4046         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4047 }
4048
4049 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4050         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4051         // to avoid our counterparty failing the channel.
4052         let chanmon_cfgs = create_chanmon_cfgs(2);
4053         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4054         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4055         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4056
4057         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4058         let logger = test_utils::TestLogger::new();
4059
4060         let our_payment_hash = if send_partial_mpp {
4061                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4062                 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();
4063                 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4064                 let payment_secret = PaymentSecret([0xdb; 32]);
4065                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4066                 // indicates there are more HTLCs coming.
4067                 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.
4068                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height).unwrap();
4069                 check_added_monitors!(nodes[0], 1);
4070                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4071                 assert_eq!(events.len(), 1);
4072                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4073                 // hop should *not* yet generate any PaymentReceived event(s).
4074                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4075                 our_payment_hash
4076         } else {
4077                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4078         };
4079
4080         let mut block = Block {
4081                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4082                 txdata: vec![],
4083         };
4084         connect_block(&nodes[0], &block);
4085         connect_block(&nodes[1], &block);
4086         for _ in CHAN_CONFIRM_DEPTH + 2 ..TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4087                 block.header.prev_blockhash = block.block_hash();
4088                 connect_block(&nodes[0], &block);
4089                 connect_block(&nodes[1], &block);
4090         }
4091
4092         expect_pending_htlcs_forwardable!(nodes[1]);
4093
4094         check_added_monitors!(nodes[1], 1);
4095         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4096         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4097         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4098         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4099         assert!(htlc_timeout_updates.update_fee.is_none());
4100
4101         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4102         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4103         // 100_000 msat as u64, followed by a height of TEST_FINAL_CLTV + 2 as u32
4104         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4105         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(TEST_FINAL_CLTV + 2));
4106         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4107 }
4108
4109 #[test]
4110 fn test_htlc_timeout() {
4111         do_test_htlc_timeout(true);
4112         do_test_htlc_timeout(false);
4113 }
4114
4115 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4116         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4117         let chanmon_cfgs = create_chanmon_cfgs(3);
4118         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4119         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4120         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4121         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4122         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4123
4124         // Make sure all nodes are at the same starting height
4125         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4126         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4127         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4128
4129         let logger = test_utils::TestLogger::new();
4130
4131         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4132         let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4133         {
4134                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4135                 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();
4136                 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4137         }
4138         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4139         check_added_monitors!(nodes[1], 1);
4140
4141         // Now attempt to route a second payment, which should be placed in the holding cell
4142         let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4143         if forwarded_htlc {
4144                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4145                 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();
4146                 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4147                 check_added_monitors!(nodes[0], 1);
4148                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4149                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4150                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4151                 expect_pending_htlcs_forwardable!(nodes[1]);
4152                 check_added_monitors!(nodes[1], 0);
4153         } else {
4154                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4155                 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();
4156                 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4157                 check_added_monitors!(nodes[1], 0);
4158         }
4159
4160         connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4161         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4162         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4163         connect_blocks(&nodes[1], 1);
4164
4165         if forwarded_htlc {
4166                 expect_pending_htlcs_forwardable!(nodes[1]);
4167                 check_added_monitors!(nodes[1], 1);
4168                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4169                 assert_eq!(fail_commit.len(), 1);
4170                 match fail_commit[0] {
4171                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4172                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4173                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4174                         },
4175                         _ => unreachable!(),
4176                 }
4177                 expect_payment_failed!(nodes[0], second_payment_hash, false);
4178                 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4179                         match update {
4180                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4181                                 _ => panic!("Unexpected event"),
4182                         }
4183                 } else {
4184                         panic!("Unexpected event");
4185                 }
4186         } else {
4187                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4188         }
4189 }
4190
4191 #[test]
4192 fn test_holding_cell_htlc_add_timeouts() {
4193         do_test_holding_cell_htlc_add_timeouts(false);
4194         do_test_holding_cell_htlc_add_timeouts(true);
4195 }
4196
4197 #[test]
4198 fn test_invalid_channel_announcement() {
4199         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4200         let secp_ctx = Secp256k1::new();
4201         let chanmon_cfgs = create_chanmon_cfgs(2);
4202         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4203         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4204         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4205
4206         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4207
4208         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4209         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4210         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4211         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4212
4213         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 } );
4214
4215         let as_bitcoin_key = as_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4216         let bs_bitcoin_key = bs_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4217
4218         let as_network_key = nodes[0].node.get_our_node_id();
4219         let bs_network_key = nodes[1].node.get_our_node_id();
4220
4221         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4222
4223         let mut chan_announcement;
4224
4225         macro_rules! dummy_unsigned_msg {
4226                 () => {
4227                         msgs::UnsignedChannelAnnouncement {
4228                                 features: ChannelFeatures::known(),
4229                                 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4230                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4231                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4232                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4233                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4234                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4235                                 excess_data: Vec::new(),
4236                         };
4237                 }
4238         }
4239
4240         macro_rules! sign_msg {
4241                 ($unsigned_msg: expr) => {
4242                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4243                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_signer().inner.funding_key);
4244                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_signer().inner.funding_key);
4245                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4246                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4247                         chan_announcement = msgs::ChannelAnnouncement {
4248                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4249                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4250                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4251                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4252                                 contents: $unsigned_msg
4253                         }
4254                 }
4255         }
4256
4257         let unsigned_msg = dummy_unsigned_msg!();
4258         sign_msg!(unsigned_msg);
4259         assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4260         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 } );
4261
4262         // Configured with Network::Testnet
4263         let mut unsigned_msg = dummy_unsigned_msg!();
4264         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4265         sign_msg!(unsigned_msg);
4266         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4267
4268         let mut unsigned_msg = dummy_unsigned_msg!();
4269         unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4270         sign_msg!(unsigned_msg);
4271         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4272 }
4273
4274 #[test]
4275 fn test_no_txn_manager_serialize_deserialize() {
4276         let chanmon_cfgs = create_chanmon_cfgs(2);
4277         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4278         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4279         let logger: test_utils::TestLogger;
4280         let fee_estimator: test_utils::TestFeeEstimator;
4281         let persister: test_utils::TestPersister;
4282         let new_chain_monitor: test_utils::TestChainMonitor;
4283         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4284         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4285
4286         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4287
4288         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4289
4290         let nodes_0_serialized = nodes[0].node.encode();
4291         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4292         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4293
4294         logger = test_utils::TestLogger::new();
4295         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4296         persister = test_utils::TestPersister::new();
4297         let keys_manager = &chanmon_cfgs[0].keys_manager;
4298         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4299         nodes[0].chain_monitor = &new_chain_monitor;
4300         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4301         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4302                 &mut chan_0_monitor_read, keys_manager).unwrap();
4303         assert!(chan_0_monitor_read.is_empty());
4304
4305         let mut nodes_0_read = &nodes_0_serialized[..];
4306         let config = UserConfig::default();
4307         let (_, nodes_0_deserialized_tmp) = {
4308                 let mut channel_monitors = HashMap::new();
4309                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4310                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4311                         default_config: config,
4312                         keys_manager,
4313                         fee_estimator: &fee_estimator,
4314                         chain_monitor: nodes[0].chain_monitor,
4315                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4316                         logger: &logger,
4317                         channel_monitors,
4318                 }).unwrap()
4319         };
4320         nodes_0_deserialized = nodes_0_deserialized_tmp;
4321         assert!(nodes_0_read.is_empty());
4322
4323         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4324         nodes[0].node = &nodes_0_deserialized;
4325         assert_eq!(nodes[0].node.list_channels().len(), 1);
4326         check_added_monitors!(nodes[0], 1);
4327
4328         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4329         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4330         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4331         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4332
4333         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4334         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4335         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4336         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4337
4338         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4339         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4340         for node in nodes.iter() {
4341                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4342                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4343                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4344         }
4345
4346         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4347 }
4348
4349 #[test]
4350 fn test_manager_serialize_deserialize_events() {
4351         // This test makes sure the events field in ChannelManager survives de/serialization
4352         let chanmon_cfgs = create_chanmon_cfgs(2);
4353         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4354         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4355         let fee_estimator: test_utils::TestFeeEstimator;
4356         let persister: test_utils::TestPersister;
4357         let logger: test_utils::TestLogger;
4358         let new_chain_monitor: test_utils::TestChainMonitor;
4359         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4360         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4361
4362         // Start creating a channel, but stop right before broadcasting the funding transaction
4363         let channel_value = 100000;
4364         let push_msat = 10001;
4365         let a_flags = InitFeatures::known();
4366         let b_flags = InitFeatures::known();
4367         let node_a = nodes.remove(0);
4368         let node_b = nodes.remove(0);
4369         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4370         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()));
4371         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()));
4372
4373         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4374
4375         node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4376         check_added_monitors!(node_a, 0);
4377
4378         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()));
4379         {
4380                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4381                 assert_eq!(added_monitors.len(), 1);
4382                 assert_eq!(added_monitors[0].0, funding_output);
4383                 added_monitors.clear();
4384         }
4385
4386         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()));
4387         {
4388                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4389                 assert_eq!(added_monitors.len(), 1);
4390                 assert_eq!(added_monitors[0].0, funding_output);
4391                 added_monitors.clear();
4392         }
4393         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4394
4395         nodes.push(node_a);
4396         nodes.push(node_b);
4397
4398         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4399         let nodes_0_serialized = nodes[0].node.encode();
4400         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4401         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4402
4403         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4404         logger = test_utils::TestLogger::new();
4405         persister = test_utils::TestPersister::new();
4406         let keys_manager = &chanmon_cfgs[0].keys_manager;
4407         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4408         nodes[0].chain_monitor = &new_chain_monitor;
4409         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4410         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4411                 &mut chan_0_monitor_read, keys_manager).unwrap();
4412         assert!(chan_0_monitor_read.is_empty());
4413
4414         let mut nodes_0_read = &nodes_0_serialized[..];
4415         let config = UserConfig::default();
4416         let (_, nodes_0_deserialized_tmp) = {
4417                 let mut channel_monitors = HashMap::new();
4418                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4419                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4420                         default_config: config,
4421                         keys_manager,
4422                         fee_estimator: &fee_estimator,
4423                         chain_monitor: nodes[0].chain_monitor,
4424                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4425                         logger: &logger,
4426                         channel_monitors,
4427                 }).unwrap()
4428         };
4429         nodes_0_deserialized = nodes_0_deserialized_tmp;
4430         assert!(nodes_0_read.is_empty());
4431
4432         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4433
4434         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4435         nodes[0].node = &nodes_0_deserialized;
4436
4437         // After deserializing, make sure the funding_transaction is still held by the channel manager
4438         let events_4 = nodes[0].node.get_and_clear_pending_events();
4439         assert_eq!(events_4.len(), 0);
4440         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4441         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4442
4443         // Make sure the channel is functioning as though the de/serialization never happened
4444         assert_eq!(nodes[0].node.list_channels().len(), 1);
4445         check_added_monitors!(nodes[0], 1);
4446
4447         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4448         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4449         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4450         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4451
4452         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4453         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4454         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4455         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4456
4457         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4458         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4459         for node in nodes.iter() {
4460                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4461                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4462                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4463         }
4464
4465         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4466 }
4467
4468 #[test]
4469 fn test_simple_manager_serialize_deserialize() {
4470         let chanmon_cfgs = create_chanmon_cfgs(2);
4471         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4472         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4473         let logger: test_utils::TestLogger;
4474         let fee_estimator: test_utils::TestFeeEstimator;
4475         let persister: test_utils::TestPersister;
4476         let new_chain_monitor: test_utils::TestChainMonitor;
4477         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4478         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4479         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4480
4481         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4482         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4483
4484         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4485
4486         let nodes_0_serialized = nodes[0].node.encode();
4487         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4488         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4489
4490         logger = test_utils::TestLogger::new();
4491         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4492         persister = test_utils::TestPersister::new();
4493         let keys_manager = &chanmon_cfgs[0].keys_manager;
4494         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4495         nodes[0].chain_monitor = &new_chain_monitor;
4496         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4497         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4498                 &mut chan_0_monitor_read, keys_manager).unwrap();
4499         assert!(chan_0_monitor_read.is_empty());
4500
4501         let mut nodes_0_read = &nodes_0_serialized[..];
4502         let (_, nodes_0_deserialized_tmp) = {
4503                 let mut channel_monitors = HashMap::new();
4504                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4505                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4506                         default_config: UserConfig::default(),
4507                         keys_manager,
4508                         fee_estimator: &fee_estimator,
4509                         chain_monitor: nodes[0].chain_monitor,
4510                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4511                         logger: &logger,
4512                         channel_monitors,
4513                 }).unwrap()
4514         };
4515         nodes_0_deserialized = nodes_0_deserialized_tmp;
4516         assert!(nodes_0_read.is_empty());
4517
4518         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4519         nodes[0].node = &nodes_0_deserialized;
4520         check_added_monitors!(nodes[0], 1);
4521
4522         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4523
4524         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4525         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4526 }
4527
4528 #[test]
4529 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4530         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4531         let chanmon_cfgs = create_chanmon_cfgs(4);
4532         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4533         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4534         let logger: test_utils::TestLogger;
4535         let fee_estimator: test_utils::TestFeeEstimator;
4536         let persister: test_utils::TestPersister;
4537         let new_chain_monitor: test_utils::TestChainMonitor;
4538         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4539         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4540         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4541         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4542         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4543
4544         let mut node_0_stale_monitors_serialized = Vec::new();
4545         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4546                 let mut writer = test_utils::TestVecWriter(Vec::new());
4547                 monitor.1.write(&mut writer).unwrap();
4548                 node_0_stale_monitors_serialized.push(writer.0);
4549         }
4550
4551         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4552
4553         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4554         let nodes_0_serialized = nodes[0].node.encode();
4555
4556         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4557         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4558         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4559         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4560
4561         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4562         // nodes[3])
4563         let mut node_0_monitors_serialized = Vec::new();
4564         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4565                 let mut writer = test_utils::TestVecWriter(Vec::new());
4566                 monitor.1.write(&mut writer).unwrap();
4567                 node_0_monitors_serialized.push(writer.0);
4568         }
4569
4570         logger = test_utils::TestLogger::new();
4571         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4572         persister = test_utils::TestPersister::new();
4573         let keys_manager = &chanmon_cfgs[0].keys_manager;
4574         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4575         nodes[0].chain_monitor = &new_chain_monitor;
4576
4577
4578         let mut node_0_stale_monitors = Vec::new();
4579         for serialized in node_0_stale_monitors_serialized.iter() {
4580                 let mut read = &serialized[..];
4581                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4582                 assert!(read.is_empty());
4583                 node_0_stale_monitors.push(monitor);
4584         }
4585
4586         let mut node_0_monitors = Vec::new();
4587         for serialized in node_0_monitors_serialized.iter() {
4588                 let mut read = &serialized[..];
4589                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4590                 assert!(read.is_empty());
4591                 node_0_monitors.push(monitor);
4592         }
4593
4594         let mut nodes_0_read = &nodes_0_serialized[..];
4595         if let Err(msgs::DecodeError::InvalidValue) =
4596                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4597                 default_config: UserConfig::default(),
4598                 keys_manager,
4599                 fee_estimator: &fee_estimator,
4600                 chain_monitor: nodes[0].chain_monitor,
4601                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4602                 logger: &logger,
4603                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4604         }) { } else {
4605                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4606         };
4607
4608         let mut nodes_0_read = &nodes_0_serialized[..];
4609         let (_, nodes_0_deserialized_tmp) =
4610                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4611                 default_config: UserConfig::default(),
4612                 keys_manager,
4613                 fee_estimator: &fee_estimator,
4614                 chain_monitor: nodes[0].chain_monitor,
4615                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4616                 logger: &logger,
4617                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4618         }).unwrap();
4619         nodes_0_deserialized = nodes_0_deserialized_tmp;
4620         assert!(nodes_0_read.is_empty());
4621
4622         { // Channel close should result in a commitment tx and an HTLC tx
4623                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4624                 assert_eq!(txn.len(), 2);
4625                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4626                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4627         }
4628
4629         for monitor in node_0_monitors.drain(..) {
4630                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4631                 check_added_monitors!(nodes[0], 1);
4632         }
4633         nodes[0].node = &nodes_0_deserialized;
4634
4635         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4636         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4637         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4638         //... and we can even still claim the payment!
4639         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4640
4641         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4642         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4643         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4644         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4645         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4646         assert_eq!(msg_events.len(), 1);
4647         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4648                 match action {
4649                         &ErrorAction::SendErrorMessage { ref msg } => {
4650                                 assert_eq!(msg.channel_id, channel_id);
4651                         },
4652                         _ => panic!("Unexpected event!"),
4653                 }
4654         }
4655 }
4656
4657 macro_rules! check_spendable_outputs {
4658         ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4659                 {
4660                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4661                         let mut txn = Vec::new();
4662                         let mut all_outputs = Vec::new();
4663                         let secp_ctx = Secp256k1::new();
4664                         for event in events.drain(..) {
4665                                 match event {
4666                                         Event::SpendableOutputs { mut outputs } => {
4667                                                 for outp in outputs.drain(..) {
4668                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4669                                                         all_outputs.push(outp);
4670                                                 }
4671                                         },
4672                                         _ => panic!("Unexpected event"),
4673                                 };
4674                         }
4675                         if all_outputs.len() > 1 {
4676                                 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) {
4677                                         txn.push(tx);
4678                                 }
4679                         }
4680                         txn
4681                 }
4682         }
4683 }
4684
4685 #[test]
4686 fn test_claim_sizeable_push_msat() {
4687         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4688         let chanmon_cfgs = create_chanmon_cfgs(2);
4689         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4690         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4691         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4692
4693         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4694         nodes[1].node.force_close_channel(&chan.2).unwrap();
4695         check_closed_broadcast!(nodes[1], true);
4696         check_added_monitors!(nodes[1], 1);
4697         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4698         assert_eq!(node_txn.len(), 1);
4699         check_spends!(node_txn[0], chan.3);
4700         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
4701
4702         mine_transaction(&nodes[1], &node_txn[0]);
4703         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4704
4705         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4706         assert_eq!(spend_txn.len(), 1);
4707         check_spends!(spend_txn[0], node_txn[0]);
4708 }
4709
4710 #[test]
4711 fn test_claim_on_remote_sizeable_push_msat() {
4712         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4713         // to_remote output is encumbered by a P2WPKH
4714         let chanmon_cfgs = create_chanmon_cfgs(2);
4715         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4716         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4717         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4718
4719         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4720         nodes[0].node.force_close_channel(&chan.2).unwrap();
4721         check_closed_broadcast!(nodes[0], true);
4722         check_added_monitors!(nodes[0], 1);
4723
4724         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4725         assert_eq!(node_txn.len(), 1);
4726         check_spends!(node_txn[0], chan.3);
4727         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
4728
4729         mine_transaction(&nodes[1], &node_txn[0]);
4730         check_closed_broadcast!(nodes[1], true);
4731         check_added_monitors!(nodes[1], 1);
4732         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4733
4734         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4735         assert_eq!(spend_txn.len(), 1);
4736         check_spends!(spend_txn[0], node_txn[0]);
4737 }
4738
4739 #[test]
4740 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4741         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4742         // to_remote output is encumbered by a P2WPKH
4743
4744         let chanmon_cfgs = create_chanmon_cfgs(2);
4745         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4746         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4747         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4748
4749         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4750         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4751         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4752         assert_eq!(revoked_local_txn[0].input.len(), 1);
4753         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4754
4755         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4756         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4757         check_closed_broadcast!(nodes[1], true);
4758         check_added_monitors!(nodes[1], 1);
4759
4760         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4761         mine_transaction(&nodes[1], &node_txn[0]);
4762         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4763
4764         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4765         assert_eq!(spend_txn.len(), 3);
4766         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4767         check_spends!(spend_txn[1], node_txn[0]);
4768         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4769 }
4770
4771 #[test]
4772 fn test_static_spendable_outputs_preimage_tx() {
4773         let chanmon_cfgs = create_chanmon_cfgs(2);
4774         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4775         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4776         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4777
4778         // Create some initial channels
4779         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4780
4781         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4782
4783         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4784         assert_eq!(commitment_tx[0].input.len(), 1);
4785         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4786
4787         // Settle A's commitment tx on B's chain
4788         assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4789         check_added_monitors!(nodes[1], 1);
4790         mine_transaction(&nodes[1], &commitment_tx[0]);
4791         check_added_monitors!(nodes[1], 1);
4792         let events = nodes[1].node.get_and_clear_pending_msg_events();
4793         match events[0] {
4794                 MessageSendEvent::UpdateHTLCs { .. } => {},
4795                 _ => panic!("Unexpected event"),
4796         }
4797         match events[1] {
4798                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4799                 _ => panic!("Unexepected event"),
4800         }
4801
4802         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4803         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4804         assert_eq!(node_txn.len(), 3);
4805         check_spends!(node_txn[0], commitment_tx[0]);
4806         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4807         check_spends!(node_txn[1], chan_1.3);
4808         check_spends!(node_txn[2], node_txn[1]);
4809
4810         mine_transaction(&nodes[1], &node_txn[0]);
4811         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4812
4813         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4814         assert_eq!(spend_txn.len(), 1);
4815         check_spends!(spend_txn[0], node_txn[0]);
4816 }
4817
4818 #[test]
4819 fn test_static_spendable_outputs_timeout_tx() {
4820         let chanmon_cfgs = create_chanmon_cfgs(2);
4821         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4822         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4823         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4824
4825         // Create some initial channels
4826         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4827
4828         // Rebalance the network a bit by relaying one payment through all the channels ...
4829         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4830
4831         let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4832
4833         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4834         assert_eq!(commitment_tx[0].input.len(), 1);
4835         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4836
4837         // Settle A's commitment tx on B' chain
4838         mine_transaction(&nodes[1], &commitment_tx[0]);
4839         check_added_monitors!(nodes[1], 1);
4840         let events = nodes[1].node.get_and_clear_pending_msg_events();
4841         match events[0] {
4842                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4843                 _ => panic!("Unexpected event"),
4844         }
4845
4846         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4847         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4848         assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4849         check_spends!(node_txn[0],  commitment_tx[0].clone());
4850         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4851         check_spends!(node_txn[1], chan_1.3.clone());
4852         check_spends!(node_txn[2], node_txn[1]);
4853
4854         mine_transaction(&nodes[1], &node_txn[0]);
4855         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4856         expect_payment_failed!(nodes[1], our_payment_hash, true);
4857
4858         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4859         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4860         check_spends!(spend_txn[0], commitment_tx[0]);
4861         check_spends!(spend_txn[1], node_txn[0]);
4862         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4863 }
4864
4865 #[test]
4866 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4867         let chanmon_cfgs = create_chanmon_cfgs(2);
4868         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4869         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4870         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4871
4872         // Create some initial channels
4873         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4874
4875         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4876         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4877         assert_eq!(revoked_local_txn[0].input.len(), 1);
4878         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4879
4880         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4881
4882         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4883         check_closed_broadcast!(nodes[1], true);
4884         check_added_monitors!(nodes[1], 1);
4885
4886         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4887         assert_eq!(node_txn.len(), 2);
4888         assert_eq!(node_txn[0].input.len(), 2);
4889         check_spends!(node_txn[0], revoked_local_txn[0]);
4890
4891         mine_transaction(&nodes[1], &node_txn[0]);
4892         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4893
4894         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4895         assert_eq!(spend_txn.len(), 1);
4896         check_spends!(spend_txn[0], node_txn[0]);
4897 }
4898
4899 #[test]
4900 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4901         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4902         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4903         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4904         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4905         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4906
4907         // Create some initial channels
4908         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4909
4910         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4911         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4912         assert_eq!(revoked_local_txn[0].input.len(), 1);
4913         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4914
4915         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4916
4917         // A will generate HTLC-Timeout from revoked commitment tx
4918         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4919         check_closed_broadcast!(nodes[0], true);
4920         check_added_monitors!(nodes[0], 1);
4921
4922         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4923         assert_eq!(revoked_htlc_txn.len(), 2);
4924         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4925         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4926         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4927         check_spends!(revoked_htlc_txn[1], chan_1.3);
4928
4929         // B will generate justice tx from A's revoked commitment/HTLC tx
4930         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4931         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4932         check_closed_broadcast!(nodes[1], true);
4933         check_added_monitors!(nodes[1], 1);
4934
4935         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4936         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4937         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4938         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4939         // transactions next...
4940         assert_eq!(node_txn[0].input.len(), 3);
4941         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4942
4943         assert_eq!(node_txn[1].input.len(), 2);
4944         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4945         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4946                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4947         } else {
4948                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4949                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4950         }
4951
4952         assert_eq!(node_txn[2].input.len(), 1);
4953         check_spends!(node_txn[2], chan_1.3);
4954
4955         mine_transaction(&nodes[1], &node_txn[1]);
4956         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4957
4958         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4959         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4960         assert_eq!(spend_txn.len(), 1);
4961         assert_eq!(spend_txn[0].input.len(), 1);
4962         check_spends!(spend_txn[0], node_txn[1]);
4963 }
4964
4965 #[test]
4966 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4967         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4968         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4969         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4970         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4971         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4972
4973         // Create some initial channels
4974         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4975
4976         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4977         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4978         assert_eq!(revoked_local_txn[0].input.len(), 1);
4979         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4980
4981         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4982         assert_eq!(revoked_local_txn[0].output.len(), 2);
4983
4984         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4985
4986         // B will generate HTLC-Success from revoked commitment tx
4987         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4988         check_closed_broadcast!(nodes[1], true);
4989         check_added_monitors!(nodes[1], 1);
4990         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4991
4992         assert_eq!(revoked_htlc_txn.len(), 2);
4993         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4994         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4995         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4996
4997         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4998         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4999         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5000
5001         // A will generate justice tx from B's revoked commitment/HTLC tx
5002         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5003         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5004         check_closed_broadcast!(nodes[0], true);
5005         check_added_monitors!(nodes[0], 1);
5006
5007         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5008         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5009
5010         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5011         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5012         // transactions next...
5013         assert_eq!(node_txn[0].input.len(), 2);
5014         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5015         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5016                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5017         } else {
5018                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5019                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5020         }
5021
5022         assert_eq!(node_txn[1].input.len(), 1);
5023         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5024
5025         check_spends!(node_txn[2], chan_1.3);
5026
5027         mine_transaction(&nodes[0], &node_txn[1]);
5028         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5029
5030         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5031         // didn't try to generate any new transactions.
5032
5033         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5034         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5035         assert_eq!(spend_txn.len(), 3);
5036         assert_eq!(spend_txn[0].input.len(), 1);
5037         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5038         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5039         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5040         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5041 }
5042
5043 #[test]
5044 fn test_onchain_to_onchain_claim() {
5045         // Test that in case of channel closure, we detect the state of output and claim HTLC
5046         // on downstream peer's remote commitment tx.
5047         // First, have C claim an HTLC against its own latest commitment transaction.
5048         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5049         // channel.
5050         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5051         // gets broadcast.
5052
5053         let chanmon_cfgs = create_chanmon_cfgs(3);
5054         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5055         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5056         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5057
5058         // Create some initial channels
5059         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5060         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5061
5062         // Rebalance the network a bit by relaying one payment through all the channels ...
5063         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5064         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5065
5066         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5067         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5068         check_spends!(commitment_tx[0], chan_2.3);
5069         nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5070         check_added_monitors!(nodes[2], 1);
5071         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5072         assert!(updates.update_add_htlcs.is_empty());
5073         assert!(updates.update_fail_htlcs.is_empty());
5074         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5075         assert!(updates.update_fail_malformed_htlcs.is_empty());
5076
5077         mine_transaction(&nodes[2], &commitment_tx[0]);
5078         check_closed_broadcast!(nodes[2], true);
5079         check_added_monitors!(nodes[2], 1);
5080
5081         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5082         assert_eq!(c_txn.len(), 3);
5083         assert_eq!(c_txn[0], c_txn[2]);
5084         assert_eq!(commitment_tx[0], c_txn[1]);
5085         check_spends!(c_txn[1], chan_2.3);
5086         check_spends!(c_txn[2], c_txn[1]);
5087         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5088         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5089         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5090         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5091
5092         // 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
5093         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5094         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5095         {
5096                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5097                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5098                 assert_eq!(b_txn.len(), 3);
5099                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5100                 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5101                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5102                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5103                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5104                 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5105                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5106                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5107                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5108                 b_txn.clear();
5109         }
5110         check_added_monitors!(nodes[1], 1);
5111         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5112         assert_eq!(msg_events.len(), 3);
5113         check_added_monitors!(nodes[1], 1);
5114         match msg_events[0] {
5115                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5116                 _ => panic!("Unexpected event"),
5117         }
5118         match msg_events[1] {
5119                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5120                 _ => panic!("Unexpected event"),
5121         }
5122         match msg_events[2] {
5123                 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, .. } } => {
5124                         assert!(update_add_htlcs.is_empty());
5125                         assert!(update_fail_htlcs.is_empty());
5126                         assert_eq!(update_fulfill_htlcs.len(), 1);
5127                         assert!(update_fail_malformed_htlcs.is_empty());
5128                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5129                 },
5130                 _ => panic!("Unexpected event"),
5131         };
5132         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5133         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5134         mine_transaction(&nodes[1], &commitment_tx[0]);
5135         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5136         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5137         assert_eq!(b_txn.len(), 3);
5138         check_spends!(b_txn[1], chan_1.3);
5139         check_spends!(b_txn[2], b_txn[1]);
5140         check_spends!(b_txn[0], commitment_tx[0]);
5141         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5142         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5143         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5144
5145         check_closed_broadcast!(nodes[1], true);
5146         check_added_monitors!(nodes[1], 1);
5147 }
5148
5149 #[test]
5150 fn test_duplicate_payment_hash_one_failure_one_success() {
5151         // Topology : A --> B --> C
5152         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5153         let chanmon_cfgs = create_chanmon_cfgs(3);
5154         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5155         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5156         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5157
5158         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5159         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5160
5161         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5162         *nodes[0].network_payment_count.borrow_mut() -= 1;
5163         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5164
5165         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5166         assert_eq!(commitment_txn[0].input.len(), 1);
5167         check_spends!(commitment_txn[0], chan_2.3);
5168
5169         mine_transaction(&nodes[1], &commitment_txn[0]);
5170         check_closed_broadcast!(nodes[1], true);
5171         check_added_monitors!(nodes[1], 1);
5172
5173         let htlc_timeout_tx;
5174         { // Extract one of the two HTLC-Timeout transaction
5175                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5176                 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5177                 assert_eq!(node_txn.len(), 5);
5178                 check_spends!(node_txn[0], commitment_txn[0]);
5179                 assert_eq!(node_txn[0].input.len(), 1);
5180                 check_spends!(node_txn[1], commitment_txn[0]);
5181                 assert_eq!(node_txn[1].input.len(), 1);
5182                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5183                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5184                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5185                 check_spends!(node_txn[2], chan_2.3);
5186                 check_spends!(node_txn[3], node_txn[2]);
5187                 check_spends!(node_txn[4], node_txn[2]);
5188                 htlc_timeout_tx = node_txn[1].clone();
5189         }
5190
5191         nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5192         mine_transaction(&nodes[2], &commitment_txn[0]);
5193         check_added_monitors!(nodes[2], 3);
5194         let events = nodes[2].node.get_and_clear_pending_msg_events();
5195         match events[0] {
5196                 MessageSendEvent::UpdateHTLCs { .. } => {},
5197                 _ => panic!("Unexpected event"),
5198         }
5199         match events[1] {
5200                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5201                 _ => panic!("Unexepected event"),
5202         }
5203         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5204         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)
5205         check_spends!(htlc_success_txn[2], chan_2.3);
5206         check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5207         check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5208         assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5209         assert_eq!(htlc_success_txn[0].input.len(), 1);
5210         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5211         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5212         assert_eq!(htlc_success_txn[1].input.len(), 1);
5213         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5214         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5215         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5216         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5217
5218         mine_transaction(&nodes[1], &htlc_timeout_tx);
5219         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5220         expect_pending_htlcs_forwardable!(nodes[1]);
5221         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5222         assert!(htlc_updates.update_add_htlcs.is_empty());
5223         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5224         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5225         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5226         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5227         check_added_monitors!(nodes[1], 1);
5228
5229         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5230         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5231         {
5232                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5233                 let events = nodes[0].node.get_and_clear_pending_msg_events();
5234                 assert_eq!(events.len(), 1);
5235                 match events[0] {
5236                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
5237                         },
5238                         _ => { panic!("Unexpected event"); }
5239                 }
5240         }
5241         expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5242
5243         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5244         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5245         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5246         assert!(updates.update_add_htlcs.is_empty());
5247         assert!(updates.update_fail_htlcs.is_empty());
5248         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5249         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5250         assert!(updates.update_fail_malformed_htlcs.is_empty());
5251         check_added_monitors!(nodes[1], 1);
5252
5253         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5254         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5255
5256         let events = nodes[0].node.get_and_clear_pending_events();
5257         match events[0] {
5258                 Event::PaymentSent { ref payment_preimage } => {
5259                         assert_eq!(*payment_preimage, our_payment_preimage);
5260                 }
5261                 _ => panic!("Unexpected event"),
5262         }
5263 }
5264
5265 #[test]
5266 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5267         let chanmon_cfgs = create_chanmon_cfgs(2);
5268         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5269         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5270         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5271
5272         // Create some initial channels
5273         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5274
5275         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5276         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5277         assert_eq!(local_txn.len(), 1);
5278         assert_eq!(local_txn[0].input.len(), 1);
5279         check_spends!(local_txn[0], chan_1.3);
5280
5281         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5282         nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5283         check_added_monitors!(nodes[1], 1);
5284         mine_transaction(&nodes[1], &local_txn[0]);
5285         check_added_monitors!(nodes[1], 1);
5286         let events = nodes[1].node.get_and_clear_pending_msg_events();
5287         match events[0] {
5288                 MessageSendEvent::UpdateHTLCs { .. } => {},
5289                 _ => panic!("Unexpected event"),
5290         }
5291         match events[1] {
5292                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5293                 _ => panic!("Unexepected event"),
5294         }
5295         let node_tx = {
5296                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5297                 assert_eq!(node_txn.len(), 3);
5298                 assert_eq!(node_txn[0], node_txn[2]);
5299                 assert_eq!(node_txn[1], local_txn[0]);
5300                 assert_eq!(node_txn[0].input.len(), 1);
5301                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5302                 check_spends!(node_txn[0], local_txn[0]);
5303                 node_txn[0].clone()
5304         };
5305
5306         mine_transaction(&nodes[1], &node_tx);
5307         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5308
5309         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5310         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5311         assert_eq!(spend_txn.len(), 1);
5312         check_spends!(spend_txn[0], node_tx);
5313 }
5314
5315 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5316         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5317         // unrevoked commitment transaction.
5318         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5319         // a remote RAA before they could be failed backwards (and combinations thereof).
5320         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5321         // use the same payment hashes.
5322         // Thus, we use a six-node network:
5323         //
5324         // A \         / E
5325         //    - C - D -
5326         // B /         \ F
5327         // And test where C fails back to A/B when D announces its latest commitment transaction
5328         let chanmon_cfgs = create_chanmon_cfgs(6);
5329         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5330         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5331         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5332         let logger = test_utils::TestLogger::new();
5333
5334         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5335         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5336         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5337         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5338         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5339
5340         // Rebalance and check output sanity...
5341         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5342         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5343         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5344
5345         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5346         // 0th HTLC:
5347         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
5348         // 1st HTLC:
5349         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
5350         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5351         let our_node_id = &nodes[1].node.get_our_node_id();
5352         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();
5353         // 2nd HTLC:
5354         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
5355         // 3rd HTLC:
5356         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
5357         // 4th HTLC:
5358         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5359         // 5th HTLC:
5360         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5361         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();
5362         // 6th HTLC:
5363         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5364         // 7th HTLC:
5365         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5366
5367         // 8th HTLC:
5368         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5369         // 9th HTLC:
5370         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();
5371         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
5372
5373         // 10th HTLC:
5374         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
5375         // 11th HTLC:
5376         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();
5377         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5378
5379         // Double-check that six of the new HTLC were added
5380         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5381         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5382         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5383         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5384
5385         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5386         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5387         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5388         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5389         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5390         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5391         check_added_monitors!(nodes[4], 0);
5392         expect_pending_htlcs_forwardable!(nodes[4]);
5393         check_added_monitors!(nodes[4], 1);
5394
5395         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5396         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5397         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5398         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5399         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5400         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5401
5402         // Fail 3rd below-dust and 7th above-dust HTLCs
5403         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5404         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5405         check_added_monitors!(nodes[5], 0);
5406         expect_pending_htlcs_forwardable!(nodes[5]);
5407         check_added_monitors!(nodes[5], 1);
5408
5409         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5410         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5411         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5412         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5413
5414         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5415
5416         expect_pending_htlcs_forwardable!(nodes[3]);
5417         check_added_monitors!(nodes[3], 1);
5418         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5419         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5420         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5421         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5422         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5423         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5424         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5425         if deliver_last_raa {
5426                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5427         } else {
5428                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5429         }
5430
5431         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5432         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5433         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5434         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5435         //
5436         // We now broadcast the latest commitment transaction, which *should* result in failures for
5437         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5438         // the non-broadcast above-dust HTLCs.
5439         //
5440         // Alternatively, we may broadcast the previous commitment transaction, which should only
5441         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5442         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5443
5444         if announce_latest {
5445                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5446         } else {
5447                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5448         }
5449         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5450         check_closed_broadcast!(nodes[2], true);
5451         expect_pending_htlcs_forwardable!(nodes[2]);
5452         check_added_monitors!(nodes[2], 3);
5453
5454         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5455         assert_eq!(cs_msgs.len(), 2);
5456         let mut a_done = false;
5457         for msg in cs_msgs {
5458                 match msg {
5459                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5460                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5461                                 // should be failed-backwards here.
5462                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5463                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5464                                         for htlc in &updates.update_fail_htlcs {
5465                                                 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 });
5466                                         }
5467                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5468                                         assert!(!a_done);
5469                                         a_done = true;
5470                                         &nodes[0]
5471                                 } else {
5472                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5473                                         for htlc in &updates.update_fail_htlcs {
5474                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5475                                         }
5476                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5477                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5478                                         &nodes[1]
5479                                 };
5480                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5481                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5482                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5483                                 if announce_latest {
5484                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5485                                         if *node_id == nodes[0].node.get_our_node_id() {
5486                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5487                                         }
5488                                 }
5489                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5490                         },
5491                         _ => panic!("Unexpected event"),
5492                 }
5493         }
5494
5495         let as_events = nodes[0].node.get_and_clear_pending_events();
5496         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5497         let mut as_failds = HashSet::new();
5498         for event in as_events.iter() {
5499                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5500                         assert!(as_failds.insert(*payment_hash));
5501                         if *payment_hash != payment_hash_2 {
5502                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5503                         } else {
5504                                 assert!(!rejected_by_dest);
5505                         }
5506                 } else { panic!("Unexpected event"); }
5507         }
5508         assert!(as_failds.contains(&payment_hash_1));
5509         assert!(as_failds.contains(&payment_hash_2));
5510         if announce_latest {
5511                 assert!(as_failds.contains(&payment_hash_3));
5512                 assert!(as_failds.contains(&payment_hash_5));
5513         }
5514         assert!(as_failds.contains(&payment_hash_6));
5515
5516         let bs_events = nodes[1].node.get_and_clear_pending_events();
5517         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5518         let mut bs_failds = HashSet::new();
5519         for event in bs_events.iter() {
5520                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5521                         assert!(bs_failds.insert(*payment_hash));
5522                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5523                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5524                         } else {
5525                                 assert!(!rejected_by_dest);
5526                         }
5527                 } else { panic!("Unexpected event"); }
5528         }
5529         assert!(bs_failds.contains(&payment_hash_1));
5530         assert!(bs_failds.contains(&payment_hash_2));
5531         if announce_latest {
5532                 assert!(bs_failds.contains(&payment_hash_4));
5533         }
5534         assert!(bs_failds.contains(&payment_hash_5));
5535
5536         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5537         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5538         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5539         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5540         // PaymentFailureNetworkUpdates.
5541         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5542         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5543         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5544         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5545         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5546                 match event {
5547                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5548                         _ => panic!("Unexpected event"),
5549                 }
5550         }
5551 }
5552
5553 #[test]
5554 fn test_fail_backwards_latest_remote_announce_a() {
5555         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5556 }
5557
5558 #[test]
5559 fn test_fail_backwards_latest_remote_announce_b() {
5560         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5561 }
5562
5563 #[test]
5564 fn test_fail_backwards_previous_remote_announce() {
5565         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5566         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5567         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5568 }
5569
5570 #[test]
5571 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5572         let chanmon_cfgs = create_chanmon_cfgs(2);
5573         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5574         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5575         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5576
5577         // Create some initial channels
5578         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5579
5580         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5581         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5582         assert_eq!(local_txn[0].input.len(), 1);
5583         check_spends!(local_txn[0], chan_1.3);
5584
5585         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5586         mine_transaction(&nodes[0], &local_txn[0]);
5587         check_closed_broadcast!(nodes[0], true);
5588         check_added_monitors!(nodes[0], 1);
5589
5590         let htlc_timeout = {
5591                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5592                 assert_eq!(node_txn[0].input.len(), 1);
5593                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5594                 check_spends!(node_txn[0], local_txn[0]);
5595                 node_txn[0].clone()
5596         };
5597
5598         mine_transaction(&nodes[0], &htlc_timeout);
5599         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5600         expect_payment_failed!(nodes[0], our_payment_hash, true);
5601
5602         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5603         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5604         assert_eq!(spend_txn.len(), 3);
5605         check_spends!(spend_txn[0], local_txn[0]);
5606         check_spends!(spend_txn[1], htlc_timeout);
5607         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5608 }
5609
5610 #[test]
5611 fn test_key_derivation_params() {
5612         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5613         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5614         // let us re-derive the channel key set to then derive a delayed_payment_key.
5615
5616         let chanmon_cfgs = create_chanmon_cfgs(3);
5617
5618         // We manually create the node configuration to backup the seed.
5619         let seed = [42; 32];
5620         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5621         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);
5622         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 };
5623         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5624         node_cfgs.remove(0);
5625         node_cfgs.insert(0, node);
5626
5627         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5628         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5629
5630         // Create some initial channels
5631         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5632         // for node 0
5633         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5634         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5635         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5636
5637         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5638         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5639         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5640         assert_eq!(local_txn_1[0].input.len(), 1);
5641         check_spends!(local_txn_1[0], chan_1.3);
5642
5643         // We check funding pubkey are unique
5644         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]));
5645         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]));
5646         if from_0_funding_key_0 == from_1_funding_key_0
5647             || from_0_funding_key_0 == from_1_funding_key_1
5648             || from_0_funding_key_1 == from_1_funding_key_0
5649             || from_0_funding_key_1 == from_1_funding_key_1 {
5650                 panic!("Funding pubkeys aren't unique");
5651         }
5652
5653         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5654         mine_transaction(&nodes[0], &local_txn_1[0]);
5655         check_closed_broadcast!(nodes[0], true);
5656         check_added_monitors!(nodes[0], 1);
5657
5658         let htlc_timeout = {
5659                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5660                 assert_eq!(node_txn[0].input.len(), 1);
5661                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5662                 check_spends!(node_txn[0], local_txn_1[0]);
5663                 node_txn[0].clone()
5664         };
5665
5666         mine_transaction(&nodes[0], &htlc_timeout);
5667         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5668         expect_payment_failed!(nodes[0], our_payment_hash, true);
5669
5670         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5671         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5672         let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5673         assert_eq!(spend_txn.len(), 3);
5674         check_spends!(spend_txn[0], local_txn_1[0]);
5675         check_spends!(spend_txn[1], htlc_timeout);
5676         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5677 }
5678
5679 #[test]
5680 fn test_static_output_closing_tx() {
5681         let chanmon_cfgs = create_chanmon_cfgs(2);
5682         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5683         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5684         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5685
5686         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5687
5688         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5689         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5690
5691         mine_transaction(&nodes[0], &closing_tx);
5692         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5693
5694         let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5695         assert_eq!(spend_txn.len(), 1);
5696         check_spends!(spend_txn[0], closing_tx);
5697
5698         mine_transaction(&nodes[1], &closing_tx);
5699         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5700
5701         let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5702         assert_eq!(spend_txn.len(), 1);
5703         check_spends!(spend_txn[0], closing_tx);
5704 }
5705
5706 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5707         let chanmon_cfgs = create_chanmon_cfgs(2);
5708         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5709         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5710         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5711         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5712
5713         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5714
5715         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5716         // present in B's local commitment transaction, but none of A's commitment transactions.
5717         assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5718         check_added_monitors!(nodes[1], 1);
5719
5720         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5721         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5722         let events = nodes[0].node.get_and_clear_pending_events();
5723         assert_eq!(events.len(), 1);
5724         match events[0] {
5725                 Event::PaymentSent { payment_preimage } => {
5726                         assert_eq!(payment_preimage, our_payment_preimage);
5727                 },
5728                 _ => panic!("Unexpected event"),
5729         }
5730
5731         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5732         check_added_monitors!(nodes[0], 1);
5733         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5734         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5735         check_added_monitors!(nodes[1], 1);
5736
5737         let starting_block = nodes[1].best_block_info();
5738         let mut block = Block {
5739                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5740                 txdata: vec![],
5741         };
5742         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5743                 connect_block(&nodes[1], &block);
5744                 block.header.prev_blockhash = block.block_hash();
5745         }
5746         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5747         check_closed_broadcast!(nodes[1], true);
5748         check_added_monitors!(nodes[1], 1);
5749 }
5750
5751 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5752         let chanmon_cfgs = create_chanmon_cfgs(2);
5753         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5754         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5755         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5756         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5757         let logger = test_utils::TestLogger::new();
5758
5759         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5760         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5761         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();
5762         nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5763         check_added_monitors!(nodes[0], 1);
5764
5765         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5766
5767         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5768         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5769         // to "time out" the HTLC.
5770
5771         let starting_block = nodes[1].best_block_info();
5772         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5773
5774         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5775                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5776                 header.prev_blockhash = header.block_hash();
5777         }
5778         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5779         check_closed_broadcast!(nodes[0], true);
5780         check_added_monitors!(nodes[0], 1);
5781 }
5782
5783 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5784         let chanmon_cfgs = create_chanmon_cfgs(3);
5785         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5786         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5787         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5788         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5789
5790         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5791         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5792         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5793         // actually revoked.
5794         let htlc_value = if use_dust { 50000 } else { 3000000 };
5795         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5796         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5797         expect_pending_htlcs_forwardable!(nodes[1]);
5798         check_added_monitors!(nodes[1], 1);
5799
5800         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5801         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5802         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5803         check_added_monitors!(nodes[0], 1);
5804         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5805         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5806         check_added_monitors!(nodes[1], 1);
5807         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5808         check_added_monitors!(nodes[1], 1);
5809         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5810
5811         if check_revoke_no_close {
5812                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5813                 check_added_monitors!(nodes[0], 1);
5814         }
5815
5816         let starting_block = nodes[1].best_block_info();
5817         let mut block = Block {
5818                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5819                 txdata: vec![],
5820         };
5821         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5822                 connect_block(&nodes[0], &block);
5823                 block.header.prev_blockhash = block.block_hash();
5824         }
5825         if !check_revoke_no_close {
5826                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5827                 check_closed_broadcast!(nodes[0], true);
5828                 check_added_monitors!(nodes[0], 1);
5829         } else {
5830                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5831         }
5832 }
5833
5834 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5835 // There are only a few cases to test here:
5836 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5837 //    broadcastable commitment transactions result in channel closure,
5838 //  * its included in an unrevoked-but-previous remote commitment transaction,
5839 //  * its included in the latest remote or local commitment transactions.
5840 // We test each of the three possible commitment transactions individually and use both dust and
5841 // non-dust HTLCs.
5842 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5843 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5844 // tested for at least one of the cases in other tests.
5845 #[test]
5846 fn htlc_claim_single_commitment_only_a() {
5847         do_htlc_claim_local_commitment_only(true);
5848         do_htlc_claim_local_commitment_only(false);
5849
5850         do_htlc_claim_current_remote_commitment_only(true);
5851         do_htlc_claim_current_remote_commitment_only(false);
5852 }
5853
5854 #[test]
5855 fn htlc_claim_single_commitment_only_b() {
5856         do_htlc_claim_previous_remote_commitment_only(true, false);
5857         do_htlc_claim_previous_remote_commitment_only(false, false);
5858         do_htlc_claim_previous_remote_commitment_only(true, true);
5859         do_htlc_claim_previous_remote_commitment_only(false, true);
5860 }
5861
5862 #[test]
5863 #[should_panic]
5864 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5865         let chanmon_cfgs = create_chanmon_cfgs(2);
5866         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5867         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5868         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5869         //Force duplicate channel ids
5870         for node in nodes.iter() {
5871                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5872         }
5873
5874         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5875         let channel_value_satoshis=10000;
5876         let push_msat=10001;
5877         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5878         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5879         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5880
5881         //Create a second channel with a channel_id collision
5882         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5883 }
5884
5885 #[test]
5886 fn bolt2_open_channel_sending_node_checks_part2() {
5887         let chanmon_cfgs = create_chanmon_cfgs(2);
5888         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5889         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5890         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5891
5892         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5893         let channel_value_satoshis=2^24;
5894         let push_msat=10001;
5895         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5896
5897         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5898         let channel_value_satoshis=10000;
5899         // Test when push_msat is equal to 1000 * funding_satoshis.
5900         let push_msat=1000*channel_value_satoshis+1;
5901         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5902
5903         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5904         let channel_value_satoshis=10000;
5905         let push_msat=10001;
5906         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
5907         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5908         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5909
5910         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5911         // 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
5912         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5913
5914         // 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.
5915         assert!(BREAKDOWN_TIMEOUT>0);
5916         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5917
5918         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5919         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5920         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5921
5922         // 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.
5923         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5924         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5925         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5926         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5927         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5928 }
5929
5930 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5931 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5932 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5933 // is no longer affordable once it's freed.
5934 #[test]
5935 fn test_fail_holding_cell_htlc_upon_free() {
5936         let chanmon_cfgs = create_chanmon_cfgs(2);
5937         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5938         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5939         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5940         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5941         let logger = test_utils::TestLogger::new();
5942
5943         // First nodes[0] generates an update_fee, setting the channel's
5944         // pending_update_fee.
5945         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
5946         check_added_monitors!(nodes[0], 1);
5947
5948         let events = nodes[0].node.get_and_clear_pending_msg_events();
5949         assert_eq!(events.len(), 1);
5950         let (update_msg, commitment_signed) = match events[0] {
5951                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5952                         (update_fee.as_ref(), commitment_signed)
5953                 },
5954                 _ => panic!("Unexpected event"),
5955         };
5956
5957         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5958
5959         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5960         let channel_reserve = chan_stat.channel_reserve_msat;
5961         let feerate = get_feerate!(nodes[0], chan.2);
5962
5963         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5964         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5965         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5966         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5967         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();
5968
5969         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5970         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5971         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5972         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5973
5974         // Flush the pending fee update.
5975         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5976         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5977         check_added_monitors!(nodes[1], 1);
5978         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5979         check_added_monitors!(nodes[0], 1);
5980
5981         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5982         // HTLC, but now that the fee has been raised the payment will now fail, causing
5983         // us to surface its failure to the user.
5984         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5985         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5986         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
5987         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);
5988         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5989
5990         // Check that the payment failed to be sent out.
5991         let events = nodes[0].node.get_and_clear_pending_events();
5992         assert_eq!(events.len(), 1);
5993         match &events[0] {
5994                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
5995                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5996                         assert_eq!(*rejected_by_dest, false);
5997                         assert_eq!(*error_code, None);
5998                         assert_eq!(*error_data, None);
5999                 },
6000                 _ => panic!("Unexpected event"),
6001         }
6002 }
6003
6004 // Test that if multiple HTLCs are released from the holding cell and one is
6005 // valid but the other is no longer valid upon release, the valid HTLC can be
6006 // successfully completed while the other one fails as expected.
6007 #[test]
6008 fn test_free_and_fail_holding_cell_htlcs() {
6009         let chanmon_cfgs = create_chanmon_cfgs(2);
6010         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6011         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6012         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6013         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6014         let logger = test_utils::TestLogger::new();
6015
6016         // First nodes[0] generates an update_fee, setting the channel's
6017         // pending_update_fee.
6018         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6019         check_added_monitors!(nodes[0], 1);
6020
6021         let events = nodes[0].node.get_and_clear_pending_msg_events();
6022         assert_eq!(events.len(), 1);
6023         let (update_msg, commitment_signed) = match events[0] {
6024                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6025                         (update_fee.as_ref(), commitment_signed)
6026                 },
6027                 _ => panic!("Unexpected event"),
6028         };
6029
6030         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6031
6032         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6033         let channel_reserve = chan_stat.channel_reserve_msat;
6034         let feerate = get_feerate!(nodes[0], chan.2);
6035
6036         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6037         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6038         let amt_1 = 20000;
6039         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6040         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6041         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6042         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();
6043         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();
6044
6045         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6046         nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6047         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6048         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6049         nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6050         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6051         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6052
6053         // Flush the pending fee update.
6054         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6055         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6056         check_added_monitors!(nodes[1], 1);
6057         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6058         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6059         check_added_monitors!(nodes[0], 2);
6060
6061         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6062         // but now that the fee has been raised the second payment will now fail, causing us
6063         // to surface its failure to the user. The first payment should succeed.
6064         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6065         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6066         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6067         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);
6068         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6069
6070         // Check that the second payment failed to be sent out.
6071         let events = nodes[0].node.get_and_clear_pending_events();
6072         assert_eq!(events.len(), 1);
6073         match &events[0] {
6074                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6075                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6076                         assert_eq!(*rejected_by_dest, false);
6077                         assert_eq!(*error_code, None);
6078                         assert_eq!(*error_data, None);
6079                 },
6080                 _ => panic!("Unexpected event"),
6081         }
6082
6083         // Complete the first payment and the RAA from the fee update.
6084         let (payment_event, send_raa_event) = {
6085                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6086                 assert_eq!(msgs.len(), 2);
6087                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6088         };
6089         let raa = match send_raa_event {
6090                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6091                 _ => panic!("Unexpected event"),
6092         };
6093         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6094         check_added_monitors!(nodes[1], 1);
6095         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6096         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6097         let events = nodes[1].node.get_and_clear_pending_events();
6098         assert_eq!(events.len(), 1);
6099         match events[0] {
6100                 Event::PendingHTLCsForwardable { .. } => {},
6101                 _ => panic!("Unexpected event"),
6102         }
6103         nodes[1].node.process_pending_htlc_forwards();
6104         let events = nodes[1].node.get_and_clear_pending_events();
6105         assert_eq!(events.len(), 1);
6106         match events[0] {
6107                 Event::PaymentReceived { .. } => {},
6108                 _ => panic!("Unexpected event"),
6109         }
6110         nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6111         check_added_monitors!(nodes[1], 1);
6112         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6113         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6114         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6115         let events = nodes[0].node.get_and_clear_pending_events();
6116         assert_eq!(events.len(), 1);
6117         match events[0] {
6118                 Event::PaymentSent { ref payment_preimage } => {
6119                         assert_eq!(*payment_preimage, payment_preimage_1);
6120                 }
6121                 _ => panic!("Unexpected event"),
6122         }
6123 }
6124
6125 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6126 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6127 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6128 // once it's freed.
6129 #[test]
6130 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6131         let chanmon_cfgs = create_chanmon_cfgs(3);
6132         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6133         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6134         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6135         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6136         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6137         let logger = test_utils::TestLogger::new();
6138
6139         // First nodes[1] generates an update_fee, setting the channel's
6140         // pending_update_fee.
6141         nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6142         check_added_monitors!(nodes[1], 1);
6143
6144         let events = nodes[1].node.get_and_clear_pending_msg_events();
6145         assert_eq!(events.len(), 1);
6146         let (update_msg, commitment_signed) = match events[0] {
6147                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6148                         (update_fee.as_ref(), commitment_signed)
6149                 },
6150                 _ => panic!("Unexpected event"),
6151         };
6152
6153         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6154
6155         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6156         let channel_reserve = chan_stat.channel_reserve_msat;
6157         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6158
6159         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6160         let feemsat = 239;
6161         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6162         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6163         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6164         let payment_event = {
6165                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6166                 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();
6167                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6168                 check_added_monitors!(nodes[0], 1);
6169
6170                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6171                 assert_eq!(events.len(), 1);
6172
6173                 SendEvent::from_event(events.remove(0))
6174         };
6175         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6176         check_added_monitors!(nodes[1], 0);
6177         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6178         expect_pending_htlcs_forwardable!(nodes[1]);
6179
6180         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6181         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6182
6183         // Flush the pending fee update.
6184         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6185         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6186         check_added_monitors!(nodes[2], 1);
6187         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6188         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6189         check_added_monitors!(nodes[1], 2);
6190
6191         // A final RAA message is generated to finalize the fee update.
6192         let events = nodes[1].node.get_and_clear_pending_msg_events();
6193         assert_eq!(events.len(), 1);
6194
6195         let raa_msg = match &events[0] {
6196                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6197                         msg.clone()
6198                 },
6199                 _ => panic!("Unexpected event"),
6200         };
6201
6202         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6203         check_added_monitors!(nodes[2], 1);
6204         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6205
6206         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6207         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6208         assert_eq!(process_htlc_forwards_event.len(), 1);
6209         match &process_htlc_forwards_event[0] {
6210                 &Event::PendingHTLCsForwardable { .. } => {},
6211                 _ => panic!("Unexpected event"),
6212         }
6213
6214         // In response, we call ChannelManager's process_pending_htlc_forwards
6215         nodes[1].node.process_pending_htlc_forwards();
6216         check_added_monitors!(nodes[1], 1);
6217
6218         // This causes the HTLC to be failed backwards.
6219         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6220         assert_eq!(fail_event.len(), 1);
6221         let (fail_msg, commitment_signed) = match &fail_event[0] {
6222                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6223                         assert_eq!(updates.update_add_htlcs.len(), 0);
6224                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6225                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6226                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6227                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6228                 },
6229                 _ => panic!("Unexpected event"),
6230         };
6231
6232         // Pass the failure messages back to nodes[0].
6233         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6234         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6235
6236         // Complete the HTLC failure+removal process.
6237         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6238         check_added_monitors!(nodes[0], 1);
6239         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6240         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6241         check_added_monitors!(nodes[1], 2);
6242         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6243         assert_eq!(final_raa_event.len(), 1);
6244         let raa = match &final_raa_event[0] {
6245                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6246                 _ => panic!("Unexpected event"),
6247         };
6248         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6249         let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6250         assert_eq!(fail_msg_event.len(), 1);
6251         match &fail_msg_event[0] {
6252                 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6253                 _ => panic!("Unexpected event"),
6254         }
6255         let failure_event = nodes[0].node.get_and_clear_pending_events();
6256         assert_eq!(failure_event.len(), 1);
6257         match &failure_event[0] {
6258                 &Event::PaymentFailed { rejected_by_dest, .. } => {
6259                         assert!(!rejected_by_dest);
6260                 },
6261                 _ => panic!("Unexpected event"),
6262         }
6263         check_added_monitors!(nodes[0], 1);
6264 }
6265
6266 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6267 // 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.
6268 //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.
6269
6270 #[test]
6271 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6272         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6273         let chanmon_cfgs = create_chanmon_cfgs(2);
6274         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6275         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6276         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6277         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6278
6279         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6280         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6281         let logger = test_utils::TestLogger::new();
6282         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();
6283         route.paths[0][0].fee_msat = 100;
6284
6285         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6286                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6287         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6288         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6289 }
6290
6291 #[test]
6292 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6293         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6294         let chanmon_cfgs = create_chanmon_cfgs(2);
6295         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6296         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6297         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6298         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6299         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6300
6301         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6302         let logger = test_utils::TestLogger::new();
6303         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();
6304         route.paths[0][0].fee_msat = 0;
6305         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6306                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6307
6308         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6309         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6310 }
6311
6312 #[test]
6313 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6314         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6315         let chanmon_cfgs = create_chanmon_cfgs(2);
6316         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6317         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6318         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6319         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6320
6321         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6322         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6323         let logger = test_utils::TestLogger::new();
6324         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();
6325         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6326         check_added_monitors!(nodes[0], 1);
6327         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6328         updates.update_add_htlcs[0].amount_msat = 0;
6329
6330         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6331         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6332         check_closed_broadcast!(nodes[1], true).unwrap();
6333         check_added_monitors!(nodes[1], 1);
6334 }
6335
6336 #[test]
6337 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6338         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6339         //It is enforced when constructing a route.
6340         let chanmon_cfgs = create_chanmon_cfgs(2);
6341         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6342         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6343         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6344         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6345         let logger = test_utils::TestLogger::new();
6346
6347         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6348
6349         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6350         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();
6351         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6352                 assert_eq!(err, &"Channel CLTV overflowed?"));
6353 }
6354
6355 #[test]
6356 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6357         //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.
6358         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6359         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6360         let chanmon_cfgs = create_chanmon_cfgs(2);
6361         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6362         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6363         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6364         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6365         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6366
6367         let logger = test_utils::TestLogger::new();
6368         for i in 0..max_accepted_htlcs {
6369                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6370                 let payment_event = {
6371                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6372                         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();
6373                         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6374                         check_added_monitors!(nodes[0], 1);
6375
6376                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6377                         assert_eq!(events.len(), 1);
6378                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6379                                 assert_eq!(htlcs[0].htlc_id, i);
6380                         } else {
6381                                 assert!(false);
6382                         }
6383                         SendEvent::from_event(events.remove(0))
6384                 };
6385                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6386                 check_added_monitors!(nodes[1], 0);
6387                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6388
6389                 expect_pending_htlcs_forwardable!(nodes[1]);
6390                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6391         }
6392         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6393         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6394         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();
6395         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6396                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6397
6398         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6399         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6400 }
6401
6402 #[test]
6403 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6404         //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.
6405         let chanmon_cfgs = create_chanmon_cfgs(2);
6406         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6407         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6408         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6409         let channel_value = 100000;
6410         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6411         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6412
6413         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6414
6415         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6416         // Manually create a route over our max in flight (which our router normally automatically
6417         // limits us to.
6418         let route = Route { paths: vec![vec![RouteHop {
6419            pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6420            short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6421            fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6422         }]] };
6423         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6424                 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)));
6425
6426         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6427         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);
6428
6429         send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6430 }
6431
6432 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6433 #[test]
6434 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6435         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6436         let chanmon_cfgs = create_chanmon_cfgs(2);
6437         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6438         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6439         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6440         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6441         let htlc_minimum_msat: u64;
6442         {
6443                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6444                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6445                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6446         }
6447
6448         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6449         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6450         let logger = test_utils::TestLogger::new();
6451         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();
6452         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6453         check_added_monitors!(nodes[0], 1);
6454         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6455         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6456         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6457         assert!(nodes[1].node.list_channels().is_empty());
6458         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6459         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()));
6460         check_added_monitors!(nodes[1], 1);
6461 }
6462
6463 #[test]
6464 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6465         //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
6466         let chanmon_cfgs = create_chanmon_cfgs(2);
6467         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6468         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6469         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6470         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6471         let logger = test_utils::TestLogger::new();
6472
6473         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6474         let channel_reserve = chan_stat.channel_reserve_msat;
6475         let feerate = get_feerate!(nodes[0], chan.2);
6476         // The 2* and +1 are for the fee spike reserve.
6477         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6478
6479         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6480         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6481         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6482         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();
6483         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6484         check_added_monitors!(nodes[0], 1);
6485         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6486
6487         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6488         // at this time channel-initiatee receivers are not required to enforce that senders
6489         // respect the fee_spike_reserve.
6490         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6491         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6492
6493         assert!(nodes[1].node.list_channels().is_empty());
6494         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6495         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6496         check_added_monitors!(nodes[1], 1);
6497 }
6498
6499 #[test]
6500 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6501         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6502         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6503         let chanmon_cfgs = create_chanmon_cfgs(2);
6504         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6505         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6506         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6507         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6508         let logger = test_utils::TestLogger::new();
6509
6510         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6511         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6512
6513         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6514         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();
6515
6516         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6517         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6518         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6519         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6520
6521         let mut msg = msgs::UpdateAddHTLC {
6522                 channel_id: chan.2,
6523                 htlc_id: 0,
6524                 amount_msat: 1000,
6525                 payment_hash: our_payment_hash,
6526                 cltv_expiry: htlc_cltv,
6527                 onion_routing_packet: onion_packet.clone(),
6528         };
6529
6530         for i in 0..super::channel::OUR_MAX_HTLCS {
6531                 msg.htlc_id = i as u64;
6532                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6533         }
6534         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6535         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6536
6537         assert!(nodes[1].node.list_channels().is_empty());
6538         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6539         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6540         check_added_monitors!(nodes[1], 1);
6541 }
6542
6543 #[test]
6544 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6545         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6546         let chanmon_cfgs = create_chanmon_cfgs(2);
6547         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6548         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6549         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6550         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6551         let logger = test_utils::TestLogger::new();
6552
6553         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6554         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6555         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();
6556         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6557         check_added_monitors!(nodes[0], 1);
6558         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6559         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6560         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6561
6562         assert!(nodes[1].node.list_channels().is_empty());
6563         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6564         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6565         check_added_monitors!(nodes[1], 1);
6566 }
6567
6568 #[test]
6569 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6570         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6571         let chanmon_cfgs = create_chanmon_cfgs(2);
6572         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6573         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6574         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6575         let logger = test_utils::TestLogger::new();
6576
6577         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6578         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6579         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6580         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();
6581         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6582         check_added_monitors!(nodes[0], 1);
6583         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6584         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6585         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6586
6587         assert!(nodes[1].node.list_channels().is_empty());
6588         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6589         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6590         check_added_monitors!(nodes[1], 1);
6591 }
6592
6593 #[test]
6594 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6595         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6596         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6597         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6598         let chanmon_cfgs = create_chanmon_cfgs(2);
6599         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6600         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6601         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6602         let logger = test_utils::TestLogger::new();
6603
6604         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6605         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6606         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6607         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();
6608         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6609         check_added_monitors!(nodes[0], 1);
6610         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6611         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6612
6613         //Disconnect and Reconnect
6614         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6615         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6616         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6617         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6618         assert_eq!(reestablish_1.len(), 1);
6619         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6620         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6621         assert_eq!(reestablish_2.len(), 1);
6622         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6623         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6624         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6625         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6626
6627         //Resend HTLC
6628         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6629         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6630         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6631         check_added_monitors!(nodes[1], 1);
6632         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6633
6634         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6635
6636         assert!(nodes[1].node.list_channels().is_empty());
6637         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6638         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6639         check_added_monitors!(nodes[1], 1);
6640 }
6641
6642 #[test]
6643 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6644         //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.
6645
6646         let chanmon_cfgs = create_chanmon_cfgs(2);
6647         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6648         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6649         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6650         let logger = test_utils::TestLogger::new();
6651         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6652         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6653         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6654         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();
6655         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6656
6657         check_added_monitors!(nodes[0], 1);
6658         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6659         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6660
6661         let update_msg = msgs::UpdateFulfillHTLC{
6662                 channel_id: chan.2,
6663                 htlc_id: 0,
6664                 payment_preimage: our_payment_preimage,
6665         };
6666
6667         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6668
6669         assert!(nodes[0].node.list_channels().is_empty());
6670         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6671         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()));
6672         check_added_monitors!(nodes[0], 1);
6673 }
6674
6675 #[test]
6676 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6677         //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.
6678
6679         let chanmon_cfgs = create_chanmon_cfgs(2);
6680         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6681         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6682         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6683         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6684         let logger = test_utils::TestLogger::new();
6685
6686         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6687         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6688         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();
6689         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6690         check_added_monitors!(nodes[0], 1);
6691         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6692         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6693
6694         let update_msg = msgs::UpdateFailHTLC{
6695                 channel_id: chan.2,
6696                 htlc_id: 0,
6697                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6698         };
6699
6700         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6701
6702         assert!(nodes[0].node.list_channels().is_empty());
6703         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6704         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()));
6705         check_added_monitors!(nodes[0], 1);
6706 }
6707
6708 #[test]
6709 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6710         //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.
6711
6712         let chanmon_cfgs = create_chanmon_cfgs(2);
6713         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6714         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6715         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6716         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6717         let logger = test_utils::TestLogger::new();
6718
6719         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6720         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6721         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();
6722         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6723         check_added_monitors!(nodes[0], 1);
6724         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6725         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6726         let update_msg = msgs::UpdateFailMalformedHTLC{
6727                 channel_id: chan.2,
6728                 htlc_id: 0,
6729                 sha256_of_onion: [1; 32],
6730                 failure_code: 0x8000,
6731         };
6732
6733         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6734
6735         assert!(nodes[0].node.list_channels().is_empty());
6736         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6737         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()));
6738         check_added_monitors!(nodes[0], 1);
6739 }
6740
6741 #[test]
6742 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6743         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6744
6745         let chanmon_cfgs = create_chanmon_cfgs(2);
6746         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6747         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6748         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6749         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6750
6751         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6752
6753         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6754         check_added_monitors!(nodes[1], 1);
6755
6756         let events = nodes[1].node.get_and_clear_pending_msg_events();
6757         assert_eq!(events.len(), 1);
6758         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6759                 match events[0] {
6760                         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, .. } } => {
6761                                 assert!(update_add_htlcs.is_empty());
6762                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6763                                 assert!(update_fail_htlcs.is_empty());
6764                                 assert!(update_fail_malformed_htlcs.is_empty());
6765                                 assert!(update_fee.is_none());
6766                                 update_fulfill_htlcs[0].clone()
6767                         },
6768                         _ => panic!("Unexpected event"),
6769                 }
6770         };
6771
6772         update_fulfill_msg.htlc_id = 1;
6773
6774         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6775
6776         assert!(nodes[0].node.list_channels().is_empty());
6777         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6778         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6779         check_added_monitors!(nodes[0], 1);
6780 }
6781
6782 #[test]
6783 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6784         //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.
6785
6786         let chanmon_cfgs = create_chanmon_cfgs(2);
6787         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6788         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6789         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6790         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6791
6792         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6793
6794         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6795         check_added_monitors!(nodes[1], 1);
6796
6797         let events = nodes[1].node.get_and_clear_pending_msg_events();
6798         assert_eq!(events.len(), 1);
6799         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6800                 match events[0] {
6801                         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, .. } } => {
6802                                 assert!(update_add_htlcs.is_empty());
6803                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6804                                 assert!(update_fail_htlcs.is_empty());
6805                                 assert!(update_fail_malformed_htlcs.is_empty());
6806                                 assert!(update_fee.is_none());
6807                                 update_fulfill_htlcs[0].clone()
6808                         },
6809                         _ => panic!("Unexpected event"),
6810                 }
6811         };
6812
6813         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6814
6815         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6816
6817         assert!(nodes[0].node.list_channels().is_empty());
6818         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6819         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6820         check_added_monitors!(nodes[0], 1);
6821 }
6822
6823 #[test]
6824 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6825         //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.
6826
6827         let chanmon_cfgs = create_chanmon_cfgs(2);
6828         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6829         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6830         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6831         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6832         let logger = test_utils::TestLogger::new();
6833
6834         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6835         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6836         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();
6837         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6838         check_added_monitors!(nodes[0], 1);
6839
6840         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6841         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6842
6843         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6844         check_added_monitors!(nodes[1], 0);
6845         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6846
6847         let events = nodes[1].node.get_and_clear_pending_msg_events();
6848
6849         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6850                 match events[0] {
6851                         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, .. } } => {
6852                                 assert!(update_add_htlcs.is_empty());
6853                                 assert!(update_fulfill_htlcs.is_empty());
6854                                 assert!(update_fail_htlcs.is_empty());
6855                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6856                                 assert!(update_fee.is_none());
6857                                 update_fail_malformed_htlcs[0].clone()
6858                         },
6859                         _ => panic!("Unexpected event"),
6860                 }
6861         };
6862         update_msg.failure_code &= !0x8000;
6863         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6864
6865         assert!(nodes[0].node.list_channels().is_empty());
6866         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6867         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6868         check_added_monitors!(nodes[0], 1);
6869 }
6870
6871 #[test]
6872 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6873         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6874         //    * 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.
6875
6876         let chanmon_cfgs = create_chanmon_cfgs(3);
6877         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6878         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6879         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6880         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6881         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6882         let logger = test_utils::TestLogger::new();
6883
6884         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6885
6886         //First hop
6887         let mut payment_event = {
6888                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6889                 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();
6890                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6891                 check_added_monitors!(nodes[0], 1);
6892                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6893                 assert_eq!(events.len(), 1);
6894                 SendEvent::from_event(events.remove(0))
6895         };
6896         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6897         check_added_monitors!(nodes[1], 0);
6898         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6899         expect_pending_htlcs_forwardable!(nodes[1]);
6900         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6901         assert_eq!(events_2.len(), 1);
6902         check_added_monitors!(nodes[1], 1);
6903         payment_event = SendEvent::from_event(events_2.remove(0));
6904         assert_eq!(payment_event.msgs.len(), 1);
6905
6906         //Second Hop
6907         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6908         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6909         check_added_monitors!(nodes[2], 0);
6910         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6911
6912         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6913         assert_eq!(events_3.len(), 1);
6914         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6915                 match events_3[0] {
6916                         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 } } => {
6917                                 assert!(update_add_htlcs.is_empty());
6918                                 assert!(update_fulfill_htlcs.is_empty());
6919                                 assert!(update_fail_htlcs.is_empty());
6920                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6921                                 assert!(update_fee.is_none());
6922                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6923                         },
6924                         _ => panic!("Unexpected event"),
6925                 }
6926         };
6927
6928         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6929
6930         check_added_monitors!(nodes[1], 0);
6931         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6932         expect_pending_htlcs_forwardable!(nodes[1]);
6933         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6934         assert_eq!(events_4.len(), 1);
6935
6936         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6937         match events_4[0] {
6938                 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, .. } } => {
6939                         assert!(update_add_htlcs.is_empty());
6940                         assert!(update_fulfill_htlcs.is_empty());
6941                         assert_eq!(update_fail_htlcs.len(), 1);
6942                         assert!(update_fail_malformed_htlcs.is_empty());
6943                         assert!(update_fee.is_none());
6944                 },
6945                 _ => panic!("Unexpected event"),
6946         };
6947
6948         check_added_monitors!(nodes[1], 1);
6949 }
6950
6951 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6952         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6953         // 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
6954         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6955
6956         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6957         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6958         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6959         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6960         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6961         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6962
6963         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6964
6965         // We route 2 dust-HTLCs between A and B
6966         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6967         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6968         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6969
6970         // Cache one local commitment tx as previous
6971         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6972
6973         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6974         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
6975         check_added_monitors!(nodes[1], 0);
6976         expect_pending_htlcs_forwardable!(nodes[1]);
6977         check_added_monitors!(nodes[1], 1);
6978
6979         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6980         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6981         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6982         check_added_monitors!(nodes[0], 1);
6983
6984         // Cache one local commitment tx as lastest
6985         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6986
6987         let events = nodes[0].node.get_and_clear_pending_msg_events();
6988         match events[0] {
6989                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6990                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6991                 },
6992                 _ => panic!("Unexpected event"),
6993         }
6994         match events[1] {
6995                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6996                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6997                 },
6998                 _ => panic!("Unexpected event"),
6999         }
7000
7001         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7002         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7003         if announce_latest {
7004                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7005         } else {
7006                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7007         }
7008
7009         check_closed_broadcast!(nodes[0], true);
7010         check_added_monitors!(nodes[0], 1);
7011
7012         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7013         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7014         let events = nodes[0].node.get_and_clear_pending_events();
7015         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7016         assert_eq!(events.len(), 2);
7017         let mut first_failed = false;
7018         for event in events {
7019                 match event {
7020                         Event::PaymentFailed { payment_hash, .. } => {
7021                                 if payment_hash == payment_hash_1 {
7022                                         assert!(!first_failed);
7023                                         first_failed = true;
7024                                 } else {
7025                                         assert_eq!(payment_hash, payment_hash_2);
7026                                 }
7027                         }
7028                         _ => panic!("Unexpected event"),
7029                 }
7030         }
7031 }
7032
7033 #[test]
7034 fn test_failure_delay_dust_htlc_local_commitment() {
7035         do_test_failure_delay_dust_htlc_local_commitment(true);
7036         do_test_failure_delay_dust_htlc_local_commitment(false);
7037 }
7038
7039 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7040         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7041         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7042         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7043         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7044         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7045         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7046
7047         let chanmon_cfgs = create_chanmon_cfgs(3);
7048         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7049         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7050         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7051         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7052
7053         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7054
7055         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7056         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7057
7058         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7059         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7060
7061         // We revoked bs_commitment_tx
7062         if revoked {
7063                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7064                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7065         }
7066
7067         let mut timeout_tx = Vec::new();
7068         if local {
7069                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7070                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7071                 check_closed_broadcast!(nodes[0], true);
7072                 check_added_monitors!(nodes[0], 1);
7073                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7074                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7075                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7076                 expect_payment_failed!(nodes[0], dust_hash, true);
7077                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7078                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7079                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7080                 mine_transaction(&nodes[0], &timeout_tx[0]);
7081                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7082                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7083         } else {
7084                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7085                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7086                 check_closed_broadcast!(nodes[0], true);
7087                 check_added_monitors!(nodes[0], 1);
7088                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7089                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7090                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7091                 if !revoked {
7092                         expect_payment_failed!(nodes[0], dust_hash, true);
7093                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7094                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7095                         mine_transaction(&nodes[0], &timeout_tx[0]);
7096                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7097                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7098                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7099                 } else {
7100                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7101                         // commitment tx
7102                         let events = nodes[0].node.get_and_clear_pending_events();
7103                         assert_eq!(events.len(), 2);
7104                         let first;
7105                         match events[0] {
7106                                 Event::PaymentFailed { payment_hash, .. } => {
7107                                         if payment_hash == dust_hash { first = true; }
7108                                         else { first = false; }
7109                                 },
7110                                 _ => panic!("Unexpected event"),
7111                         }
7112                         match events[1] {
7113                                 Event::PaymentFailed { payment_hash, .. } => {
7114                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7115                                         else { assert_eq!(payment_hash, dust_hash); }
7116                                 },
7117                                 _ => panic!("Unexpected event"),
7118                         }
7119                 }
7120         }
7121 }
7122
7123 #[test]
7124 fn test_sweep_outbound_htlc_failure_update() {
7125         do_test_sweep_outbound_htlc_failure_update(false, true);
7126         do_test_sweep_outbound_htlc_failure_update(false, false);
7127         do_test_sweep_outbound_htlc_failure_update(true, false);
7128 }
7129
7130 #[test]
7131 fn test_upfront_shutdown_script() {
7132         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7133         // enforce it at shutdown message
7134
7135         let mut config = UserConfig::default();
7136         config.channel_options.announced_channel = true;
7137         config.peer_channel_config_limits.force_announced_channel_preference = false;
7138         config.channel_options.commit_upfront_shutdown_pubkey = false;
7139         let user_cfgs = [None, Some(config), None];
7140         let chanmon_cfgs = create_chanmon_cfgs(3);
7141         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7142         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7143         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7144
7145         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7146         let flags = InitFeatures::known();
7147         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7148         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7149         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7150         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7151         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
7152         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7153     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()));
7154         check_added_monitors!(nodes[2], 1);
7155
7156         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7157         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7158         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7159         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7160         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7161         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7162         let events = nodes[2].node.get_and_clear_pending_msg_events();
7163         assert_eq!(events.len(), 1);
7164         match events[0] {
7165                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7166                 _ => panic!("Unexpected event"),
7167         }
7168
7169         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7170         let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7171         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7172         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7173         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7174         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7175         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
7176         let events = nodes[1].node.get_and_clear_pending_msg_events();
7177         assert_eq!(events.len(), 1);
7178         match events[0] {
7179                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7180                 _ => panic!("Unexpected event"),
7181         }
7182
7183         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7184         // channel smoothly, opt-out is from channel initiator here
7185         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7186         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7187         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7188         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7189         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7190         let events = nodes[0].node.get_and_clear_pending_msg_events();
7191         assert_eq!(events.len(), 1);
7192         match events[0] {
7193                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7194                 _ => panic!("Unexpected event"),
7195         }
7196
7197         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7198         //// channel smoothly
7199         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7200         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7201         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7202         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7203         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7204         let events = nodes[0].node.get_and_clear_pending_msg_events();
7205         assert_eq!(events.len(), 2);
7206         match events[0] {
7207                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7208                 _ => panic!("Unexpected event"),
7209         }
7210         match events[1] {
7211                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7212                 _ => panic!("Unexpected event"),
7213         }
7214 }
7215
7216 #[test]
7217 fn test_upfront_shutdown_script_unsupport_segwit() {
7218         // We test that channel is closed early
7219         // if a segwit program is passed as upfront shutdown script,
7220         // but the peer does not support segwit.
7221         let chanmon_cfgs = create_chanmon_cfgs(2);
7222         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7223         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7224         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7225
7226         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
7227
7228         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7229         open_channel.shutdown_scriptpubkey = Present(Builder::new().push_int(16)
7230                 .push_slice(&[0, 0])
7231                 .into_script());
7232
7233         let features = InitFeatures::known().clear_shutdown_anysegwit();
7234         nodes[0].node.handle_open_channel(&nodes[0].node.get_our_node_id(), features, &open_channel);
7235
7236         let events = nodes[0].node.get_and_clear_pending_msg_events();
7237         assert_eq!(events.len(), 1);
7238         match events[0] {
7239                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7240                         assert_eq!(node_id, nodes[0].node.get_our_node_id());
7241                         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));
7242                 },
7243                 _ => panic!("Unexpected event"),
7244         }
7245 }
7246
7247 #[test]
7248 fn test_shutdown_script_any_segwit_allowed() {
7249         let mut config = UserConfig::default();
7250         config.channel_options.announced_channel = true;
7251         config.peer_channel_config_limits.force_announced_channel_preference = false;
7252         config.channel_options.commit_upfront_shutdown_pubkey = false;
7253         let user_cfgs = [None, Some(config), None];
7254         let chanmon_cfgs = create_chanmon_cfgs(3);
7255         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7256         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7257         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7258
7259         //// We test if the remote peer accepts opt_shutdown_anysegwit, a witness program can be used on shutdown
7260         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7261         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7262         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7263         node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7264                 .push_slice(&[0, 0])
7265                 .into_script();
7266         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7267         let events = nodes[0].node.get_and_clear_pending_msg_events();
7268         assert_eq!(events.len(), 2);
7269         match events[0] {
7270                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7271                 _ => panic!("Unexpected event"),
7272         }
7273         match events[1] {
7274                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7275                 _ => panic!("Unexpected event"),
7276         }
7277 }
7278
7279 #[test]
7280 fn test_shutdown_script_any_segwit_not_allowed() {
7281         let mut config = UserConfig::default();
7282         config.channel_options.announced_channel = true;
7283         config.peer_channel_config_limits.force_announced_channel_preference = false;
7284         config.channel_options.commit_upfront_shutdown_pubkey = false;
7285         let user_cfgs = [None, Some(config), None];
7286         let chanmon_cfgs = create_chanmon_cfgs(3);
7287         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7288         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7289         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7290
7291         //// We test that if the remote peer does not accept opt_shutdown_anysegwit, the witness program cannot be used on shutdown
7292         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7293         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7294         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7295         // Make an any segwit version script
7296         node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7297                 .push_slice(&[0, 0])
7298                 .into_script();
7299         let flags_no = InitFeatures::known().clear_shutdown_anysegwit();
7300         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &flags_no, &node_0_shutdown);
7301         let events = nodes[0].node.get_and_clear_pending_msg_events();
7302         assert_eq!(events.len(), 2);
7303         match events[1] {
7304                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7305                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7306                         assert_eq!(msg.data, "Got a nonstandard scriptpubkey (60020000) from remote peer".to_owned())
7307                 },
7308                 _ => panic!("Unexpected event"),
7309         }
7310         check_added_monitors!(nodes[0], 1);
7311 }
7312
7313 #[test]
7314 fn test_shutdown_script_segwit_but_not_anysegwit() {
7315         let mut config = UserConfig::default();
7316         config.channel_options.announced_channel = true;
7317         config.peer_channel_config_limits.force_announced_channel_preference = false;
7318         config.channel_options.commit_upfront_shutdown_pubkey = false;
7319         let user_cfgs = [None, Some(config), None];
7320         let chanmon_cfgs = create_chanmon_cfgs(3);
7321         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7322         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7323         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7324
7325         //// We test that if shutdown any segwit is supported and we send a witness script with 0 version, this is not accepted
7326         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7327         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7328         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7329         // Make a segwit script that is not a valid as any segwit
7330         node_0_shutdown.scriptpubkey = Builder::new().push_int(0)
7331                 .push_slice(&[0, 0])
7332                 .into_script();
7333         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7334         let events = nodes[0].node.get_and_clear_pending_msg_events();
7335         assert_eq!(events.len(), 2);
7336         match events[1] {
7337                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7338                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7339                         assert_eq!(msg.data, "Got a nonstandard scriptpubkey (00020000) from remote peer".to_owned())
7340                 },
7341                 _ => panic!("Unexpected event"),
7342         }
7343         check_added_monitors!(nodes[0], 1);
7344 }
7345
7346 #[test]
7347 fn test_user_configurable_csv_delay() {
7348         // We test our channel constructors yield errors when we pass them absurd csv delay
7349
7350         let mut low_our_to_self_config = UserConfig::default();
7351         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7352         let mut high_their_to_self_config = UserConfig::default();
7353         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7354         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7355         let chanmon_cfgs = create_chanmon_cfgs(2);
7356         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7357         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7358         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7359
7360         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7361         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) {
7362                 match error {
7363                         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())); },
7364                         _ => panic!("Unexpected event"),
7365                 }
7366         } else { assert!(false) }
7367
7368         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7369         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7370         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7371         open_channel.to_self_delay = 200;
7372         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) {
7373                 match error {
7374                         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()));  },
7375                         _ => panic!("Unexpected event"),
7376                 }
7377         } else { assert!(false); }
7378
7379         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7380         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7381         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()));
7382         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7383         accept_channel.to_self_delay = 200;
7384         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7385         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7386                 match action {
7387                         &ErrorAction::SendErrorMessage { ref msg } => {
7388                                 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()));
7389                         },
7390                         _ => { assert!(false); }
7391                 }
7392         } else { assert!(false); }
7393
7394         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7395         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7396         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7397         open_channel.to_self_delay = 200;
7398         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) {
7399                 match error {
7400                         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())); },
7401                         _ => panic!("Unexpected event"),
7402                 }
7403         } else { assert!(false); }
7404 }
7405
7406 #[test]
7407 fn test_data_loss_protect() {
7408         // We want to be sure that :
7409         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7410         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7411         // * we close channel in case of detecting other being fallen behind
7412         // * we are able to claim our own outputs thanks to to_remote being static
7413         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7414         let persister;
7415         let logger;
7416         let fee_estimator;
7417         let tx_broadcaster;
7418         let chain_source;
7419         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7420         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7421         // during signing due to revoked tx
7422         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7423         let keys_manager = &chanmon_cfgs[0].keys_manager;
7424         let monitor;
7425         let node_state_0;
7426         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7427         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7428         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7429
7430         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7431
7432         // Cache node A state before any channel update
7433         let previous_node_state = nodes[0].node.encode();
7434         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7435         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7436
7437         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7438         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7439
7440         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7441         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7442
7443         // Restore node A from previous state
7444         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7445         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7446         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7447         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7448         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7449         persister = test_utils::TestPersister::new();
7450         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7451         node_state_0 = {
7452                 let mut channel_monitors = HashMap::new();
7453                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7454                 <(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 {
7455                         keys_manager: keys_manager,
7456                         fee_estimator: &fee_estimator,
7457                         chain_monitor: &monitor,
7458                         logger: &logger,
7459                         tx_broadcaster: &tx_broadcaster,
7460                         default_config: UserConfig::default(),
7461                         channel_monitors,
7462                 }).unwrap().1
7463         };
7464         nodes[0].node = &node_state_0;
7465         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7466         nodes[0].chain_monitor = &monitor;
7467         nodes[0].chain_source = &chain_source;
7468
7469         check_added_monitors!(nodes[0], 1);
7470
7471         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7472         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7473
7474         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7475
7476         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7477         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7478         check_added_monitors!(nodes[0], 1);
7479
7480         {
7481                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7482                 assert_eq!(node_txn.len(), 0);
7483         }
7484
7485         let mut reestablish_1 = Vec::with_capacity(1);
7486         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7487                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7488                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7489                         reestablish_1.push(msg.clone());
7490                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7491                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7492                         match action {
7493                                 &ErrorAction::SendErrorMessage { ref msg } => {
7494                                         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");
7495                                 },
7496                                 _ => panic!("Unexpected event!"),
7497                         }
7498                 } else {
7499                         panic!("Unexpected event")
7500                 }
7501         }
7502
7503         // Check we close channel detecting A is fallen-behind
7504         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7505         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7506         check_added_monitors!(nodes[1], 1);
7507
7508
7509         // Check A is able to claim to_remote output
7510         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7511         assert_eq!(node_txn.len(), 1);
7512         check_spends!(node_txn[0], chan.3);
7513         assert_eq!(node_txn[0].output.len(), 2);
7514         mine_transaction(&nodes[0], &node_txn[0]);
7515         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7516         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 1000000);
7517         assert_eq!(spend_txn.len(), 1);
7518         check_spends!(spend_txn[0], node_txn[0]);
7519 }
7520
7521 #[test]
7522 fn test_check_htlc_underpaying() {
7523         // Send payment through A -> B but A is maliciously
7524         // sending a probe payment (i.e less than expected value0
7525         // to B, B should refuse payment.
7526
7527         let chanmon_cfgs = create_chanmon_cfgs(2);
7528         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7529         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7530         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7531
7532         // Create some initial channels
7533         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7534
7535         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7536
7537         // Node 3 is expecting payment of 100_000 but receive 10_000,
7538         // fail htlc like we didn't know the preimage.
7539         nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7540         nodes[1].node.process_pending_htlc_forwards();
7541
7542         let events = nodes[1].node.get_and_clear_pending_msg_events();
7543         assert_eq!(events.len(), 1);
7544         let (update_fail_htlc, commitment_signed) = match events[0] {
7545                 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 } } => {
7546                         assert!(update_add_htlcs.is_empty());
7547                         assert!(update_fulfill_htlcs.is_empty());
7548                         assert_eq!(update_fail_htlcs.len(), 1);
7549                         assert!(update_fail_malformed_htlcs.is_empty());
7550                         assert!(update_fee.is_none());
7551                         (update_fail_htlcs[0].clone(), commitment_signed)
7552                 },
7553                 _ => panic!("Unexpected event"),
7554         };
7555         check_added_monitors!(nodes[1], 1);
7556
7557         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7558         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7559
7560         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7561         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7562         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7563         expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7564         nodes[1].node.get_and_clear_pending_events();
7565 }
7566
7567 #[test]
7568 fn test_announce_disable_channels() {
7569         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7570         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7571
7572         let chanmon_cfgs = create_chanmon_cfgs(2);
7573         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7574         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7575         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7576
7577         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7578         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7579         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7580
7581         // Disconnect peers
7582         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7583         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7584
7585         nodes[0].node.timer_tick_occurred(); // dirty -> stagged
7586         nodes[0].node.timer_tick_occurred(); // staged -> fresh
7587         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7588         assert_eq!(msg_events.len(), 3);
7589         for e in msg_events {
7590                 match e {
7591                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7592                                 let short_id = msg.contents.short_channel_id;
7593                                 // Check generated channel_update match list in PendingChannelUpdate
7594                                 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7595                                         panic!("Generated ChannelUpdate for wrong chan!");
7596                                 }
7597                         },
7598                         _ => panic!("Unexpected event"),
7599                 }
7600         }
7601         // Reconnect peers
7602         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7603         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7604         assert_eq!(reestablish_1.len(), 3);
7605         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7606         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7607         assert_eq!(reestablish_2.len(), 3);
7608
7609         // Reestablish chan_1
7610         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7611         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7612         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7613         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7614         // Reestablish chan_2
7615         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7616         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7617         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7618         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7619         // Reestablish chan_3
7620         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7621         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7622         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7623         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7624
7625         nodes[0].node.timer_tick_occurred();
7626         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7627 }
7628
7629 #[test]
7630 fn test_bump_penalty_txn_on_revoked_commitment() {
7631         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7632         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7633
7634         let chanmon_cfgs = create_chanmon_cfgs(2);
7635         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7636         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7637         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7638
7639         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7640         let logger = test_utils::TestLogger::new();
7641
7642         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7643         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7644         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();
7645         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7646
7647         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7648         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7649         assert_eq!(revoked_txn[0].output.len(), 4);
7650         assert_eq!(revoked_txn[0].input.len(), 1);
7651         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7652         let revoked_txid = revoked_txn[0].txid();
7653
7654         let mut penalty_sum = 0;
7655         for outp in revoked_txn[0].output.iter() {
7656                 if outp.script_pubkey.is_v0_p2wsh() {
7657                         penalty_sum += outp.value;
7658                 }
7659         }
7660
7661         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7662         let header_114 = connect_blocks(&nodes[1], 14);
7663
7664         // Actually revoke tx by claiming a HTLC
7665         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7666         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7667         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7668         check_added_monitors!(nodes[1], 1);
7669
7670         // One or more justice tx should have been broadcast, check it
7671         let penalty_1;
7672         let feerate_1;
7673         {
7674                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7675                 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7676                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7677                 assert_eq!(node_txn[0].output.len(), 1);
7678                 check_spends!(node_txn[0], revoked_txn[0]);
7679                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7680                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7681                 penalty_1 = node_txn[0].txid();
7682                 node_txn.clear();
7683         };
7684
7685         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7686         connect_blocks(&nodes[1], 15);
7687         let mut penalty_2 = penalty_1;
7688         let mut feerate_2 = 0;
7689         {
7690                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7691                 assert_eq!(node_txn.len(), 1);
7692                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7693                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7694                         assert_eq!(node_txn[0].output.len(), 1);
7695                         check_spends!(node_txn[0], revoked_txn[0]);
7696                         penalty_2 = node_txn[0].txid();
7697                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7698                         assert_ne!(penalty_2, penalty_1);
7699                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7700                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7701                         // Verify 25% bump heuristic
7702                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7703                         node_txn.clear();
7704                 }
7705         }
7706         assert_ne!(feerate_2, 0);
7707
7708         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7709         connect_blocks(&nodes[1], 1);
7710         let penalty_3;
7711         let mut feerate_3 = 0;
7712         {
7713                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7714                 assert_eq!(node_txn.len(), 1);
7715                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7716                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7717                         assert_eq!(node_txn[0].output.len(), 1);
7718                         check_spends!(node_txn[0], revoked_txn[0]);
7719                         penalty_3 = node_txn[0].txid();
7720                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7721                         assert_ne!(penalty_3, penalty_2);
7722                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7723                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7724                         // Verify 25% bump heuristic
7725                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7726                         node_txn.clear();
7727                 }
7728         }
7729         assert_ne!(feerate_3, 0);
7730
7731         nodes[1].node.get_and_clear_pending_events();
7732         nodes[1].node.get_and_clear_pending_msg_events();
7733 }
7734
7735 #[test]
7736 fn test_bump_penalty_txn_on_revoked_htlcs() {
7737         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7738         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7739
7740         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7741         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7742         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7743         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7744         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7745
7746         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7747         // Lock HTLC in both directions
7748         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7749         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7750
7751         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7752         assert_eq!(revoked_local_txn[0].input.len(), 1);
7753         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7754
7755         // Revoke local commitment tx
7756         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7757
7758         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7759         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7760         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7761         check_closed_broadcast!(nodes[1], true);
7762         check_added_monitors!(nodes[1], 1);
7763
7764         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7765         assert_eq!(revoked_htlc_txn.len(), 4);
7766         if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7767                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7768                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7769                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7770                 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7771                 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7772                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7773         } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7774                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7775                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7776                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7777                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7778                 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7779                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7780         }
7781
7782         // Broadcast set of revoked txn on A
7783         let hash_128 = connect_blocks(&nodes[0], 40);
7784         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7785         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7786         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7787         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7788         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7789         let first;
7790         let feerate_1;
7791         let penalty_txn;
7792         {
7793                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7794                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7795                 // Verify claim tx are spending revoked HTLC txn
7796
7797                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7798                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7799                 // which are included in the same block (they are broadcasted because we scan the
7800                 // transactions linearly and generate claims as we go, they likely should be removed in the
7801                 // future).
7802                 assert_eq!(node_txn[0].input.len(), 1);
7803                 check_spends!(node_txn[0], revoked_local_txn[0]);
7804                 assert_eq!(node_txn[1].input.len(), 1);
7805                 check_spends!(node_txn[1], revoked_local_txn[0]);
7806                 assert_eq!(node_txn[2].input.len(), 1);
7807                 check_spends!(node_txn[2], revoked_local_txn[0]);
7808
7809                 // Each of the three justice transactions claim a separate (single) output of the three
7810                 // available, which we check here:
7811                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7812                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7813                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7814
7815                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7816                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7817
7818                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7819                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7820                 // a remote commitment tx has already been confirmed).
7821                 check_spends!(node_txn[3], chan.3);
7822
7823                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7824                 // output, checked above).
7825                 assert_eq!(node_txn[4].input.len(), 2);
7826                 assert_eq!(node_txn[4].output.len(), 1);
7827                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7828
7829                 first = node_txn[4].txid();
7830                 // Store both feerates for later comparison
7831                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7832                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7833                 penalty_txn = vec![node_txn[2].clone()];
7834                 node_txn.clear();
7835         }
7836
7837         // Connect one more block to see if bumped penalty are issued for HTLC txn
7838         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7839         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7840         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7841         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7842         {
7843                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7844                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7845
7846                 check_spends!(node_txn[0], revoked_local_txn[0]);
7847                 check_spends!(node_txn[1], revoked_local_txn[0]);
7848                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7849                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7850                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7851                 } else {
7852                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7853                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7854                 }
7855
7856                 node_txn.clear();
7857         };
7858
7859         // Few more blocks to confirm penalty txn
7860         connect_blocks(&nodes[0], 4);
7861         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7862         let header_144 = connect_blocks(&nodes[0], 9);
7863         let node_txn = {
7864                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7865                 assert_eq!(node_txn.len(), 1);
7866
7867                 assert_eq!(node_txn[0].input.len(), 2);
7868                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7869                 // Verify bumped tx is different and 25% bump heuristic
7870                 assert_ne!(first, node_txn[0].txid());
7871                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7872                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7873                 assert!(feerate_2 * 100 > feerate_1 * 125);
7874                 let txn = vec![node_txn[0].clone()];
7875                 node_txn.clear();
7876                 txn
7877         };
7878         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7879         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7880         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7881         connect_blocks(&nodes[0], 20);
7882         {
7883                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7884                 // We verify than no new transaction has been broadcast because previously
7885                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7886                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7887                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7888                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7889                 // up bumped justice generation.
7890                 assert_eq!(node_txn.len(), 0);
7891                 node_txn.clear();
7892         }
7893         check_closed_broadcast!(nodes[0], true);
7894         check_added_monitors!(nodes[0], 1);
7895 }
7896
7897 #[test]
7898 fn test_bump_penalty_txn_on_remote_commitment() {
7899         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7900         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7901
7902         // Create 2 HTLCs
7903         // Provide preimage for one
7904         // Check aggregation
7905
7906         let chanmon_cfgs = create_chanmon_cfgs(2);
7907         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7908         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7909         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7910
7911         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7912         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7913         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7914
7915         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7916         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7917         assert_eq!(remote_txn[0].output.len(), 4);
7918         assert_eq!(remote_txn[0].input.len(), 1);
7919         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7920
7921         // Claim a HTLC without revocation (provide B monitor with preimage)
7922         nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7923         mine_transaction(&nodes[1], &remote_txn[0]);
7924         check_added_monitors!(nodes[1], 2);
7925
7926         // One or more claim tx should have been broadcast, check it
7927         let timeout;
7928         let preimage;
7929         let feerate_timeout;
7930         let feerate_preimage;
7931         {
7932                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7933                 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7934                 assert_eq!(node_txn[0].input.len(), 1);
7935                 assert_eq!(node_txn[1].input.len(), 1);
7936                 check_spends!(node_txn[0], remote_txn[0]);
7937                 check_spends!(node_txn[1], remote_txn[0]);
7938                 check_spends!(node_txn[2], chan.3);
7939                 check_spends!(node_txn[3], node_txn[2]);
7940                 check_spends!(node_txn[4], node_txn[2]);
7941                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7942                         timeout = node_txn[0].txid();
7943                         let index = node_txn[0].input[0].previous_output.vout;
7944                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7945                         feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7946
7947                         preimage = node_txn[1].txid();
7948                         let index = node_txn[1].input[0].previous_output.vout;
7949                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7950                         feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7951                 } else {
7952                         timeout = node_txn[1].txid();
7953                         let index = node_txn[1].input[0].previous_output.vout;
7954                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7955                         feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7956
7957                         preimage = node_txn[0].txid();
7958                         let index = node_txn[0].input[0].previous_output.vout;
7959                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7960                         feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7961                 }
7962                 node_txn.clear();
7963         };
7964         assert_ne!(feerate_timeout, 0);
7965         assert_ne!(feerate_preimage, 0);
7966
7967         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7968         connect_blocks(&nodes[1], 15);
7969         {
7970                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7971                 assert_eq!(node_txn.len(), 2);
7972                 assert_eq!(node_txn[0].input.len(), 1);
7973                 assert_eq!(node_txn[1].input.len(), 1);
7974                 check_spends!(node_txn[0], remote_txn[0]);
7975                 check_spends!(node_txn[1], remote_txn[0]);
7976                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7977                         let index = node_txn[0].input[0].previous_output.vout;
7978                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7979                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7980                         assert!(new_feerate * 100 > feerate_timeout * 125);
7981                         assert_ne!(timeout, node_txn[0].txid());
7982
7983                         let index = node_txn[1].input[0].previous_output.vout;
7984                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7985                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7986                         assert!(new_feerate * 100 > feerate_preimage * 125);
7987                         assert_ne!(preimage, node_txn[1].txid());
7988                 } else {
7989                         let index = node_txn[1].input[0].previous_output.vout;
7990                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7991                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7992                         assert!(new_feerate * 100 > feerate_timeout * 125);
7993                         assert_ne!(timeout, node_txn[1].txid());
7994
7995                         let index = node_txn[0].input[0].previous_output.vout;
7996                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7997                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7998                         assert!(new_feerate * 100 > feerate_preimage * 125);
7999                         assert_ne!(preimage, node_txn[0].txid());
8000                 }
8001                 node_txn.clear();
8002         }
8003
8004         nodes[1].node.get_and_clear_pending_events();
8005         nodes[1].node.get_and_clear_pending_msg_events();
8006 }
8007
8008 #[test]
8009 fn test_counterparty_raa_skip_no_crash() {
8010         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8011         // commitment transaction, we would have happily carried on and provided them the next
8012         // commitment transaction based on one RAA forward. This would probably eventually have led to
8013         // channel closure, but it would not have resulted in funds loss. Still, our
8014         // EnforcingSigner would have paniced as it doesn't like jumps into the future. Here, we
8015         // check simply that the channel is closed in response to such an RAA, but don't check whether
8016         // we decide to punish our counterparty for revoking their funds (as we don't currently
8017         // implement that).
8018         let chanmon_cfgs = create_chanmon_cfgs(2);
8019         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8020         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8021         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8022         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8023
8024         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8025         let keys = &guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8026         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8027         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8028         // Must revoke without gaps
8029         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8030         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8031                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8032
8033         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8034                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8035         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8036         check_added_monitors!(nodes[1], 1);
8037 }
8038
8039 #[test]
8040 fn test_bump_txn_sanitize_tracking_maps() {
8041         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8042         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8043
8044         let chanmon_cfgs = create_chanmon_cfgs(2);
8045         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8046         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8047         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8048
8049         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8050         // Lock HTLC in both directions
8051         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8052         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8053
8054         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8055         assert_eq!(revoked_local_txn[0].input.len(), 1);
8056         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8057
8058         // Revoke local commitment tx
8059         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8060
8061         // Broadcast set of revoked txn on A
8062         connect_blocks(&nodes[0], 52 - CHAN_CONFIRM_DEPTH);
8063         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8064         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8065
8066         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8067         check_closed_broadcast!(nodes[0], true);
8068         check_added_monitors!(nodes[0], 1);
8069         let penalty_txn = {
8070                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8071                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8072                 check_spends!(node_txn[0], revoked_local_txn[0]);
8073                 check_spends!(node_txn[1], revoked_local_txn[0]);
8074                 check_spends!(node_txn[2], revoked_local_txn[0]);
8075                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8076                 node_txn.clear();
8077                 penalty_txn
8078         };
8079         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8080         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8081         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8082         {
8083                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8084                 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8085                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8086                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8087                 }
8088         }
8089 }
8090
8091 #[test]
8092 fn test_override_channel_config() {
8093         let chanmon_cfgs = create_chanmon_cfgs(2);
8094         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8095         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8096         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8097
8098         // Node0 initiates a channel to node1 using the override config.
8099         let mut override_config = UserConfig::default();
8100         override_config.own_channel_config.our_to_self_delay = 200;
8101
8102         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8103
8104         // Assert the channel created by node0 is using the override config.
8105         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8106         assert_eq!(res.channel_flags, 0);
8107         assert_eq!(res.to_self_delay, 200);
8108 }
8109
8110 #[test]
8111 fn test_override_0msat_htlc_minimum() {
8112         let mut zero_config = UserConfig::default();
8113         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8114         let chanmon_cfgs = create_chanmon_cfgs(2);
8115         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8116         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8117         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8118
8119         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8120         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8121         assert_eq!(res.htlc_minimum_msat, 1);
8122
8123         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8124         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8125         assert_eq!(res.htlc_minimum_msat, 1);
8126 }
8127
8128 #[test]
8129 fn test_simple_payment_secret() {
8130         // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8131         // features, however.
8132         let chanmon_cfgs = create_chanmon_cfgs(3);
8133         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8134         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8135         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8136
8137         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8138         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8139         let logger = test_utils::TestLogger::new();
8140
8141         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8142         let payment_secret = PaymentSecret([0xdb; 32]);
8143         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8144         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();
8145         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8146         // Claiming with all the correct values but the wrong secret should result in nothing...
8147         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8148         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8149         // ...but with the right secret we should be able to claim all the way back
8150         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8151 }
8152
8153 #[test]
8154 fn test_simple_mpp() {
8155         // Simple test of sending a multi-path payment.
8156         let chanmon_cfgs = create_chanmon_cfgs(4);
8157         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8158         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8159         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8160
8161         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8162         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8163         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8164         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8165         let logger = test_utils::TestLogger::new();
8166
8167         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8168         let payment_secret = PaymentSecret([0xdb; 32]);
8169         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8170         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();
8171         let path = route.paths[0].clone();
8172         route.paths.push(path);
8173         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8174         route.paths[0][0].short_channel_id = chan_1_id;
8175         route.paths[0][1].short_channel_id = chan_3_id;
8176         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8177         route.paths[1][0].short_channel_id = chan_2_id;
8178         route.paths[1][1].short_channel_id = chan_4_id;
8179         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8180         // Claiming with all the correct values but the wrong secret should result in nothing...
8181         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8182         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8183         // ...but with the right secret we should be able to claim all the way back
8184         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8185 }
8186
8187 #[test]
8188 fn test_update_err_monitor_lockdown() {
8189         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8190         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8191         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8192         //
8193         // This scenario may happen in a watchtower setup, where watchtower process a block height
8194         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8195         // commitment at same time.
8196
8197         let chanmon_cfgs = create_chanmon_cfgs(2);
8198         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8199         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8200         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8201
8202         // Create some initial channel
8203         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8204         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8205
8206         // Rebalance the network to generate htlc in the two directions
8207         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8208
8209         // Route a HTLC from node 0 to node 1 (but don't settle)
8210         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8211
8212         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8213         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8214         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8215         let persister = test_utils::TestPersister::new();
8216         let watchtower = {
8217                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8218                 let monitor = monitors.get(&outpoint).unwrap();
8219                 let mut w = test_utils::TestVecWriter(Vec::new());
8220                 monitor.write(&mut w).unwrap();
8221                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8222                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8223                 assert!(new_monitor == *monitor);
8224                 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);
8225                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8226                 watchtower
8227         };
8228         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8229         watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8230
8231         // Try to update ChannelMonitor
8232         assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8233         check_added_monitors!(nodes[1], 1);
8234         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8235         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8236         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8237         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8238                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8239                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8240                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8241                 } else { assert!(false); }
8242         } else { assert!(false); };
8243         // Our local monitor is in-sync and hasn't processed yet timeout
8244         check_added_monitors!(nodes[0], 1);
8245         let events = nodes[0].node.get_and_clear_pending_events();
8246         assert_eq!(events.len(), 1);
8247 }
8248
8249 #[test]
8250 fn test_concurrent_monitor_claim() {
8251         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8252         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8253         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8254         // state N+1 confirms. Alice claims output from state N+1.
8255
8256         let chanmon_cfgs = create_chanmon_cfgs(2);
8257         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8258         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8259         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8260
8261         // Create some initial channel
8262         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8263         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8264
8265         // Rebalance the network to generate htlc in the two directions
8266         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8267
8268         // Route a HTLC from node 0 to node 1 (but don't settle)
8269         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8270
8271         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8272         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8273         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8274         let persister = test_utils::TestPersister::new();
8275         let watchtower_alice = {
8276                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8277                 let monitor = monitors.get(&outpoint).unwrap();
8278                 let mut w = test_utils::TestVecWriter(Vec::new());
8279                 monitor.write(&mut w).unwrap();
8280                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8281                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8282                 assert!(new_monitor == *monitor);
8283                 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);
8284                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8285                 watchtower
8286         };
8287         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8288         watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8289
8290         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8291         {
8292                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8293                 assert_eq!(txn.len(), 2);
8294                 txn.clear();
8295         }
8296
8297         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8298         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8299         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8300         let persister = test_utils::TestPersister::new();
8301         let watchtower_bob = {
8302                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8303                 let monitor = monitors.get(&outpoint).unwrap();
8304                 let mut w = test_utils::TestVecWriter(Vec::new());
8305                 monitor.write(&mut w).unwrap();
8306                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8307                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8308                 assert!(new_monitor == *monitor);
8309                 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);
8310                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8311                 watchtower
8312         };
8313         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8314         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8315
8316         // Route another payment to generate another update with still previous HTLC pending
8317         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8318         {
8319                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8320                 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();
8321                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8322         }
8323         check_added_monitors!(nodes[1], 1);
8324
8325         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8326         assert_eq!(updates.update_add_htlcs.len(), 1);
8327         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8328         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8329                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8330                         // Watchtower Alice should already have seen the block and reject the update
8331                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8332                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8333                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8334                 } else { assert!(false); }
8335         } else { assert!(false); };
8336         // Our local monitor is in-sync and hasn't processed yet timeout
8337         check_added_monitors!(nodes[0], 1);
8338
8339         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8340         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8341         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8342
8343         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8344         let bob_state_y;
8345         {
8346                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8347                 assert_eq!(txn.len(), 2);
8348                 bob_state_y = txn[0].clone();
8349                 txn.clear();
8350         };
8351
8352         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8353         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8354         watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![bob_state_y.clone()] }, CHAN_CONFIRM_DEPTH + 2 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8355         {
8356                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8357                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8358                 // the onchain detection of the HTLC output
8359                 assert_eq!(htlc_txn.len(), 2);
8360                 check_spends!(htlc_txn[0], bob_state_y);
8361                 check_spends!(htlc_txn[1], bob_state_y);
8362         }
8363 }
8364
8365 #[test]
8366 fn test_pre_lockin_no_chan_closed_update() {
8367         // Test that if a peer closes a channel in response to a funding_created message we don't
8368         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8369         // message).
8370         //
8371         // Doing so would imply a channel monitor update before the initial channel monitor
8372         // registration, violating our API guarantees.
8373         //
8374         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8375         // then opening a second channel with the same funding output as the first (which is not
8376         // rejected because the first channel does not exist in the ChannelManager) and closing it
8377         // before receiving funding_signed.
8378         let chanmon_cfgs = create_chanmon_cfgs(2);
8379         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8380         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8381         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8382
8383         // Create an initial channel
8384         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8385         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8386         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8387         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8388         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8389
8390         // Move the first channel through the funding flow...
8391         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8392
8393         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8394         check_added_monitors!(nodes[0], 0);
8395
8396         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8397         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8398         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8399         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8400 }
8401
8402 #[test]
8403 fn test_htlc_no_detection() {
8404         // This test is a mutation to underscore the detection logic bug we had
8405         // before #653. HTLC value routed is above the remaining balance, thus
8406         // inverting HTLC and `to_remote` output. HTLC will come second and
8407         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8408         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8409         // outputs order detection for correct spending children filtring.
8410
8411         let chanmon_cfgs = create_chanmon_cfgs(2);
8412         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8413         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8414         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8415
8416         // Create some initial channels
8417         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8418
8419         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000, 1_000_000);
8420         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8421         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8422         assert_eq!(local_txn[0].input.len(), 1);
8423         assert_eq!(local_txn[0].output.len(), 3);
8424         check_spends!(local_txn[0], chan_1.3);
8425
8426         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8427         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8428         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8429         // We deliberately connect the local tx twice as this should provoke a failure calling
8430         // this test before #653 fix.
8431         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);
8432         check_closed_broadcast!(nodes[0], true);
8433         check_added_monitors!(nodes[0], 1);
8434
8435         let htlc_timeout = {
8436                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8437                 assert_eq!(node_txn[0].input.len(), 1);
8438                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8439                 check_spends!(node_txn[0], local_txn[0]);
8440                 node_txn[0].clone()
8441         };
8442
8443         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8444         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8445         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8446         expect_payment_failed!(nodes[0], our_payment_hash, true);
8447 }
8448
8449 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8450         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8451         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8452         // Carol, Alice would be the upstream node, and Carol the downstream.)
8453         //
8454         // Steps of the test:
8455         // 1) Alice sends a HTLC to Carol through Bob.
8456         // 2) Carol doesn't settle the HTLC.
8457         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8458         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8459         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8460         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8461         // 5) Carol release the preimage to Bob off-chain.
8462         // 6) Bob claims the offered output on the broadcasted commitment.
8463         let chanmon_cfgs = create_chanmon_cfgs(3);
8464         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8465         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8466         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8467
8468         // Create some initial channels
8469         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8470         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8471
8472         // Steps (1) and (2):
8473         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8474         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8475
8476         // Check that Alice's commitment transaction now contains an output for this HTLC.
8477         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8478         check_spends!(alice_txn[0], chan_ab.3);
8479         assert_eq!(alice_txn[0].output.len(), 2);
8480         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8481         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8482         assert_eq!(alice_txn.len(), 2);
8483
8484         // Steps (3) and (4):
8485         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8486         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8487         let mut force_closing_node = 0; // Alice force-closes
8488         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8489         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8490         check_closed_broadcast!(nodes[force_closing_node], true);
8491         check_added_monitors!(nodes[force_closing_node], 1);
8492         if go_onchain_before_fulfill {
8493                 let txn_to_broadcast = match broadcast_alice {
8494                         true => alice_txn.clone(),
8495                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8496                 };
8497                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8498                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8499                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8500                 if broadcast_alice {
8501                         check_closed_broadcast!(nodes[1], true);
8502                         check_added_monitors!(nodes[1], 1);
8503                 }
8504                 assert_eq!(bob_txn.len(), 1);
8505                 check_spends!(bob_txn[0], chan_ab.3);
8506         }
8507
8508         // Step (5):
8509         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8510         // process of removing the HTLC from their commitment transactions.
8511         assert!(nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000));
8512         check_added_monitors!(nodes[2], 1);
8513         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8514         assert!(carol_updates.update_add_htlcs.is_empty());
8515         assert!(carol_updates.update_fail_htlcs.is_empty());
8516         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8517         assert!(carol_updates.update_fee.is_none());
8518         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8519
8520         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8521         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8522         if !go_onchain_before_fulfill && broadcast_alice {
8523                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8524                 assert_eq!(events.len(), 1);
8525                 match events[0] {
8526                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8527                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8528                         },
8529                         _ => panic!("Unexpected event"),
8530                 };
8531         }
8532         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8533         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8534         // Carol<->Bob's updated commitment transaction info.
8535         check_added_monitors!(nodes[1], 2);
8536
8537         let events = nodes[1].node.get_and_clear_pending_msg_events();
8538         assert_eq!(events.len(), 2);
8539         let bob_revocation = match events[0] {
8540                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8541                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8542                         (*msg).clone()
8543                 },
8544                 _ => panic!("Unexpected event"),
8545         };
8546         let bob_updates = match events[1] {
8547                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8548                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8549                         (*updates).clone()
8550                 },
8551                 _ => panic!("Unexpected event"),
8552         };
8553
8554         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8555         check_added_monitors!(nodes[2], 1);
8556         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8557         check_added_monitors!(nodes[2], 1);
8558
8559         let events = nodes[2].node.get_and_clear_pending_msg_events();
8560         assert_eq!(events.len(), 1);
8561         let carol_revocation = match events[0] {
8562                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8563                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8564                         (*msg).clone()
8565                 },
8566                 _ => panic!("Unexpected event"),
8567         };
8568         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8569         check_added_monitors!(nodes[1], 1);
8570
8571         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8572         // here's where we put said channel's commitment tx on-chain.
8573         let mut txn_to_broadcast = alice_txn.clone();
8574         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8575         if !go_onchain_before_fulfill {
8576                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8577                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8578                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8579                 if broadcast_alice {
8580                         check_closed_broadcast!(nodes[1], true);
8581                         check_added_monitors!(nodes[1], 1);
8582                 }
8583                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8584                 if broadcast_alice {
8585                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8586                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8587                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8588                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8589                         // broadcasted.
8590                         assert_eq!(bob_txn.len(), 3);
8591                         check_spends!(bob_txn[1], chan_ab.3);
8592                 } else {
8593                         assert_eq!(bob_txn.len(), 2);
8594                         check_spends!(bob_txn[0], chan_ab.3);
8595                 }
8596         }
8597
8598         // Step (6):
8599         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8600         // broadcasted commitment transaction.
8601         {
8602                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8603                 if go_onchain_before_fulfill {
8604                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8605                         assert_eq!(bob_txn.len(), 2);
8606                 }
8607                 let script_weight = match broadcast_alice {
8608                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8609                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8610                 };
8611                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8612                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8613                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8614                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8615                 if broadcast_alice && !go_onchain_before_fulfill {
8616                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8617                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8618                 } else {
8619                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8620                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8621                 }
8622         }
8623 }
8624
8625 #[test]
8626 fn test_onchain_htlc_settlement_after_close() {
8627         do_test_onchain_htlc_settlement_after_close(true, true);
8628         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8629         do_test_onchain_htlc_settlement_after_close(true, false);
8630         do_test_onchain_htlc_settlement_after_close(false, false);
8631 }
8632
8633 #[test]
8634 fn test_duplicate_chan_id() {
8635         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8636         // already open we reject it and keep the old channel.
8637         //
8638         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8639         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8640         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8641         // updating logic for the existing channel.
8642         let chanmon_cfgs = create_chanmon_cfgs(2);
8643         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8644         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8645         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8646
8647         // Create an initial channel
8648         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8649         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8650         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8651         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()));
8652
8653         // Try to create a second channel with the same temporary_channel_id as the first and check
8654         // that it is rejected.
8655         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8656         {
8657                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8658                 assert_eq!(events.len(), 1);
8659                 match events[0] {
8660                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8661                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8662                                 // first (valid) and second (invalid) channels are closed, given they both have
8663                                 // the same non-temporary channel_id. However, currently we do not, so we just
8664                                 // 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         // Move the first channel through the funding flow...
8673         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8674
8675         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8676         check_added_monitors!(nodes[0], 0);
8677
8678         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8679         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8680         {
8681                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8682                 assert_eq!(added_monitors.len(), 1);
8683                 assert_eq!(added_monitors[0].0, funding_output);
8684                 added_monitors.clear();
8685         }
8686         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8687
8688         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8689         let channel_id = funding_outpoint.to_channel_id();
8690
8691         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8692         // temporary one).
8693
8694         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8695         // Technically this is allowed by the spec, but we don't support it and there's little reason
8696         // to. Still, it shouldn't cause any other issues.
8697         open_chan_msg.temporary_channel_id = channel_id;
8698         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8699         {
8700                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8701                 assert_eq!(events.len(), 1);
8702                 match events[0] {
8703                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8704                                 // Technically, at this point, nodes[1] would be justified in thinking both
8705                                 // channels are closed, but currently we do not, so we just move forward with it.
8706                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8707                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8708                         },
8709                         _ => panic!("Unexpected event"),
8710                 }
8711         }
8712
8713         // Now try to create a second channel which has a duplicate funding output.
8714         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8715         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8716         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8717         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()));
8718         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8719
8720         let funding_created = {
8721                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8722                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8723                 let logger = test_utils::TestLogger::new();
8724                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8725         };
8726         check_added_monitors!(nodes[0], 0);
8727         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8728         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8729         // still needs to be cleared here.
8730         check_added_monitors!(nodes[1], 1);
8731
8732         // ...still, nodes[1] will reject the duplicate channel.
8733         {
8734                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8735                 assert_eq!(events.len(), 1);
8736                 match events[0] {
8737                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8738                                 // Technically, at this point, nodes[1] would be justified in thinking both
8739                                 // channels are closed, but currently we do not, so we just move forward with it.
8740                                 assert_eq!(msg.channel_id, channel_id);
8741                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8742                         },
8743                         _ => panic!("Unexpected event"),
8744                 }
8745         }
8746
8747         // finally, finish creating the original channel and send a payment over it to make sure
8748         // everything is functional.
8749         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8750         {
8751                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8752                 assert_eq!(added_monitors.len(), 1);
8753                 assert_eq!(added_monitors[0].0, funding_output);
8754                 added_monitors.clear();
8755         }
8756
8757         let events_4 = nodes[0].node.get_and_clear_pending_events();
8758         assert_eq!(events_4.len(), 0);
8759         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8760         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
8761
8762         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8763         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8764         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8765         send_payment(&nodes[0], &[&nodes[1]], 8000000, 8_000_000);
8766 }
8767
8768 #[test]
8769 fn test_error_chans_closed() {
8770         // Test that we properly handle error messages, closing appropriate channels.
8771         //
8772         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8773         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8774         // we can test various edge cases around it to ensure we don't regress.
8775         let chanmon_cfgs = create_chanmon_cfgs(3);
8776         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8777         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8778         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8779
8780         // Create some initial channels
8781         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8782         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8783         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8784
8785         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8786         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8787         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8788
8789         // Closing a channel from a different peer has no effect
8790         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8791         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8792
8793         // Closing one channel doesn't impact others
8794         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8795         check_added_monitors!(nodes[0], 1);
8796         check_closed_broadcast!(nodes[0], false);
8797         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8798         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8799         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);
8800         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);
8801
8802         // A null channel ID should close all channels
8803         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8804         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8805         check_added_monitors!(nodes[0], 2);
8806         let events = nodes[0].node.get_and_clear_pending_msg_events();
8807         assert_eq!(events.len(), 2);
8808         match events[0] {
8809                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8810                         assert_eq!(msg.contents.flags & 2, 2);
8811                 },
8812                 _ => panic!("Unexpected event"),
8813         }
8814         match events[1] {
8815                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8816                         assert_eq!(msg.contents.flags & 2, 2);
8817                 },
8818                 _ => panic!("Unexpected event"),
8819         }
8820         // Note that at this point users of a standard PeerHandler will end up calling
8821         // peer_disconnected with no_connection_possible set to false, duplicating the
8822         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8823         // users with their own peer handling logic. We duplicate the call here, however.
8824         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8825         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8826
8827         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8828         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8829         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8830 }
8831
8832 #[test]
8833 fn test_invalid_funding_tx() {
8834         // Test that we properly handle invalid funding transactions sent to us from a peer.
8835         //
8836         // Previously, all other major lightning implementations had failed to properly sanitize
8837         // funding transactions from their counterparties, leading to a multi-implementation critical
8838         // security vulnerability (though we always sanitized properly, we've previously had
8839         // un-released crashes in the sanitization process).
8840         let chanmon_cfgs = create_chanmon_cfgs(2);
8841         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8842         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8843         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8844
8845         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8846         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()));
8847         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()));
8848
8849         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
8850         for output in tx.output.iter_mut() {
8851                 // Make the confirmed funding transaction have a bogus script_pubkey
8852                 output.script_pubkey = bitcoin::Script::new();
8853         }
8854
8855         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
8856         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id()));
8857         check_added_monitors!(nodes[1], 1);
8858
8859         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id()));
8860         check_added_monitors!(nodes[0], 1);
8861
8862         let events_1 = nodes[0].node.get_and_clear_pending_events();
8863         assert_eq!(events_1.len(), 0);
8864
8865         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8866         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8867         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8868
8869         confirm_transaction_at(&nodes[1], &tx, 1);
8870         check_added_monitors!(nodes[1], 1);
8871         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8872         assert_eq!(events_2.len(), 1);
8873         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
8874                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8875                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
8876                         assert_eq!(msg.data, "funding tx had wrong script/value or output index");
8877                 } else { panic!(); }
8878         } else { panic!(); }
8879         assert_eq!(nodes[1].node.list_channels().len(), 0);
8880 }