Rename timer_chan_freshness_every_min for uniformity with PeerManager
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use chain;
15 use chain::Watch;
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::{KeysInterface, BaseSign};
20 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
21 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
22 use ln::channel::{Channel, ChannelError};
23 use ln::{chan_utils, onion_utils};
24 use routing::router::{Route, RouteHop, get_route};
25 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
26 use ln::msgs;
27 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
28 use util::enforcing_trait_impls::EnforcingSigner;
29 use util::{byte_utils, test_utils};
30 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
31 use util::errors::APIError;
32 use util::ser::{Writeable, ReadableArgs};
33 use util::config::UserConfig;
34
35 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
36 use bitcoin::hash_types::{Txid, BlockHash};
37 use bitcoin::blockdata::block::{Block, BlockHeader};
38 use bitcoin::blockdata::script::Builder;
39 use bitcoin::blockdata::opcodes;
40 use bitcoin::blockdata::constants::genesis_block;
41 use bitcoin::network::constants::Network;
42
43 use bitcoin::hashes::sha256::Hash as Sha256;
44 use bitcoin::hashes::Hash;
45
46 use bitcoin::secp256k1::{Secp256k1, Message};
47 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
48
49 use regex;
50
51 use std::collections::{BTreeSet, HashMap, HashSet};
52 use std::default::Default;
53 use std::sync::Mutex;
54 use std::sync::atomic::Ordering;
55
56 use ln::functional_test_utils::*;
57 use ln::chan_utils::CommitmentTransaction;
58 use ln::msgs::OptionalField::Present;
59
60 #[test]
61 fn test_insane_channel_opens() {
62         // Stand up a network of 2 nodes
63         let chanmon_cfgs = create_chanmon_cfgs(2);
64         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
65         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
66         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
67
68         // Instantiate channel parameters where we push the maximum msats given our
69         // funding satoshis
70         let channel_value_sat = 31337; // same as funding satoshis
71         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
72         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
73
74         // Have node0 initiate a channel to node1 with aforementioned parameters
75         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
76
77         // Extract the channel open message from node0 to node1
78         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
79
80         // Test helper that asserts we get the correct error string given a mutator
81         // that supposedly makes the channel open message insane
82         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
83                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
84                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
85                 assert_eq!(msg_events.len(), 1);
86                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
87                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
88                         match action {
89                                 &ErrorAction::SendErrorMessage { .. } => {
90                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
91                                 },
92                                 _ => panic!("unexpected event!"),
93                         }
94                 } else { assert!(false); }
95         };
96
97         use ln::channel::MAX_FUNDING_SATOSHIS;
98         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
99
100         // Test all mutations that would make the channel open message insane
101         insane_open_helper(format!("Funding must be smaller than {}. It was {}", MAX_FUNDING_SATOSHIS, MAX_FUNDING_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
102
103         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
104
105         insane_open_helper(r"push_msat \d+ was larger than funding value \d+", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
106
107         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
108
109         insane_open_helper(r"Bogus; channel reserve \(\d+\) is less than dust limit \(\d+\)", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
110
111         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
112
113         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
114
115         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
116
117         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
118 }
119
120 #[test]
121 fn test_async_inbound_update_fee() {
122         let chanmon_cfgs = create_chanmon_cfgs(2);
123         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
124         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
125         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
126         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
127         let logger = test_utils::TestLogger::new();
128         let channel_id = chan.2;
129
130         // balancing
131         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
132
133         // A                                        B
134         // update_fee                            ->
135         // send (1) commitment_signed            -.
136         //                                       <- update_add_htlc/commitment_signed
137         // send (2) RAA (awaiting remote revoke) -.
138         // (1) commitment_signed is delivered    ->
139         //                                       .- send (3) RAA (awaiting remote revoke)
140         // (2) RAA is delivered                  ->
141         //                                       .- send (4) commitment_signed
142         //                                       <- (3) RAA is delivered
143         // send (5) commitment_signed            -.
144         //                                       <- (4) commitment_signed is delivered
145         // send (6) RAA                          -.
146         // (5) commitment_signed is delivered    ->
147         //                                       <- RAA
148         // (6) RAA is delivered                  ->
149
150         // First nodes[0] generates an update_fee
151         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
152         check_added_monitors!(nodes[0], 1);
153
154         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
155         assert_eq!(events_0.len(), 1);
156         let (update_msg, commitment_signed) = match events_0[0] { // (1)
157                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
158                         (update_fee.as_ref(), commitment_signed)
159                 },
160                 _ => panic!("Unexpected event"),
161         };
162
163         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
164
165         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
166         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
167         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
168         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
169         check_added_monitors!(nodes[1], 1);
170
171         let payment_event = {
172                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
173                 assert_eq!(events_1.len(), 1);
174                 SendEvent::from_event(events_1.remove(0))
175         };
176         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
177         assert_eq!(payment_event.msgs.len(), 1);
178
179         // ...now when the messages get delivered everyone should be happy
180         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
181         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
182         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
183         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
184         check_added_monitors!(nodes[0], 1);
185
186         // deliver(1), generate (3):
187         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
188         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
189         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
190         check_added_monitors!(nodes[1], 1);
191
192         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
193         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
194         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
195         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
196         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
197         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
198         assert!(bs_update.update_fee.is_none()); // (4)
199         check_added_monitors!(nodes[1], 1);
200
201         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
202         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
203         assert!(as_update.update_add_htlcs.is_empty()); // (5)
204         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
205         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
206         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
207         assert!(as_update.update_fee.is_none()); // (5)
208         check_added_monitors!(nodes[0], 1);
209
210         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
211         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
212         // only (6) so get_event_msg's assert(len == 1) passes
213         check_added_monitors!(nodes[0], 1);
214
215         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
216         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
217         check_added_monitors!(nodes[1], 1);
218
219         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
220         check_added_monitors!(nodes[0], 1);
221
222         let events_2 = nodes[0].node.get_and_clear_pending_events();
223         assert_eq!(events_2.len(), 1);
224         match events_2[0] {
225                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
226                 _ => panic!("Unexpected event"),
227         }
228
229         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
230         check_added_monitors!(nodes[1], 1);
231 }
232
233 #[test]
234 fn test_update_fee_unordered_raa() {
235         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
236         // crash in an earlier version of the update_fee patch)
237         let chanmon_cfgs = create_chanmon_cfgs(2);
238         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
239         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
240         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
241         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
242         let channel_id = chan.2;
243         let logger = test_utils::TestLogger::new();
244
245         // balancing
246         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
247
248         // First nodes[0] generates an update_fee
249         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
250         check_added_monitors!(nodes[0], 1);
251
252         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
253         assert_eq!(events_0.len(), 1);
254         let update_msg = match events_0[0] { // (1)
255                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
256                         update_fee.as_ref()
257                 },
258                 _ => panic!("Unexpected event"),
259         };
260
261         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
262
263         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
264         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
265         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
266         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
267         check_added_monitors!(nodes[1], 1);
268
269         let payment_event = {
270                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
271                 assert_eq!(events_1.len(), 1);
272                 SendEvent::from_event(events_1.remove(0))
273         };
274         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
275         assert_eq!(payment_event.msgs.len(), 1);
276
277         // ...now when the messages get delivered everyone should be happy
278         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
279         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
280         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
281         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
282         check_added_monitors!(nodes[0], 1);
283
284         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
285         check_added_monitors!(nodes[1], 1);
286
287         // We can't continue, sadly, because our (1) now has a bogus signature
288 }
289
290 #[test]
291 fn test_multi_flight_update_fee() {
292         let chanmon_cfgs = create_chanmon_cfgs(2);
293         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
294         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
295         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
296         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
297         let channel_id = chan.2;
298
299         // A                                        B
300         // update_fee/commitment_signed          ->
301         //                                       .- send (1) RAA and (2) commitment_signed
302         // update_fee (never committed)          ->
303         // (3) update_fee                        ->
304         // We have to manually generate the above update_fee, it is allowed by the protocol but we
305         // don't track which updates correspond to which revoke_and_ack responses so we're in
306         // AwaitingRAA mode and will not generate the update_fee yet.
307         //                                       <- (1) RAA delivered
308         // (3) is generated and send (4) CS      -.
309         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
310         // know the per_commitment_point to use for it.
311         //                                       <- (2) commitment_signed delivered
312         // revoke_and_ack                        ->
313         //                                          B should send no response here
314         // (4) commitment_signed delivered       ->
315         //                                       <- RAA/commitment_signed delivered
316         // revoke_and_ack                        ->
317
318         // First nodes[0] generates an update_fee
319         let initial_feerate = get_feerate!(nodes[0], channel_id);
320         nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
321         check_added_monitors!(nodes[0], 1);
322
323         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
324         assert_eq!(events_0.len(), 1);
325         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
326                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
327                         (update_fee.as_ref().unwrap(), commitment_signed)
328                 },
329                 _ => panic!("Unexpected event"),
330         };
331
332         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
333         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
334         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
335         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
336         check_added_monitors!(nodes[1], 1);
337
338         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
339         // transaction:
340         nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
341         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
342         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
343
344         // Create the (3) update_fee message that nodes[0] will generate before it does...
345         let mut update_msg_2 = msgs::UpdateFee {
346                 channel_id: update_msg_1.channel_id.clone(),
347                 feerate_per_kw: (initial_feerate + 30) as u32,
348         };
349
350         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
351
352         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
353         // Deliver (3)
354         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
355
356         // Deliver (1), generating (3) and (4)
357         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
358         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
359         check_added_monitors!(nodes[0], 1);
360         assert!(as_second_update.update_add_htlcs.is_empty());
361         assert!(as_second_update.update_fulfill_htlcs.is_empty());
362         assert!(as_second_update.update_fail_htlcs.is_empty());
363         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
364         // Check that the update_fee newly generated matches what we delivered:
365         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
366         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
367
368         // Deliver (2) commitment_signed
369         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
370         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
371         check_added_monitors!(nodes[0], 1);
372         // No commitment_signed so get_event_msg's assert(len == 1) passes
373
374         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
375         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
376         check_added_monitors!(nodes[1], 1);
377
378         // Delever (4)
379         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
380         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
381         check_added_monitors!(nodes[1], 1);
382
383         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
384         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
385         check_added_monitors!(nodes[0], 1);
386
387         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
388         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
389         // No commitment_signed so get_event_msg's assert(len == 1) passes
390         check_added_monitors!(nodes[0], 1);
391
392         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
393         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
394         check_added_monitors!(nodes[1], 1);
395 }
396
397 fn do_test_1_conf_open(connect_style: ConnectStyle) {
398         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
399         // tests that we properly send one in that case.
400         let mut alice_config = UserConfig::default();
401         alice_config.own_channel_config.minimum_depth = 1;
402         alice_config.channel_options.announced_channel = true;
403         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
404         let mut bob_config = UserConfig::default();
405         bob_config.own_channel_config.minimum_depth = 1;
406         bob_config.channel_options.announced_channel = true;
407         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
408         let chanmon_cfgs = create_chanmon_cfgs(2);
409         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
410         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
411         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
412         *nodes[0].connect_style.borrow_mut() = connect_style;
413
414         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
415         mine_transaction(&nodes[1], &tx);
416         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id()));
417
418         mine_transaction(&nodes[0], &tx);
419         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
420         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
421
422         for node in nodes {
423                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
424                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
425                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
426         }
427 }
428 #[test]
429 fn test_1_conf_open() {
430         do_test_1_conf_open(ConnectStyle::BestBlockFirst);
431         do_test_1_conf_open(ConnectStyle::TransactionsFirst);
432         do_test_1_conf_open(ConnectStyle::FullBlockViaListen);
433 }
434
435 fn do_test_sanity_on_in_flight_opens(steps: u8) {
436         // Previously, we had issues deserializing channels when we hadn't connected the first block
437         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
438         // serialization round-trips and simply do steps towards opening a channel and then drop the
439         // Node objects.
440
441         let chanmon_cfgs = create_chanmon_cfgs(2);
442         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
443         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
444         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
445
446         if steps & 0b1000_0000 != 0{
447                 let block = Block {
448                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
449                         txdata: vec![],
450                 };
451                 connect_block(&nodes[0], &block);
452                 connect_block(&nodes[1], &block);
453         }
454
455         if steps & 0x0f == 0 { return; }
456         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
457         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
458
459         if steps & 0x0f == 1 { return; }
460         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
461         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
462
463         if steps & 0x0f == 2 { return; }
464         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
465
466         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
467
468         if steps & 0x0f == 3 { return; }
469         nodes[0].node.funding_transaction_generated(&temporary_channel_id, 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.latest_block_height.load(Ordering::Acquire) as u32 + 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.latest_block_height.load(Ordering::Acquire) as u32 + 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 = 546000; // 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.latest_block_height.load(Ordering::Acquire) as u32 + 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 #[test]
2945 fn test_htlc_on_chain_timeout() {
2946         // Test that in case of a unilateral close onchain, we detect the state of output and
2947         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2948         // broadcasting the right event to other nodes in payment path.
2949         // A ------------------> B ----------------------> C (timeout)
2950         //    B's commitment tx                 C's commitment tx
2951         //            \                                  \
2952         //         B's HTLC timeout tx               B's timeout tx
2953
2954         let chanmon_cfgs = create_chanmon_cfgs(3);
2955         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2956         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2957         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2958
2959         // Create some intial channels
2960         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2961         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2962
2963         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2964         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2965         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2966
2967         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2968
2969         // Broadcast legit commitment tx from C on B's chain
2970         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2971         check_spends!(commitment_tx[0], chan_2.3);
2972         nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2973         check_added_monitors!(nodes[2], 0);
2974         expect_pending_htlcs_forwardable!(nodes[2]);
2975         check_added_monitors!(nodes[2], 1);
2976
2977         let events = nodes[2].node.get_and_clear_pending_msg_events();
2978         assert_eq!(events.len(), 1);
2979         match events[0] {
2980                 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, .. } } => {
2981                         assert!(update_add_htlcs.is_empty());
2982                         assert!(!update_fail_htlcs.is_empty());
2983                         assert!(update_fulfill_htlcs.is_empty());
2984                         assert!(update_fail_malformed_htlcs.is_empty());
2985                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2986                 },
2987                 _ => panic!("Unexpected event"),
2988         };
2989         mine_transaction(&nodes[2], &commitment_tx[0]);
2990         check_closed_broadcast!(nodes[2], true);
2991         check_added_monitors!(nodes[2], 1);
2992         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2993         assert_eq!(node_txn.len(), 1);
2994         check_spends!(node_txn[0], chan_2.3);
2995         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2996
2997         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2998         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2999         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3000         mine_transaction(&nodes[1], &commitment_tx[0]);
3001         let timeout_tx;
3002         {
3003                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3004                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
3005                 assert_eq!(node_txn[0], node_txn[3]);
3006                 assert_eq!(node_txn[1], node_txn[4]);
3007
3008                 check_spends!(node_txn[2], commitment_tx[0]);
3009                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3010
3011                 check_spends!(node_txn[0], chan_2.3);
3012                 check_spends!(node_txn[1], node_txn[0]);
3013                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3014                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3015
3016                 timeout_tx = node_txn[2].clone();
3017                 node_txn.clear();
3018         }
3019
3020         mine_transaction(&nodes[1], &timeout_tx);
3021         check_added_monitors!(nodes[1], 1);
3022         check_closed_broadcast!(nodes[1], true);
3023         {
3024                 // B will rebroadcast a fee-bumped timeout transaction here.
3025                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3026                 assert_eq!(node_txn.len(), 1);
3027                 check_spends!(node_txn[0], commitment_tx[0]);
3028         }
3029
3030         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3031         {
3032                 // B will rebroadcast its own holder commitment transaction here...just because
3033                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3034                 assert_eq!(node_txn.len(), 1);
3035                 check_spends!(node_txn[0], chan_2.3);
3036         }
3037
3038         expect_pending_htlcs_forwardable!(nodes[1]);
3039         check_added_monitors!(nodes[1], 1);
3040         let events = nodes[1].node.get_and_clear_pending_msg_events();
3041         assert_eq!(events.len(), 1);
3042         match events[0] {
3043                 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, .. } } => {
3044                         assert!(update_add_htlcs.is_empty());
3045                         assert!(!update_fail_htlcs.is_empty());
3046                         assert!(update_fulfill_htlcs.is_empty());
3047                         assert!(update_fail_malformed_htlcs.is_empty());
3048                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3049                 },
3050                 _ => panic!("Unexpected event"),
3051         };
3052
3053         // Broadcast legit commitment tx from B on A's chain
3054         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3055         check_spends!(commitment_tx[0], chan_1.3);
3056
3057         mine_transaction(&nodes[0], &commitment_tx[0]);
3058
3059         check_closed_broadcast!(nodes[0], true);
3060         check_added_monitors!(nodes[0], 1);
3061         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3062         assert_eq!(node_txn.len(), 3);
3063         check_spends!(node_txn[0], commitment_tx[0]);
3064         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3065         check_spends!(node_txn[1], chan_1.3);
3066         check_spends!(node_txn[2], node_txn[1]);
3067         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3068         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3069 }
3070
3071 #[test]
3072 fn test_simple_commitment_revoked_fail_backward() {
3073         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3074         // and fail backward accordingly.
3075
3076         let chanmon_cfgs = create_chanmon_cfgs(3);
3077         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3078         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3079         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3080
3081         // Create some initial channels
3082         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3083         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3084
3085         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3086         // Get the will-be-revoked local txn from nodes[2]
3087         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3088         // Revoke the old state
3089         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3090
3091         let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3092
3093         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3094         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3095         check_added_monitors!(nodes[1], 1);
3096         check_closed_broadcast!(nodes[1], true);
3097
3098         expect_pending_htlcs_forwardable!(nodes[1]);
3099         check_added_monitors!(nodes[1], 1);
3100         let events = nodes[1].node.get_and_clear_pending_msg_events();
3101         assert_eq!(events.len(), 1);
3102         match events[0] {
3103                 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, .. } } => {
3104                         assert!(update_add_htlcs.is_empty());
3105                         assert_eq!(update_fail_htlcs.len(), 1);
3106                         assert!(update_fulfill_htlcs.is_empty());
3107                         assert!(update_fail_malformed_htlcs.is_empty());
3108                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3109
3110                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3111                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3112
3113                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3114                         assert_eq!(events.len(), 1);
3115                         match events[0] {
3116                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3117                                 _ => panic!("Unexpected event"),
3118                         }
3119                         expect_payment_failed!(nodes[0], payment_hash, false);
3120                 },
3121                 _ => panic!("Unexpected event"),
3122         }
3123 }
3124
3125 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3126         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3127         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3128         // commitment transaction anymore.
3129         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3130         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3131         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3132         // technically disallowed and we should probably handle it reasonably.
3133         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3134         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3135         // transactions:
3136         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3137         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3138         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3139         //   and once they revoke the previous commitment transaction (allowing us to send a new
3140         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3141         let chanmon_cfgs = create_chanmon_cfgs(3);
3142         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3143         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3144         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3145
3146         // Create some initial channels
3147         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3148         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3149
3150         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3151         // Get the will-be-revoked local txn from nodes[2]
3152         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3153         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3154         // Revoke the old state
3155         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3156
3157         let value = if use_dust {
3158                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3159                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3160                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3161         } else { 3000000 };
3162
3163         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3164         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3165         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3166
3167         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3168         expect_pending_htlcs_forwardable!(nodes[2]);
3169         check_added_monitors!(nodes[2], 1);
3170         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3171         assert!(updates.update_add_htlcs.is_empty());
3172         assert!(updates.update_fulfill_htlcs.is_empty());
3173         assert!(updates.update_fail_malformed_htlcs.is_empty());
3174         assert_eq!(updates.update_fail_htlcs.len(), 1);
3175         assert!(updates.update_fee.is_none());
3176         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3177         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3178         // Drop the last RAA from 3 -> 2
3179
3180         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3181         expect_pending_htlcs_forwardable!(nodes[2]);
3182         check_added_monitors!(nodes[2], 1);
3183         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3184         assert!(updates.update_add_htlcs.is_empty());
3185         assert!(updates.update_fulfill_htlcs.is_empty());
3186         assert!(updates.update_fail_malformed_htlcs.is_empty());
3187         assert_eq!(updates.update_fail_htlcs.len(), 1);
3188         assert!(updates.update_fee.is_none());
3189         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3190         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3191         check_added_monitors!(nodes[1], 1);
3192         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3193         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3194         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3195         check_added_monitors!(nodes[2], 1);
3196
3197         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3198         expect_pending_htlcs_forwardable!(nodes[2]);
3199         check_added_monitors!(nodes[2], 1);
3200         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3201         assert!(updates.update_add_htlcs.is_empty());
3202         assert!(updates.update_fulfill_htlcs.is_empty());
3203         assert!(updates.update_fail_malformed_htlcs.is_empty());
3204         assert_eq!(updates.update_fail_htlcs.len(), 1);
3205         assert!(updates.update_fee.is_none());
3206         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3207         // At this point first_payment_hash has dropped out of the latest two commitment
3208         // transactions that nodes[1] is tracking...
3209         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3210         check_added_monitors!(nodes[1], 1);
3211         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3212         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3213         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3214         check_added_monitors!(nodes[2], 1);
3215
3216         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3217         // on nodes[2]'s RAA.
3218         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3219         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3220         let logger = test_utils::TestLogger::new();
3221         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();
3222         nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3223         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3224         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3225         check_added_monitors!(nodes[1], 0);
3226
3227         if deliver_bs_raa {
3228                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3229                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3230                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3231                 check_added_monitors!(nodes[1], 1);
3232                 let events = nodes[1].node.get_and_clear_pending_events();
3233                 assert_eq!(events.len(), 1);
3234                 match events[0] {
3235                         Event::PendingHTLCsForwardable { .. } => { },
3236                         _ => panic!("Unexpected event"),
3237                 };
3238                 // Deliberately don't process the pending fail-back so they all fail back at once after
3239                 // block connection just like the !deliver_bs_raa case
3240         }
3241
3242         let mut failed_htlcs = HashSet::new();
3243         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3244
3245         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3246         check_added_monitors!(nodes[1], 1);
3247         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3248
3249         let events = nodes[1].node.get_and_clear_pending_events();
3250         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3251         match events[0] {
3252                 Event::PaymentFailed { ref payment_hash, .. } => {
3253                         assert_eq!(*payment_hash, fourth_payment_hash);
3254                 },
3255                 _ => panic!("Unexpected event"),
3256         }
3257         if !deliver_bs_raa {
3258                 match events[1] {
3259                         Event::PendingHTLCsForwardable { .. } => { },
3260                         _ => panic!("Unexpected event"),
3261                 };
3262         }
3263         nodes[1].node.process_pending_htlc_forwards();
3264         check_added_monitors!(nodes[1], 1);
3265
3266         let events = nodes[1].node.get_and_clear_pending_msg_events();
3267         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3268         match events[if deliver_bs_raa { 1 } else { 0 }] {
3269                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3270                 _ => panic!("Unexpected event"),
3271         }
3272         match events[if deliver_bs_raa { 2 } else { 1 }] {
3273                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3274                         assert_eq!(channel_id, chan_2.2);
3275                         assert_eq!(data.as_str(), "Commitment or closing transaction was confirmed on chain.");
3276                 },
3277                 _ => panic!("Unexpected event"),
3278         }
3279         if deliver_bs_raa {
3280                 match events[0] {
3281                         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, .. } } => {
3282                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3283                                 assert_eq!(update_add_htlcs.len(), 1);
3284                                 assert!(update_fulfill_htlcs.is_empty());
3285                                 assert!(update_fail_htlcs.is_empty());
3286                                 assert!(update_fail_malformed_htlcs.is_empty());
3287                         },
3288                         _ => panic!("Unexpected event"),
3289                 }
3290         }
3291         match events[if deliver_bs_raa { 3 } else { 2 }] {
3292                 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, .. } } => {
3293                         assert!(update_add_htlcs.is_empty());
3294                         assert_eq!(update_fail_htlcs.len(), 3);
3295                         assert!(update_fulfill_htlcs.is_empty());
3296                         assert!(update_fail_malformed_htlcs.is_empty());
3297                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3298
3299                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3300                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3301                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3302
3303                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3304
3305                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3306                         // If we delivered B's RAA we got an unknown preimage error, not something
3307                         // that we should update our routing table for.
3308                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3309                         for event in events {
3310                                 match event {
3311                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3312                                         _ => panic!("Unexpected event"),
3313                                 }
3314                         }
3315                         let events = nodes[0].node.get_and_clear_pending_events();
3316                         assert_eq!(events.len(), 3);
3317                         match events[0] {
3318                                 Event::PaymentFailed { ref payment_hash, .. } => {
3319                                         assert!(failed_htlcs.insert(payment_hash.0));
3320                                 },
3321                                 _ => panic!("Unexpected event"),
3322                         }
3323                         match events[1] {
3324                                 Event::PaymentFailed { ref payment_hash, .. } => {
3325                                         assert!(failed_htlcs.insert(payment_hash.0));
3326                                 },
3327                                 _ => panic!("Unexpected event"),
3328                         }
3329                         match events[2] {
3330                                 Event::PaymentFailed { ref payment_hash, .. } => {
3331                                         assert!(failed_htlcs.insert(payment_hash.0));
3332                                 },
3333                                 _ => panic!("Unexpected event"),
3334                         }
3335                 },
3336                 _ => panic!("Unexpected event"),
3337         }
3338
3339         assert!(failed_htlcs.contains(&first_payment_hash.0));
3340         assert!(failed_htlcs.contains(&second_payment_hash.0));
3341         assert!(failed_htlcs.contains(&third_payment_hash.0));
3342 }
3343
3344 #[test]
3345 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3346         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3347         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3348         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3349         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3350 }
3351
3352 #[test]
3353 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3354         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3355         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3356         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3357         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3358 }
3359
3360 #[test]
3361 fn fail_backward_pending_htlc_upon_channel_failure() {
3362         let chanmon_cfgs = create_chanmon_cfgs(2);
3363         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3364         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3365         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3366         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3367         let logger = test_utils::TestLogger::new();
3368
3369         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3370         {
3371                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3372                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3373                 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();
3374                 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3375                 check_added_monitors!(nodes[0], 1);
3376
3377                 let payment_event = {
3378                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3379                         assert_eq!(events.len(), 1);
3380                         SendEvent::from_event(events.remove(0))
3381                 };
3382                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3383                 assert_eq!(payment_event.msgs.len(), 1);
3384         }
3385
3386         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3387         let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3388         {
3389                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3390                 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();
3391                 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3392                 check_added_monitors!(nodes[0], 0);
3393
3394                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3395         }
3396
3397         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3398         {
3399                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3400
3401                 let secp_ctx = Secp256k1::new();
3402                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3403                 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3404                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3405                 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();
3406                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3407                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3408                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3409
3410                 // Send a 0-msat update_add_htlc to fail the channel.
3411                 let update_add_htlc = msgs::UpdateAddHTLC {
3412                         channel_id: chan.2,
3413                         htlc_id: 0,
3414                         amount_msat: 0,
3415                         payment_hash,
3416                         cltv_expiry,
3417                         onion_routing_packet,
3418                 };
3419                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3420         }
3421
3422         // Check that Alice fails backward the pending HTLC from the second payment.
3423         expect_payment_failed!(nodes[0], failed_payment_hash, true);
3424         check_closed_broadcast!(nodes[0], true);
3425         check_added_monitors!(nodes[0], 1);
3426 }
3427
3428 #[test]
3429 fn test_htlc_ignore_latest_remote_commitment() {
3430         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3431         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3432         let chanmon_cfgs = create_chanmon_cfgs(2);
3433         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3434         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3435         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3436         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3437
3438         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3439         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3440         check_closed_broadcast!(nodes[0], true);
3441         check_added_monitors!(nodes[0], 1);
3442
3443         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3444         assert_eq!(node_txn.len(), 2);
3445
3446         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3447         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3448         check_closed_broadcast!(nodes[1], true);
3449         check_added_monitors!(nodes[1], 1);
3450
3451         // Duplicate the connect_block call since this may happen due to other listeners
3452         // registering new transactions
3453         header.prev_blockhash = header.block_hash();
3454         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3455 }
3456
3457 #[test]
3458 fn test_force_close_fail_back() {
3459         // Check which HTLCs are failed-backwards on channel force-closure
3460         let chanmon_cfgs = create_chanmon_cfgs(3);
3461         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3462         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3463         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3464         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3465         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3466         let logger = test_utils::TestLogger::new();
3467
3468         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3469
3470         let mut payment_event = {
3471                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3472                 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();
3473                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3474                 check_added_monitors!(nodes[0], 1);
3475
3476                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3477                 assert_eq!(events.len(), 1);
3478                 SendEvent::from_event(events.remove(0))
3479         };
3480
3481         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3482         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3483
3484         expect_pending_htlcs_forwardable!(nodes[1]);
3485
3486         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3487         assert_eq!(events_2.len(), 1);
3488         payment_event = SendEvent::from_event(events_2.remove(0));
3489         assert_eq!(payment_event.msgs.len(), 1);
3490
3491         check_added_monitors!(nodes[1], 1);
3492         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3493         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3494         check_added_monitors!(nodes[2], 1);
3495         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3496
3497         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3498         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3499         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3500
3501         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3502         check_closed_broadcast!(nodes[2], true);
3503         check_added_monitors!(nodes[2], 1);
3504         let tx = {
3505                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3506                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3507                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3508                 // back to nodes[1] upon timeout otherwise.
3509                 assert_eq!(node_txn.len(), 1);
3510                 node_txn.remove(0)
3511         };
3512
3513         mine_transaction(&nodes[1], &tx);
3514
3515         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3516         check_closed_broadcast!(nodes[1], true);
3517         check_added_monitors!(nodes[1], 1);
3518
3519         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3520         {
3521                 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3522                 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3523                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3524         }
3525         mine_transaction(&nodes[2], &tx);
3526         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3527         assert_eq!(node_txn.len(), 1);
3528         assert_eq!(node_txn[0].input.len(), 1);
3529         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3530         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3531         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3532
3533         check_spends!(node_txn[0], tx);
3534 }
3535
3536 #[test]
3537 fn test_simple_peer_disconnect() {
3538         // Test that we can reconnect when there are no lost messages
3539         let chanmon_cfgs = create_chanmon_cfgs(3);
3540         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3541         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3542         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3543         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3544         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3545
3546         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3547         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3548         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3549
3550         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3551         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3552         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3553         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
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], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3558
3559         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3560         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3561         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3562         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
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
3567         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3568         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3569
3570         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3571         {
3572                 let events = nodes[0].node.get_and_clear_pending_events();
3573                 assert_eq!(events.len(), 2);
3574                 match events[0] {
3575                         Event::PaymentSent { payment_preimage } => {
3576                                 assert_eq!(payment_preimage, payment_preimage_3);
3577                         },
3578                         _ => panic!("Unexpected event"),
3579                 }
3580                 match events[1] {
3581                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3582                                 assert_eq!(payment_hash, payment_hash_5);
3583                                 assert!(rejected_by_dest);
3584                         },
3585                         _ => panic!("Unexpected event"),
3586                 }
3587         }
3588
3589         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3590         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3591 }
3592
3593 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3594         // Test that we can reconnect when in-flight HTLC updates get dropped
3595         let chanmon_cfgs = create_chanmon_cfgs(2);
3596         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3597         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3598         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3599         if messages_delivered == 0 {
3600                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3601                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3602         } else {
3603                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3604         }
3605
3606         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3607
3608         let logger = test_utils::TestLogger::new();
3609         let payment_event = {
3610                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3611                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3612                         &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3613                         &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3614                 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3615                 check_added_monitors!(nodes[0], 1);
3616
3617                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3618                 assert_eq!(events.len(), 1);
3619                 SendEvent::from_event(events.remove(0))
3620         };
3621         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3622
3623         if messages_delivered < 2 {
3624                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3625         } else {
3626                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3627                 if messages_delivered >= 3 {
3628                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3629                         check_added_monitors!(nodes[1], 1);
3630                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3631
3632                         if messages_delivered >= 4 {
3633                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3634                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3635                                 check_added_monitors!(nodes[0], 1);
3636
3637                                 if messages_delivered >= 5 {
3638                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3639                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3640                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3641                                         check_added_monitors!(nodes[0], 1);
3642
3643                                         if messages_delivered >= 6 {
3644                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3645                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3646                                                 check_added_monitors!(nodes[1], 1);
3647                                         }
3648                                 }
3649                         }
3650                 }
3651         }
3652
3653         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3654         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3655         if messages_delivered < 3 {
3656                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3657                 // received on either side, both sides will need to resend them.
3658                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3659         } else if messages_delivered == 3 {
3660                 // nodes[0] still wants its RAA + commitment_signed
3661                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3662         } else if messages_delivered == 4 {
3663                 // nodes[0] still wants its commitment_signed
3664                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3665         } else if messages_delivered == 5 {
3666                 // nodes[1] still wants its final RAA
3667                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3668         } else if messages_delivered == 6 {
3669                 // Everything was delivered...
3670                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3671         }
3672
3673         let events_1 = nodes[1].node.get_and_clear_pending_events();
3674         assert_eq!(events_1.len(), 1);
3675         match events_1[0] {
3676                 Event::PendingHTLCsForwardable { .. } => { },
3677                 _ => panic!("Unexpected event"),
3678         };
3679
3680         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3681         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3682         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3683
3684         nodes[1].node.process_pending_htlc_forwards();
3685
3686         let events_2 = nodes[1].node.get_and_clear_pending_events();
3687         assert_eq!(events_2.len(), 1);
3688         match events_2[0] {
3689                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3690                         assert_eq!(payment_hash_1, *payment_hash);
3691                         assert_eq!(*payment_secret, None);
3692                         assert_eq!(amt, 1000000);
3693                 },
3694                 _ => panic!("Unexpected event"),
3695         }
3696
3697         nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3698         check_added_monitors!(nodes[1], 1);
3699
3700         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3701         assert_eq!(events_3.len(), 1);
3702         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3703                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3704                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3705                         assert!(updates.update_add_htlcs.is_empty());
3706                         assert!(updates.update_fail_htlcs.is_empty());
3707                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3708                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3709                         assert!(updates.update_fee.is_none());
3710                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3711                 },
3712                 _ => panic!("Unexpected event"),
3713         };
3714
3715         if messages_delivered >= 1 {
3716                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3717
3718                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3719                 assert_eq!(events_4.len(), 1);
3720                 match events_4[0] {
3721                         Event::PaymentSent { ref payment_preimage } => {
3722                                 assert_eq!(payment_preimage_1, *payment_preimage);
3723                         },
3724                         _ => panic!("Unexpected event"),
3725                 }
3726
3727                 if messages_delivered >= 2 {
3728                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3729                         check_added_monitors!(nodes[0], 1);
3730                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3731
3732                         if messages_delivered >= 3 {
3733                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3734                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3735                                 check_added_monitors!(nodes[1], 1);
3736
3737                                 if messages_delivered >= 4 {
3738                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3739                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3740                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3741                                         check_added_monitors!(nodes[1], 1);
3742
3743                                         if messages_delivered >= 5 {
3744                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3745                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3746                                                 check_added_monitors!(nodes[0], 1);
3747                                         }
3748                                 }
3749                         }
3750                 }
3751         }
3752
3753         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3754         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3755         if messages_delivered < 2 {
3756                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3757                 //TODO: Deduplicate PaymentSent events, then enable this if:
3758                 //if messages_delivered < 1 {
3759                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3760                         assert_eq!(events_4.len(), 1);
3761                         match events_4[0] {
3762                                 Event::PaymentSent { ref payment_preimage } => {
3763                                         assert_eq!(payment_preimage_1, *payment_preimage);
3764                                 },
3765                                 _ => panic!("Unexpected event"),
3766                         }
3767                 //}
3768         } else if messages_delivered == 2 {
3769                 // nodes[0] still wants its RAA + commitment_signed
3770                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3771         } else if messages_delivered == 3 {
3772                 // nodes[0] still wants its commitment_signed
3773                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3774         } else if messages_delivered == 4 {
3775                 // nodes[1] still wants its final RAA
3776                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3777         } else if messages_delivered == 5 {
3778                 // Everything was delivered...
3779                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3780         }
3781
3782         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3783         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3784         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3785
3786         // Channel should still work fine...
3787         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3788         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3789                 &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3790                 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3791         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3792         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3793 }
3794
3795 #[test]
3796 fn test_drop_messages_peer_disconnect_a() {
3797         do_test_drop_messages_peer_disconnect(0);
3798         do_test_drop_messages_peer_disconnect(1);
3799         do_test_drop_messages_peer_disconnect(2);
3800         do_test_drop_messages_peer_disconnect(3);
3801 }
3802
3803 #[test]
3804 fn test_drop_messages_peer_disconnect_b() {
3805         do_test_drop_messages_peer_disconnect(4);
3806         do_test_drop_messages_peer_disconnect(5);
3807         do_test_drop_messages_peer_disconnect(6);
3808 }
3809
3810 #[test]
3811 fn test_funding_peer_disconnect() {
3812         // Test that we can lock in our funding tx while disconnected
3813         let chanmon_cfgs = create_chanmon_cfgs(2);
3814         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3815         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3816         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3817         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3818
3819         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3820         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3821
3822         confirm_transaction(&nodes[0], &tx);
3823         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3824         assert_eq!(events_1.len(), 1);
3825         match events_1[0] {
3826                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3827                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3828                 },
3829                 _ => panic!("Unexpected event"),
3830         }
3831
3832         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3833
3834         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3835         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3836
3837         confirm_transaction(&nodes[1], &tx);
3838         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3839         assert_eq!(events_2.len(), 2);
3840         let funding_locked = match events_2[0] {
3841                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3842                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3843                         msg.clone()
3844                 },
3845                 _ => panic!("Unexpected event"),
3846         };
3847         let bs_announcement_sigs = match events_2[1] {
3848                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3849                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3850                         msg.clone()
3851                 },
3852                 _ => panic!("Unexpected event"),
3853         };
3854
3855         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3856
3857         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3858         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3859         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3860         assert_eq!(events_3.len(), 2);
3861         let as_announcement_sigs = match events_3[0] {
3862                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3863                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3864                         msg.clone()
3865                 },
3866                 _ => panic!("Unexpected event"),
3867         };
3868         let (as_announcement, as_update) = match events_3[1] {
3869                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3870                         (msg.clone(), update_msg.clone())
3871                 },
3872                 _ => panic!("Unexpected event"),
3873         };
3874
3875         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3876         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3877         assert_eq!(events_4.len(), 1);
3878         let (_, bs_update) = match events_4[0] {
3879                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3880                         (msg.clone(), update_msg.clone())
3881                 },
3882                 _ => panic!("Unexpected event"),
3883         };
3884
3885         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3886         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3887         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3888
3889         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3890         let logger = test_utils::TestLogger::new();
3891         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();
3892         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3893         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3894 }
3895
3896 #[test]
3897 fn test_drop_messages_peer_disconnect_dual_htlc() {
3898         // Test that we can handle reconnecting when both sides of a channel have pending
3899         // commitment_updates when we disconnect.
3900         let chanmon_cfgs = create_chanmon_cfgs(2);
3901         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3902         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3903         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3904         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3905         let logger = test_utils::TestLogger::new();
3906
3907         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3908
3909         // Now try to send a second payment which will fail to send
3910         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3911         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3912         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();
3913         nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3914         check_added_monitors!(nodes[0], 1);
3915
3916         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3917         assert_eq!(events_1.len(), 1);
3918         match events_1[0] {
3919                 MessageSendEvent::UpdateHTLCs { .. } => {},
3920                 _ => panic!("Unexpected event"),
3921         }
3922
3923         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3924         check_added_monitors!(nodes[1], 1);
3925
3926         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3927         assert_eq!(events_2.len(), 1);
3928         match events_2[0] {
3929                 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 } } => {
3930                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3931                         assert!(update_add_htlcs.is_empty());
3932                         assert_eq!(update_fulfill_htlcs.len(), 1);
3933                         assert!(update_fail_htlcs.is_empty());
3934                         assert!(update_fail_malformed_htlcs.is_empty());
3935                         assert!(update_fee.is_none());
3936
3937                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3938                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3939                         assert_eq!(events_3.len(), 1);
3940                         match events_3[0] {
3941                                 Event::PaymentSent { ref payment_preimage } => {
3942                                         assert_eq!(*payment_preimage, payment_preimage_1);
3943                                 },
3944                                 _ => panic!("Unexpected event"),
3945                         }
3946
3947                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3948                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3949                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3950                         check_added_monitors!(nodes[0], 1);
3951                 },
3952                 _ => panic!("Unexpected event"),
3953         }
3954
3955         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3956         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3957
3958         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3959         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3960         assert_eq!(reestablish_1.len(), 1);
3961         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3962         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3963         assert_eq!(reestablish_2.len(), 1);
3964
3965         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3966         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3967         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3968         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3969
3970         assert!(as_resp.0.is_none());
3971         assert!(bs_resp.0.is_none());
3972
3973         assert!(bs_resp.1.is_none());
3974         assert!(bs_resp.2.is_none());
3975
3976         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3977
3978         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3979         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3980         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3981         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3982         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3983         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3984         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3985         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3986         // No commitment_signed so get_event_msg's assert(len == 1) passes
3987         check_added_monitors!(nodes[1], 1);
3988
3989         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3990         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3991         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3992         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3993         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3994         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3995         assert!(bs_second_commitment_signed.update_fee.is_none());
3996         check_added_monitors!(nodes[1], 1);
3997
3998         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3999         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4000         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4001         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4002         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4003         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4004         assert!(as_commitment_signed.update_fee.is_none());
4005         check_added_monitors!(nodes[0], 1);
4006
4007         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4008         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4009         // No commitment_signed so get_event_msg's assert(len == 1) passes
4010         check_added_monitors!(nodes[0], 1);
4011
4012         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4013         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4014         // No commitment_signed so get_event_msg's assert(len == 1) passes
4015         check_added_monitors!(nodes[1], 1);
4016
4017         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4018         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4019         check_added_monitors!(nodes[1], 1);
4020
4021         expect_pending_htlcs_forwardable!(nodes[1]);
4022
4023         let events_5 = nodes[1].node.get_and_clear_pending_events();
4024         assert_eq!(events_5.len(), 1);
4025         match events_5[0] {
4026                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4027                         assert_eq!(payment_hash_2, *payment_hash);
4028                         assert_eq!(*payment_secret, None);
4029                 },
4030                 _ => panic!("Unexpected event"),
4031         }
4032
4033         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4034         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4035         check_added_monitors!(nodes[0], 1);
4036
4037         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4038 }
4039
4040 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4041         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4042         // to avoid our counterparty failing the channel.
4043         let chanmon_cfgs = create_chanmon_cfgs(2);
4044         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4045         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4046         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4047
4048         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4049         let logger = test_utils::TestLogger::new();
4050
4051         let our_payment_hash = if send_partial_mpp {
4052                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4053                 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();
4054                 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4055                 let payment_secret = PaymentSecret([0xdb; 32]);
4056                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4057                 // indicates there are more HTLCs coming.
4058                 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.
4059                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height).unwrap();
4060                 check_added_monitors!(nodes[0], 1);
4061                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4062                 assert_eq!(events.len(), 1);
4063                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4064                 // hop should *not* yet generate any PaymentReceived event(s).
4065                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4066                 our_payment_hash
4067         } else {
4068                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4069         };
4070
4071         let mut block = Block {
4072                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4073                 txdata: vec![],
4074         };
4075         connect_block(&nodes[0], &block);
4076         connect_block(&nodes[1], &block);
4077         for _ in CHAN_CONFIRM_DEPTH + 2 ..TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4078                 block.header.prev_blockhash = block.block_hash();
4079                 connect_block(&nodes[0], &block);
4080                 connect_block(&nodes[1], &block);
4081         }
4082
4083         expect_pending_htlcs_forwardable!(nodes[1]);
4084
4085         check_added_monitors!(nodes[1], 1);
4086         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4087         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4088         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4089         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4090         assert!(htlc_timeout_updates.update_fee.is_none());
4091
4092         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4093         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4094         // 100_000 msat as u64, followed by a height of TEST_FINAL_CLTV + 2 as u32
4095         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4096         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(TEST_FINAL_CLTV + 2));
4097         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4098 }
4099
4100 #[test]
4101 fn test_htlc_timeout() {
4102         do_test_htlc_timeout(true);
4103         do_test_htlc_timeout(false);
4104 }
4105
4106 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4107         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4108         let chanmon_cfgs = create_chanmon_cfgs(3);
4109         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4110         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4111         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4112         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4113         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4114
4115         // Make sure all nodes are at the same starting height
4116         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4117         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4118         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4119
4120         let logger = test_utils::TestLogger::new();
4121
4122         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4123         let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4124         {
4125                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4126                 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();
4127                 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4128         }
4129         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4130         check_added_monitors!(nodes[1], 1);
4131
4132         // Now attempt to route a second payment, which should be placed in the holding cell
4133         let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4134         if forwarded_htlc {
4135                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4136                 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();
4137                 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4138                 check_added_monitors!(nodes[0], 1);
4139                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4140                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4141                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4142                 expect_pending_htlcs_forwardable!(nodes[1]);
4143                 check_added_monitors!(nodes[1], 0);
4144         } else {
4145                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4146                 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();
4147                 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4148                 check_added_monitors!(nodes[1], 0);
4149         }
4150
4151         connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4152         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4153         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4154         connect_blocks(&nodes[1], 1);
4155
4156         if forwarded_htlc {
4157                 expect_pending_htlcs_forwardable!(nodes[1]);
4158                 check_added_monitors!(nodes[1], 1);
4159                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4160                 assert_eq!(fail_commit.len(), 1);
4161                 match fail_commit[0] {
4162                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4163                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4164                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4165                         },
4166                         _ => unreachable!(),
4167                 }
4168                 expect_payment_failed!(nodes[0], second_payment_hash, false);
4169                 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4170                         match update {
4171                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4172                                 _ => panic!("Unexpected event"),
4173                         }
4174                 } else {
4175                         panic!("Unexpected event");
4176                 }
4177         } else {
4178                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4179         }
4180 }
4181
4182 #[test]
4183 fn test_holding_cell_htlc_add_timeouts() {
4184         do_test_holding_cell_htlc_add_timeouts(false);
4185         do_test_holding_cell_htlc_add_timeouts(true);
4186 }
4187
4188 #[test]
4189 fn test_invalid_channel_announcement() {
4190         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4191         let secp_ctx = Secp256k1::new();
4192         let chanmon_cfgs = create_chanmon_cfgs(2);
4193         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4194         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4195         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4196
4197         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4198
4199         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4200         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4201         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4202         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4203
4204         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 } );
4205
4206         let as_bitcoin_key = as_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4207         let bs_bitcoin_key = bs_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4208
4209         let as_network_key = nodes[0].node.get_our_node_id();
4210         let bs_network_key = nodes[1].node.get_our_node_id();
4211
4212         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4213
4214         let mut chan_announcement;
4215
4216         macro_rules! dummy_unsigned_msg {
4217                 () => {
4218                         msgs::UnsignedChannelAnnouncement {
4219                                 features: ChannelFeatures::known(),
4220                                 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4221                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4222                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4223                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4224                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4225                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4226                                 excess_data: Vec::new(),
4227                         };
4228                 }
4229         }
4230
4231         macro_rules! sign_msg {
4232                 ($unsigned_msg: expr) => {
4233                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4234                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_signer().inner.funding_key);
4235                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_signer().inner.funding_key);
4236                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4237                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4238                         chan_announcement = msgs::ChannelAnnouncement {
4239                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4240                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4241                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4242                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4243                                 contents: $unsigned_msg
4244                         }
4245                 }
4246         }
4247
4248         let unsigned_msg = dummy_unsigned_msg!();
4249         sign_msg!(unsigned_msg);
4250         assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4251         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 } );
4252
4253         // Configured with Network::Testnet
4254         let mut unsigned_msg = dummy_unsigned_msg!();
4255         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4256         sign_msg!(unsigned_msg);
4257         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4258
4259         let mut unsigned_msg = dummy_unsigned_msg!();
4260         unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4261         sign_msg!(unsigned_msg);
4262         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4263 }
4264
4265 #[test]
4266 fn test_no_txn_manager_serialize_deserialize() {
4267         let chanmon_cfgs = create_chanmon_cfgs(2);
4268         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4269         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4270         let logger: test_utils::TestLogger;
4271         let fee_estimator: test_utils::TestFeeEstimator;
4272         let persister: test_utils::TestPersister;
4273         let new_chain_monitor: test_utils::TestChainMonitor;
4274         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4275         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4276
4277         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4278
4279         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4280
4281         let nodes_0_serialized = nodes[0].node.encode();
4282         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4283         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4284
4285         logger = test_utils::TestLogger::new();
4286         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4287         persister = test_utils::TestPersister::new();
4288         let keys_manager = &chanmon_cfgs[0].keys_manager;
4289         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4290         nodes[0].chain_monitor = &new_chain_monitor;
4291         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4292         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4293                 &mut chan_0_monitor_read, keys_manager).unwrap();
4294         assert!(chan_0_monitor_read.is_empty());
4295
4296         let mut nodes_0_read = &nodes_0_serialized[..];
4297         let config = UserConfig::default();
4298         let (_, nodes_0_deserialized_tmp) = {
4299                 let mut channel_monitors = HashMap::new();
4300                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4301                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4302                         default_config: config,
4303                         keys_manager,
4304                         fee_estimator: &fee_estimator,
4305                         chain_monitor: nodes[0].chain_monitor,
4306                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4307                         logger: &logger,
4308                         channel_monitors,
4309                 }).unwrap()
4310         };
4311         nodes_0_deserialized = nodes_0_deserialized_tmp;
4312         assert!(nodes_0_read.is_empty());
4313
4314         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4315         nodes[0].node = &nodes_0_deserialized;
4316         assert_eq!(nodes[0].node.list_channels().len(), 1);
4317         check_added_monitors!(nodes[0], 1);
4318
4319         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4320         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4321         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4322         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4323
4324         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4325         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4326         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4327         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4328
4329         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4330         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4331         for node in nodes.iter() {
4332                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4333                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4334                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4335         }
4336
4337         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4338 }
4339
4340 #[test]
4341 fn test_manager_serialize_deserialize_events() {
4342         // This test makes sure the events field in ChannelManager survives de/serialization
4343         let chanmon_cfgs = create_chanmon_cfgs(2);
4344         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4345         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4346         let fee_estimator: test_utils::TestFeeEstimator;
4347         let persister: test_utils::TestPersister;
4348         let logger: test_utils::TestLogger;
4349         let new_chain_monitor: test_utils::TestChainMonitor;
4350         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4351         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4352
4353         // Start creating a channel, but stop right before broadcasting the funding transaction
4354         let channel_value = 100000;
4355         let push_msat = 10001;
4356         let a_flags = InitFeatures::known();
4357         let b_flags = InitFeatures::known();
4358         let node_a = nodes.remove(0);
4359         let node_b = nodes.remove(0);
4360         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4361         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()));
4362         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()));
4363
4364         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4365
4366         node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4367         check_added_monitors!(node_a, 0);
4368
4369         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()));
4370         {
4371                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4372                 assert_eq!(added_monitors.len(), 1);
4373                 assert_eq!(added_monitors[0].0, funding_output);
4374                 added_monitors.clear();
4375         }
4376
4377         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()));
4378         {
4379                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4380                 assert_eq!(added_monitors.len(), 1);
4381                 assert_eq!(added_monitors[0].0, funding_output);
4382                 added_monitors.clear();
4383         }
4384         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4385
4386         nodes.push(node_a);
4387         nodes.push(node_b);
4388
4389         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4390         let nodes_0_serialized = nodes[0].node.encode();
4391         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4392         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4393
4394         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4395         logger = test_utils::TestLogger::new();
4396         persister = test_utils::TestPersister::new();
4397         let keys_manager = &chanmon_cfgs[0].keys_manager;
4398         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4399         nodes[0].chain_monitor = &new_chain_monitor;
4400         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4401         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4402                 &mut chan_0_monitor_read, keys_manager).unwrap();
4403         assert!(chan_0_monitor_read.is_empty());
4404
4405         let mut nodes_0_read = &nodes_0_serialized[..];
4406         let config = UserConfig::default();
4407         let (_, nodes_0_deserialized_tmp) = {
4408                 let mut channel_monitors = HashMap::new();
4409                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4410                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4411                         default_config: config,
4412                         keys_manager,
4413                         fee_estimator: &fee_estimator,
4414                         chain_monitor: nodes[0].chain_monitor,
4415                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4416                         logger: &logger,
4417                         channel_monitors,
4418                 }).unwrap()
4419         };
4420         nodes_0_deserialized = nodes_0_deserialized_tmp;
4421         assert!(nodes_0_read.is_empty());
4422
4423         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4424
4425         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4426         nodes[0].node = &nodes_0_deserialized;
4427
4428         // After deserializing, make sure the funding_transaction is still held by the channel manager
4429         let events_4 = nodes[0].node.get_and_clear_pending_events();
4430         assert_eq!(events_4.len(), 0);
4431         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4432         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4433
4434         // Make sure the channel is functioning as though the de/serialization never happened
4435         assert_eq!(nodes[0].node.list_channels().len(), 1);
4436         check_added_monitors!(nodes[0], 1);
4437
4438         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4439         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4440         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4441         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4442
4443         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4444         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4445         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4446         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4447
4448         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4449         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4450         for node in nodes.iter() {
4451                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4452                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4453                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4454         }
4455
4456         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4457 }
4458
4459 #[test]
4460 fn test_simple_manager_serialize_deserialize() {
4461         let chanmon_cfgs = create_chanmon_cfgs(2);
4462         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4463         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4464         let logger: test_utils::TestLogger;
4465         let fee_estimator: test_utils::TestFeeEstimator;
4466         let persister: test_utils::TestPersister;
4467         let new_chain_monitor: test_utils::TestChainMonitor;
4468         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4469         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4470         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4471
4472         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4473         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4474
4475         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4476
4477         let nodes_0_serialized = nodes[0].node.encode();
4478         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4479         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4480
4481         logger = test_utils::TestLogger::new();
4482         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4483         persister = test_utils::TestPersister::new();
4484         let keys_manager = &chanmon_cfgs[0].keys_manager;
4485         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4486         nodes[0].chain_monitor = &new_chain_monitor;
4487         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4488         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4489                 &mut chan_0_monitor_read, keys_manager).unwrap();
4490         assert!(chan_0_monitor_read.is_empty());
4491
4492         let mut nodes_0_read = &nodes_0_serialized[..];
4493         let (_, nodes_0_deserialized_tmp) = {
4494                 let mut channel_monitors = HashMap::new();
4495                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4496                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4497                         default_config: UserConfig::default(),
4498                         keys_manager,
4499                         fee_estimator: &fee_estimator,
4500                         chain_monitor: nodes[0].chain_monitor,
4501                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4502                         logger: &logger,
4503                         channel_monitors,
4504                 }).unwrap()
4505         };
4506         nodes_0_deserialized = nodes_0_deserialized_tmp;
4507         assert!(nodes_0_read.is_empty());
4508
4509         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4510         nodes[0].node = &nodes_0_deserialized;
4511         check_added_monitors!(nodes[0], 1);
4512
4513         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4514
4515         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4516         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4517 }
4518
4519 #[test]
4520 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4521         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4522         let chanmon_cfgs = create_chanmon_cfgs(4);
4523         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4524         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4525         let logger: test_utils::TestLogger;
4526         let fee_estimator: test_utils::TestFeeEstimator;
4527         let persister: test_utils::TestPersister;
4528         let new_chain_monitor: test_utils::TestChainMonitor;
4529         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4530         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4531         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4532         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4533         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4534
4535         let mut node_0_stale_monitors_serialized = Vec::new();
4536         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4537                 let mut writer = test_utils::TestVecWriter(Vec::new());
4538                 monitor.1.write(&mut writer).unwrap();
4539                 node_0_stale_monitors_serialized.push(writer.0);
4540         }
4541
4542         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4543
4544         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4545         let nodes_0_serialized = nodes[0].node.encode();
4546
4547         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4548         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4549         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4550         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4551
4552         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4553         // nodes[3])
4554         let mut node_0_monitors_serialized = Vec::new();
4555         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4556                 let mut writer = test_utils::TestVecWriter(Vec::new());
4557                 monitor.1.write(&mut writer).unwrap();
4558                 node_0_monitors_serialized.push(writer.0);
4559         }
4560
4561         logger = test_utils::TestLogger::new();
4562         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4563         persister = test_utils::TestPersister::new();
4564         let keys_manager = &chanmon_cfgs[0].keys_manager;
4565         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4566         nodes[0].chain_monitor = &new_chain_monitor;
4567
4568
4569         let mut node_0_stale_monitors = Vec::new();
4570         for serialized in node_0_stale_monitors_serialized.iter() {
4571                 let mut read = &serialized[..];
4572                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4573                 assert!(read.is_empty());
4574                 node_0_stale_monitors.push(monitor);
4575         }
4576
4577         let mut node_0_monitors = Vec::new();
4578         for serialized in node_0_monitors_serialized.iter() {
4579                 let mut read = &serialized[..];
4580                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4581                 assert!(read.is_empty());
4582                 node_0_monitors.push(monitor);
4583         }
4584
4585         let mut nodes_0_read = &nodes_0_serialized[..];
4586         if let Err(msgs::DecodeError::InvalidValue) =
4587                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4588                 default_config: UserConfig::default(),
4589                 keys_manager,
4590                 fee_estimator: &fee_estimator,
4591                 chain_monitor: nodes[0].chain_monitor,
4592                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4593                 logger: &logger,
4594                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4595         }) { } else {
4596                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4597         };
4598
4599         let mut nodes_0_read = &nodes_0_serialized[..];
4600         let (_, nodes_0_deserialized_tmp) =
4601                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4602                 default_config: UserConfig::default(),
4603                 keys_manager,
4604                 fee_estimator: &fee_estimator,
4605                 chain_monitor: nodes[0].chain_monitor,
4606                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4607                 logger: &logger,
4608                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4609         }).unwrap();
4610         nodes_0_deserialized = nodes_0_deserialized_tmp;
4611         assert!(nodes_0_read.is_empty());
4612
4613         { // Channel close should result in a commitment tx and an HTLC tx
4614                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4615                 assert_eq!(txn.len(), 2);
4616                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4617                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4618         }
4619
4620         for monitor in node_0_monitors.drain(..) {
4621                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4622                 check_added_monitors!(nodes[0], 1);
4623         }
4624         nodes[0].node = &nodes_0_deserialized;
4625
4626         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4627         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4628         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4629         //... and we can even still claim the payment!
4630         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4631
4632         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4633         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4634         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4635         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4636         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4637         assert_eq!(msg_events.len(), 1);
4638         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4639                 match action {
4640                         &ErrorAction::SendErrorMessage { ref msg } => {
4641                                 assert_eq!(msg.channel_id, channel_id);
4642                         },
4643                         _ => panic!("Unexpected event!"),
4644                 }
4645         }
4646 }
4647
4648 macro_rules! check_spendable_outputs {
4649         ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4650                 {
4651                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4652                         let mut txn = Vec::new();
4653                         let mut all_outputs = Vec::new();
4654                         let secp_ctx = Secp256k1::new();
4655                         for event in events.drain(..) {
4656                                 match event {
4657                                         Event::SpendableOutputs { mut outputs } => {
4658                                                 for outp in outputs.drain(..) {
4659                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4660                                                         all_outputs.push(outp);
4661                                                 }
4662                                         },
4663                                         _ => panic!("Unexpected event"),
4664                                 };
4665                         }
4666                         if all_outputs.len() > 1 {
4667                                 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) {
4668                                         txn.push(tx);
4669                                 }
4670                         }
4671                         txn
4672                 }
4673         }
4674 }
4675
4676 #[test]
4677 fn test_claim_sizeable_push_msat() {
4678         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4679         let chanmon_cfgs = create_chanmon_cfgs(2);
4680         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4681         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4682         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4683
4684         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4685         nodes[1].node.force_close_channel(&chan.2).unwrap();
4686         check_closed_broadcast!(nodes[1], true);
4687         check_added_monitors!(nodes[1], 1);
4688         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4689         assert_eq!(node_txn.len(), 1);
4690         check_spends!(node_txn[0], chan.3);
4691         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
4692
4693         mine_transaction(&nodes[1], &node_txn[0]);
4694         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4695
4696         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4697         assert_eq!(spend_txn.len(), 1);
4698         check_spends!(spend_txn[0], node_txn[0]);
4699 }
4700
4701 #[test]
4702 fn test_claim_on_remote_sizeable_push_msat() {
4703         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4704         // to_remote output is encumbered by a P2WPKH
4705         let chanmon_cfgs = create_chanmon_cfgs(2);
4706         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4707         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4708         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4709
4710         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4711         nodes[0].node.force_close_channel(&chan.2).unwrap();
4712         check_closed_broadcast!(nodes[0], true);
4713         check_added_monitors!(nodes[0], 1);
4714
4715         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4716         assert_eq!(node_txn.len(), 1);
4717         check_spends!(node_txn[0], chan.3);
4718         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
4719
4720         mine_transaction(&nodes[1], &node_txn[0]);
4721         check_closed_broadcast!(nodes[1], true);
4722         check_added_monitors!(nodes[1], 1);
4723         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4724
4725         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4726         assert_eq!(spend_txn.len(), 1);
4727         check_spends!(spend_txn[0], node_txn[0]);
4728 }
4729
4730 #[test]
4731 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4732         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4733         // to_remote output is encumbered by a P2WPKH
4734
4735         let chanmon_cfgs = create_chanmon_cfgs(2);
4736         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4737         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4738         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4739
4740         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4741         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4742         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4743         assert_eq!(revoked_local_txn[0].input.len(), 1);
4744         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4745
4746         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4747         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4748         check_closed_broadcast!(nodes[1], true);
4749         check_added_monitors!(nodes[1], 1);
4750
4751         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4752         mine_transaction(&nodes[1], &node_txn[0]);
4753         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4754
4755         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4756         assert_eq!(spend_txn.len(), 3);
4757         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4758         check_spends!(spend_txn[1], node_txn[0]);
4759         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4760 }
4761
4762 #[test]
4763 fn test_static_spendable_outputs_preimage_tx() {
4764         let chanmon_cfgs = create_chanmon_cfgs(2);
4765         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4766         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4767         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4768
4769         // Create some initial channels
4770         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4771
4772         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4773
4774         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4775         assert_eq!(commitment_tx[0].input.len(), 1);
4776         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4777
4778         // Settle A's commitment tx on B's chain
4779         assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4780         check_added_monitors!(nodes[1], 1);
4781         mine_transaction(&nodes[1], &commitment_tx[0]);
4782         check_added_monitors!(nodes[1], 1);
4783         let events = nodes[1].node.get_and_clear_pending_msg_events();
4784         match events[0] {
4785                 MessageSendEvent::UpdateHTLCs { .. } => {},
4786                 _ => panic!("Unexpected event"),
4787         }
4788         match events[1] {
4789                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4790                 _ => panic!("Unexepected event"),
4791         }
4792
4793         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4794         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4795         assert_eq!(node_txn.len(), 3);
4796         check_spends!(node_txn[0], commitment_tx[0]);
4797         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4798         check_spends!(node_txn[1], chan_1.3);
4799         check_spends!(node_txn[2], node_txn[1]);
4800
4801         mine_transaction(&nodes[1], &node_txn[0]);
4802         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4803
4804         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4805         assert_eq!(spend_txn.len(), 1);
4806         check_spends!(spend_txn[0], node_txn[0]);
4807 }
4808
4809 #[test]
4810 fn test_static_spendable_outputs_timeout_tx() {
4811         let chanmon_cfgs = create_chanmon_cfgs(2);
4812         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4813         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4814         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4815
4816         // Create some initial channels
4817         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4818
4819         // Rebalance the network a bit by relaying one payment through all the channels ...
4820         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4821
4822         let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4823
4824         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4825         assert_eq!(commitment_tx[0].input.len(), 1);
4826         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4827
4828         // Settle A's commitment tx on B' chain
4829         mine_transaction(&nodes[1], &commitment_tx[0]);
4830         check_added_monitors!(nodes[1], 1);
4831         let events = nodes[1].node.get_and_clear_pending_msg_events();
4832         match events[0] {
4833                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4834                 _ => panic!("Unexpected event"),
4835         }
4836
4837         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4838         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4839         assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4840         check_spends!(node_txn[0],  commitment_tx[0].clone());
4841         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4842         check_spends!(node_txn[1], chan_1.3.clone());
4843         check_spends!(node_txn[2], node_txn[1]);
4844
4845         mine_transaction(&nodes[1], &node_txn[0]);
4846         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4847         expect_payment_failed!(nodes[1], our_payment_hash, true);
4848
4849         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4850         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4851         check_spends!(spend_txn[0], commitment_tx[0]);
4852         check_spends!(spend_txn[1], node_txn[0]);
4853         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4854 }
4855
4856 #[test]
4857 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4858         let chanmon_cfgs = create_chanmon_cfgs(2);
4859         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4860         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4861         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4862
4863         // Create some initial channels
4864         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4865
4866         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4867         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4868         assert_eq!(revoked_local_txn[0].input.len(), 1);
4869         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4870
4871         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4872
4873         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4874         check_closed_broadcast!(nodes[1], true);
4875         check_added_monitors!(nodes[1], 1);
4876
4877         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4878         assert_eq!(node_txn.len(), 2);
4879         assert_eq!(node_txn[0].input.len(), 2);
4880         check_spends!(node_txn[0], revoked_local_txn[0]);
4881
4882         mine_transaction(&nodes[1], &node_txn[0]);
4883         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4884
4885         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4886         assert_eq!(spend_txn.len(), 1);
4887         check_spends!(spend_txn[0], node_txn[0]);
4888 }
4889
4890 #[test]
4891 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4892         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4893         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4894         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4895         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4896         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4897
4898         // Create some initial channels
4899         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4900
4901         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4902         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4903         assert_eq!(revoked_local_txn[0].input.len(), 1);
4904         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4905
4906         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4907
4908         // A will generate HTLC-Timeout from revoked commitment tx
4909         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4910         check_closed_broadcast!(nodes[0], true);
4911         check_added_monitors!(nodes[0], 1);
4912
4913         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4914         assert_eq!(revoked_htlc_txn.len(), 2);
4915         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4916         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4917         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4918         check_spends!(revoked_htlc_txn[1], chan_1.3);
4919
4920         // B will generate justice tx from A's revoked commitment/HTLC tx
4921         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4922         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4923         check_closed_broadcast!(nodes[1], true);
4924         check_added_monitors!(nodes[1], 1);
4925
4926         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4927         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4928         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4929         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4930         // transactions next...
4931         assert_eq!(node_txn[0].input.len(), 3);
4932         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4933
4934         assert_eq!(node_txn[1].input.len(), 2);
4935         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4936         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4937                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4938         } else {
4939                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4940                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4941         }
4942
4943         assert_eq!(node_txn[2].input.len(), 1);
4944         check_spends!(node_txn[2], chan_1.3);
4945
4946         mine_transaction(&nodes[1], &node_txn[1]);
4947         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4948
4949         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4950         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4951         assert_eq!(spend_txn.len(), 1);
4952         assert_eq!(spend_txn[0].input.len(), 1);
4953         check_spends!(spend_txn[0], node_txn[1]);
4954 }
4955
4956 #[test]
4957 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4958         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4959         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4960         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4961         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4962         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4963
4964         // Create some initial channels
4965         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4966
4967         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4968         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4969         assert_eq!(revoked_local_txn[0].input.len(), 1);
4970         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4971
4972         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4973         assert_eq!(revoked_local_txn[0].output.len(), 2);
4974
4975         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4976
4977         // B will generate HTLC-Success from revoked commitment tx
4978         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4979         check_closed_broadcast!(nodes[1], true);
4980         check_added_monitors!(nodes[1], 1);
4981         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4982
4983         assert_eq!(revoked_htlc_txn.len(), 2);
4984         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4985         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4986         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4987
4988         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4989         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4990         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4991
4992         // A will generate justice tx from B's revoked commitment/HTLC tx
4993         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4994         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4995         check_closed_broadcast!(nodes[0], true);
4996         check_added_monitors!(nodes[0], 1);
4997
4998         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4999         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5000
5001         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5002         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5003         // transactions next...
5004         assert_eq!(node_txn[0].input.len(), 2);
5005         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5006         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5007                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5008         } else {
5009                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5010                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5011         }
5012
5013         assert_eq!(node_txn[1].input.len(), 1);
5014         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5015
5016         check_spends!(node_txn[2], chan_1.3);
5017
5018         mine_transaction(&nodes[0], &node_txn[1]);
5019         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5020
5021         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5022         // didn't try to generate any new transactions.
5023
5024         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5025         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5026         assert_eq!(spend_txn.len(), 3);
5027         assert_eq!(spend_txn[0].input.len(), 1);
5028         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5029         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5030         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5031         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5032 }
5033
5034 #[test]
5035 fn test_onchain_to_onchain_claim() {
5036         // Test that in case of channel closure, we detect the state of output and claim HTLC
5037         // on downstream peer's remote commitment tx.
5038         // First, have C claim an HTLC against its own latest commitment transaction.
5039         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5040         // channel.
5041         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5042         // gets broadcast.
5043
5044         let chanmon_cfgs = create_chanmon_cfgs(3);
5045         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5046         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5047         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5048
5049         // Create some initial channels
5050         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5051         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5052
5053         // Rebalance the network a bit by relaying one payment through all the channels ...
5054         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5055         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5056
5057         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5058         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5059         check_spends!(commitment_tx[0], chan_2.3);
5060         nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5061         check_added_monitors!(nodes[2], 1);
5062         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5063         assert!(updates.update_add_htlcs.is_empty());
5064         assert!(updates.update_fail_htlcs.is_empty());
5065         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5066         assert!(updates.update_fail_malformed_htlcs.is_empty());
5067
5068         mine_transaction(&nodes[2], &commitment_tx[0]);
5069         check_closed_broadcast!(nodes[2], true);
5070         check_added_monitors!(nodes[2], 1);
5071
5072         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5073         assert_eq!(c_txn.len(), 3);
5074         assert_eq!(c_txn[0], c_txn[2]);
5075         assert_eq!(commitment_tx[0], c_txn[1]);
5076         check_spends!(c_txn[1], chan_2.3);
5077         check_spends!(c_txn[2], c_txn[1]);
5078         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5079         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5080         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5081         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5082
5083         // 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
5084         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5085         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5086         {
5087                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5088                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5089                 assert_eq!(b_txn.len(), 3);
5090                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5091                 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5092                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5093                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5094                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5095                 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5096                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5097                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5098                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5099                 b_txn.clear();
5100         }
5101         check_added_monitors!(nodes[1], 1);
5102         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5103         assert_eq!(msg_events.len(), 3);
5104         check_added_monitors!(nodes[1], 1);
5105         match msg_events[0] {
5106                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5107                 _ => panic!("Unexpected event"),
5108         }
5109         match msg_events[1] {
5110                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5111                 _ => panic!("Unexpected event"),
5112         }
5113         match msg_events[2] {
5114                 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, .. } } => {
5115                         assert!(update_add_htlcs.is_empty());
5116                         assert!(update_fail_htlcs.is_empty());
5117                         assert_eq!(update_fulfill_htlcs.len(), 1);
5118                         assert!(update_fail_malformed_htlcs.is_empty());
5119                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5120                 },
5121                 _ => panic!("Unexpected event"),
5122         };
5123         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5124         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5125         mine_transaction(&nodes[1], &commitment_tx[0]);
5126         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5127         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5128         assert_eq!(b_txn.len(), 3);
5129         check_spends!(b_txn[1], chan_1.3);
5130         check_spends!(b_txn[2], b_txn[1]);
5131         check_spends!(b_txn[0], commitment_tx[0]);
5132         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5133         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5134         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5135
5136         check_closed_broadcast!(nodes[1], true);
5137         check_added_monitors!(nodes[1], 1);
5138 }
5139
5140 #[test]
5141 fn test_duplicate_payment_hash_one_failure_one_success() {
5142         // Topology : A --> B --> C
5143         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5144         let chanmon_cfgs = create_chanmon_cfgs(3);
5145         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5146         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5147         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5148
5149         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5150         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5151
5152         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5153         *nodes[0].network_payment_count.borrow_mut() -= 1;
5154         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5155
5156         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5157         assert_eq!(commitment_txn[0].input.len(), 1);
5158         check_spends!(commitment_txn[0], chan_2.3);
5159
5160         mine_transaction(&nodes[1], &commitment_txn[0]);
5161         check_closed_broadcast!(nodes[1], true);
5162         check_added_monitors!(nodes[1], 1);
5163
5164         let htlc_timeout_tx;
5165         { // Extract one of the two HTLC-Timeout transaction
5166                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5167                 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5168                 assert_eq!(node_txn.len(), 5);
5169                 check_spends!(node_txn[0], commitment_txn[0]);
5170                 assert_eq!(node_txn[0].input.len(), 1);
5171                 check_spends!(node_txn[1], commitment_txn[0]);
5172                 assert_eq!(node_txn[1].input.len(), 1);
5173                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5174                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5175                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5176                 check_spends!(node_txn[2], chan_2.3);
5177                 check_spends!(node_txn[3], node_txn[2]);
5178                 check_spends!(node_txn[4], node_txn[2]);
5179                 htlc_timeout_tx = node_txn[1].clone();
5180         }
5181
5182         nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5183         mine_transaction(&nodes[2], &commitment_txn[0]);
5184         check_added_monitors!(nodes[2], 3);
5185         let events = nodes[2].node.get_and_clear_pending_msg_events();
5186         match events[0] {
5187                 MessageSendEvent::UpdateHTLCs { .. } => {},
5188                 _ => panic!("Unexpected event"),
5189         }
5190         match events[1] {
5191                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5192                 _ => panic!("Unexepected event"),
5193         }
5194         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5195         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)
5196         check_spends!(htlc_success_txn[2], chan_2.3);
5197         check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5198         check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5199         assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5200         assert_eq!(htlc_success_txn[0].input.len(), 1);
5201         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5202         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5203         assert_eq!(htlc_success_txn[1].input.len(), 1);
5204         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5205         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5206         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5207         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5208
5209         mine_transaction(&nodes[1], &htlc_timeout_tx);
5210         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5211         expect_pending_htlcs_forwardable!(nodes[1]);
5212         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5213         assert!(htlc_updates.update_add_htlcs.is_empty());
5214         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5215         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5216         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5217         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5218         check_added_monitors!(nodes[1], 1);
5219
5220         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5221         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5222         {
5223                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5224                 let events = nodes[0].node.get_and_clear_pending_msg_events();
5225                 assert_eq!(events.len(), 1);
5226                 match events[0] {
5227                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
5228                         },
5229                         _ => { panic!("Unexpected event"); }
5230                 }
5231         }
5232         expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5233
5234         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5235         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5236         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5237         assert!(updates.update_add_htlcs.is_empty());
5238         assert!(updates.update_fail_htlcs.is_empty());
5239         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5240         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5241         assert!(updates.update_fail_malformed_htlcs.is_empty());
5242         check_added_monitors!(nodes[1], 1);
5243
5244         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5245         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5246
5247         let events = nodes[0].node.get_and_clear_pending_events();
5248         match events[0] {
5249                 Event::PaymentSent { ref payment_preimage } => {
5250                         assert_eq!(*payment_preimage, our_payment_preimage);
5251                 }
5252                 _ => panic!("Unexpected event"),
5253         }
5254 }
5255
5256 #[test]
5257 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5258         let chanmon_cfgs = create_chanmon_cfgs(2);
5259         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5260         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5261         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5262
5263         // Create some initial channels
5264         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5265
5266         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5267         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5268         assert_eq!(local_txn.len(), 1);
5269         assert_eq!(local_txn[0].input.len(), 1);
5270         check_spends!(local_txn[0], chan_1.3);
5271
5272         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5273         nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5274         check_added_monitors!(nodes[1], 1);
5275         mine_transaction(&nodes[1], &local_txn[0]);
5276         check_added_monitors!(nodes[1], 1);
5277         let events = nodes[1].node.get_and_clear_pending_msg_events();
5278         match events[0] {
5279                 MessageSendEvent::UpdateHTLCs { .. } => {},
5280                 _ => panic!("Unexpected event"),
5281         }
5282         match events[1] {
5283                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5284                 _ => panic!("Unexepected event"),
5285         }
5286         let node_tx = {
5287                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5288                 assert_eq!(node_txn.len(), 3);
5289                 assert_eq!(node_txn[0], node_txn[2]);
5290                 assert_eq!(node_txn[1], local_txn[0]);
5291                 assert_eq!(node_txn[0].input.len(), 1);
5292                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5293                 check_spends!(node_txn[0], local_txn[0]);
5294                 node_txn[0].clone()
5295         };
5296
5297         mine_transaction(&nodes[1], &node_tx);
5298         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5299
5300         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5301         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5302         assert_eq!(spend_txn.len(), 1);
5303         check_spends!(spend_txn[0], node_tx);
5304 }
5305
5306 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5307         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5308         // unrevoked commitment transaction.
5309         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5310         // a remote RAA before they could be failed backwards (and combinations thereof).
5311         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5312         // use the same payment hashes.
5313         // Thus, we use a six-node network:
5314         //
5315         // A \         / E
5316         //    - C - D -
5317         // B /         \ F
5318         // And test where C fails back to A/B when D announces its latest commitment transaction
5319         let chanmon_cfgs = create_chanmon_cfgs(6);
5320         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5321         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5322         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5323         let logger = test_utils::TestLogger::new();
5324
5325         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5326         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5327         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5328         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5329         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5330
5331         // Rebalance and check output sanity...
5332         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5333         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5334         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5335
5336         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5337         // 0th HTLC:
5338         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
5339         // 1st HTLC:
5340         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
5341         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5342         let our_node_id = &nodes[1].node.get_our_node_id();
5343         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();
5344         // 2nd HTLC:
5345         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
5346         // 3rd HTLC:
5347         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
5348         // 4th HTLC:
5349         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5350         // 5th HTLC:
5351         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
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(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5353         // 6th HTLC:
5354         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5355         // 7th HTLC:
5356         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5357
5358         // 8th HTLC:
5359         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5360         // 9th HTLC:
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(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5362         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
5363
5364         // 10th HTLC:
5365         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
5366         // 11th HTLC:
5367         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5368         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5369
5370         // Double-check that six of the new HTLC were added
5371         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5372         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5373         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5374         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5375
5376         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5377         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5378         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5379         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5380         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5381         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5382         check_added_monitors!(nodes[4], 0);
5383         expect_pending_htlcs_forwardable!(nodes[4]);
5384         check_added_monitors!(nodes[4], 1);
5385
5386         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5387         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5388         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5389         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5390         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5391         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5392
5393         // Fail 3rd below-dust and 7th above-dust HTLCs
5394         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5395         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5396         check_added_monitors!(nodes[5], 0);
5397         expect_pending_htlcs_forwardable!(nodes[5]);
5398         check_added_monitors!(nodes[5], 1);
5399
5400         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5401         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5402         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5403         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5404
5405         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5406
5407         expect_pending_htlcs_forwardable!(nodes[3]);
5408         check_added_monitors!(nodes[3], 1);
5409         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5410         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5411         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5412         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5413         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5414         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5415         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5416         if deliver_last_raa {
5417                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5418         } else {
5419                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5420         }
5421
5422         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5423         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5424         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5425         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5426         //
5427         // We now broadcast the latest commitment transaction, which *should* result in failures for
5428         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5429         // the non-broadcast above-dust HTLCs.
5430         //
5431         // Alternatively, we may broadcast the previous commitment transaction, which should only
5432         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5433         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5434
5435         if announce_latest {
5436                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5437         } else {
5438                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5439         }
5440         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5441         check_closed_broadcast!(nodes[2], true);
5442         expect_pending_htlcs_forwardable!(nodes[2]);
5443         check_added_monitors!(nodes[2], 3);
5444
5445         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5446         assert_eq!(cs_msgs.len(), 2);
5447         let mut a_done = false;
5448         for msg in cs_msgs {
5449                 match msg {
5450                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5451                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5452                                 // should be failed-backwards here.
5453                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5454                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5455                                         for htlc in &updates.update_fail_htlcs {
5456                                                 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 });
5457                                         }
5458                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5459                                         assert!(!a_done);
5460                                         a_done = true;
5461                                         &nodes[0]
5462                                 } else {
5463                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5464                                         for htlc in &updates.update_fail_htlcs {
5465                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5466                                         }
5467                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5468                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5469                                         &nodes[1]
5470                                 };
5471                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5472                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5473                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5474                                 if announce_latest {
5475                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5476                                         if *node_id == nodes[0].node.get_our_node_id() {
5477                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5478                                         }
5479                                 }
5480                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5481                         },
5482                         _ => panic!("Unexpected event"),
5483                 }
5484         }
5485
5486         let as_events = nodes[0].node.get_and_clear_pending_events();
5487         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5488         let mut as_failds = HashSet::new();
5489         for event in as_events.iter() {
5490                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5491                         assert!(as_failds.insert(*payment_hash));
5492                         if *payment_hash != payment_hash_2 {
5493                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5494                         } else {
5495                                 assert!(!rejected_by_dest);
5496                         }
5497                 } else { panic!("Unexpected event"); }
5498         }
5499         assert!(as_failds.contains(&payment_hash_1));
5500         assert!(as_failds.contains(&payment_hash_2));
5501         if announce_latest {
5502                 assert!(as_failds.contains(&payment_hash_3));
5503                 assert!(as_failds.contains(&payment_hash_5));
5504         }
5505         assert!(as_failds.contains(&payment_hash_6));
5506
5507         let bs_events = nodes[1].node.get_and_clear_pending_events();
5508         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5509         let mut bs_failds = HashSet::new();
5510         for event in bs_events.iter() {
5511                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5512                         assert!(bs_failds.insert(*payment_hash));
5513                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5514                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5515                         } else {
5516                                 assert!(!rejected_by_dest);
5517                         }
5518                 } else { panic!("Unexpected event"); }
5519         }
5520         assert!(bs_failds.contains(&payment_hash_1));
5521         assert!(bs_failds.contains(&payment_hash_2));
5522         if announce_latest {
5523                 assert!(bs_failds.contains(&payment_hash_4));
5524         }
5525         assert!(bs_failds.contains(&payment_hash_5));
5526
5527         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5528         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5529         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5530         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5531         // PaymentFailureNetworkUpdates.
5532         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5533         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5534         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5535         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5536         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5537                 match event {
5538                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5539                         _ => panic!("Unexpected event"),
5540                 }
5541         }
5542 }
5543
5544 #[test]
5545 fn test_fail_backwards_latest_remote_announce_a() {
5546         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5547 }
5548
5549 #[test]
5550 fn test_fail_backwards_latest_remote_announce_b() {
5551         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5552 }
5553
5554 #[test]
5555 fn test_fail_backwards_previous_remote_announce() {
5556         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5557         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5558         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5559 }
5560
5561 #[test]
5562 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5563         let chanmon_cfgs = create_chanmon_cfgs(2);
5564         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5565         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5566         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5567
5568         // Create some initial channels
5569         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5570
5571         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5572         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5573         assert_eq!(local_txn[0].input.len(), 1);
5574         check_spends!(local_txn[0], chan_1.3);
5575
5576         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5577         mine_transaction(&nodes[0], &local_txn[0]);
5578         check_closed_broadcast!(nodes[0], true);
5579         check_added_monitors!(nodes[0], 1);
5580
5581         let htlc_timeout = {
5582                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5583                 assert_eq!(node_txn[0].input.len(), 1);
5584                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5585                 check_spends!(node_txn[0], local_txn[0]);
5586                 node_txn[0].clone()
5587         };
5588
5589         mine_transaction(&nodes[0], &htlc_timeout);
5590         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5591         expect_payment_failed!(nodes[0], our_payment_hash, true);
5592
5593         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5594         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5595         assert_eq!(spend_txn.len(), 3);
5596         check_spends!(spend_txn[0], local_txn[0]);
5597         check_spends!(spend_txn[1], htlc_timeout);
5598         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5599 }
5600
5601 #[test]
5602 fn test_key_derivation_params() {
5603         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5604         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5605         // let us re-derive the channel key set to then derive a delayed_payment_key.
5606
5607         let chanmon_cfgs = create_chanmon_cfgs(3);
5608
5609         // We manually create the node configuration to backup the seed.
5610         let seed = [42; 32];
5611         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5612         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);
5613         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 };
5614         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5615         node_cfgs.remove(0);
5616         node_cfgs.insert(0, node);
5617
5618         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5619         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5620
5621         // Create some initial channels
5622         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5623         // for node 0
5624         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5625         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5626         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5627
5628         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5629         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5630         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5631         assert_eq!(local_txn_1[0].input.len(), 1);
5632         check_spends!(local_txn_1[0], chan_1.3);
5633
5634         // We check funding pubkey are unique
5635         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]));
5636         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]));
5637         if from_0_funding_key_0 == from_1_funding_key_0
5638             || from_0_funding_key_0 == from_1_funding_key_1
5639             || from_0_funding_key_1 == from_1_funding_key_0
5640             || from_0_funding_key_1 == from_1_funding_key_1 {
5641                 panic!("Funding pubkeys aren't unique");
5642         }
5643
5644         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5645         mine_transaction(&nodes[0], &local_txn_1[0]);
5646         check_closed_broadcast!(nodes[0], true);
5647         check_added_monitors!(nodes[0], 1);
5648
5649         let htlc_timeout = {
5650                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5651                 assert_eq!(node_txn[0].input.len(), 1);
5652                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5653                 check_spends!(node_txn[0], local_txn_1[0]);
5654                 node_txn[0].clone()
5655         };
5656
5657         mine_transaction(&nodes[0], &htlc_timeout);
5658         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5659         expect_payment_failed!(nodes[0], our_payment_hash, true);
5660
5661         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5662         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5663         let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5664         assert_eq!(spend_txn.len(), 3);
5665         check_spends!(spend_txn[0], local_txn_1[0]);
5666         check_spends!(spend_txn[1], htlc_timeout);
5667         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5668 }
5669
5670 #[test]
5671 fn test_static_output_closing_tx() {
5672         let chanmon_cfgs = create_chanmon_cfgs(2);
5673         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5674         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5675         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5676
5677         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5678
5679         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5680         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5681
5682         mine_transaction(&nodes[0], &closing_tx);
5683         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5684
5685         let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5686         assert_eq!(spend_txn.len(), 1);
5687         check_spends!(spend_txn[0], closing_tx);
5688
5689         mine_transaction(&nodes[1], &closing_tx);
5690         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5691
5692         let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5693         assert_eq!(spend_txn.len(), 1);
5694         check_spends!(spend_txn[0], closing_tx);
5695 }
5696
5697 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5698         let chanmon_cfgs = create_chanmon_cfgs(2);
5699         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5700         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5701         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5702         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5703
5704         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5705
5706         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5707         // present in B's local commitment transaction, but none of A's commitment transactions.
5708         assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5709         check_added_monitors!(nodes[1], 1);
5710
5711         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5712         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5713         let events = nodes[0].node.get_and_clear_pending_events();
5714         assert_eq!(events.len(), 1);
5715         match events[0] {
5716                 Event::PaymentSent { payment_preimage } => {
5717                         assert_eq!(payment_preimage, our_payment_preimage);
5718                 },
5719                 _ => panic!("Unexpected event"),
5720         }
5721
5722         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5723         check_added_monitors!(nodes[0], 1);
5724         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5725         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5726         check_added_monitors!(nodes[1], 1);
5727
5728         let starting_block = nodes[1].best_block_info();
5729         let mut block = Block {
5730                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5731                 txdata: vec![],
5732         };
5733         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5734                 connect_block(&nodes[1], &block);
5735                 block.header.prev_blockhash = block.block_hash();
5736         }
5737         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5738         check_closed_broadcast!(nodes[1], true);
5739         check_added_monitors!(nodes[1], 1);
5740 }
5741
5742 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5743         let chanmon_cfgs = create_chanmon_cfgs(2);
5744         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5745         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5746         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5747         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5748         let logger = test_utils::TestLogger::new();
5749
5750         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5751         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5752         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();
5753         nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5754         check_added_monitors!(nodes[0], 1);
5755
5756         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5757
5758         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5759         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5760         // to "time out" the HTLC.
5761
5762         let starting_block = nodes[1].best_block_info();
5763         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5764
5765         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5766                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5767                 header.prev_blockhash = header.block_hash();
5768         }
5769         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5770         check_closed_broadcast!(nodes[0], true);
5771         check_added_monitors!(nodes[0], 1);
5772 }
5773
5774 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5775         let chanmon_cfgs = create_chanmon_cfgs(3);
5776         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5777         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5778         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5779         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5780
5781         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5782         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5783         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5784         // actually revoked.
5785         let htlc_value = if use_dust { 50000 } else { 3000000 };
5786         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5787         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5788         expect_pending_htlcs_forwardable!(nodes[1]);
5789         check_added_monitors!(nodes[1], 1);
5790
5791         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5792         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5793         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5794         check_added_monitors!(nodes[0], 1);
5795         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5796         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5797         check_added_monitors!(nodes[1], 1);
5798         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5799         check_added_monitors!(nodes[1], 1);
5800         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5801
5802         if check_revoke_no_close {
5803                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5804                 check_added_monitors!(nodes[0], 1);
5805         }
5806
5807         let starting_block = nodes[1].best_block_info();
5808         let mut block = Block {
5809                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5810                 txdata: vec![],
5811         };
5812         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5813                 connect_block(&nodes[0], &block);
5814                 block.header.prev_blockhash = block.block_hash();
5815         }
5816         if !check_revoke_no_close {
5817                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5818                 check_closed_broadcast!(nodes[0], true);
5819                 check_added_monitors!(nodes[0], 1);
5820         } else {
5821                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5822         }
5823 }
5824
5825 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5826 // There are only a few cases to test here:
5827 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5828 //    broadcastable commitment transactions result in channel closure,
5829 //  * its included in an unrevoked-but-previous remote commitment transaction,
5830 //  * its included in the latest remote or local commitment transactions.
5831 // We test each of the three possible commitment transactions individually and use both dust and
5832 // non-dust HTLCs.
5833 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5834 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5835 // tested for at least one of the cases in other tests.
5836 #[test]
5837 fn htlc_claim_single_commitment_only_a() {
5838         do_htlc_claim_local_commitment_only(true);
5839         do_htlc_claim_local_commitment_only(false);
5840
5841         do_htlc_claim_current_remote_commitment_only(true);
5842         do_htlc_claim_current_remote_commitment_only(false);
5843 }
5844
5845 #[test]
5846 fn htlc_claim_single_commitment_only_b() {
5847         do_htlc_claim_previous_remote_commitment_only(true, false);
5848         do_htlc_claim_previous_remote_commitment_only(false, false);
5849         do_htlc_claim_previous_remote_commitment_only(true, true);
5850         do_htlc_claim_previous_remote_commitment_only(false, true);
5851 }
5852
5853 #[test]
5854 #[should_panic]
5855 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5856         let chanmon_cfgs = create_chanmon_cfgs(2);
5857         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5858         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5859         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5860         //Force duplicate channel ids
5861         for node in nodes.iter() {
5862                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5863         }
5864
5865         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5866         let channel_value_satoshis=10000;
5867         let push_msat=10001;
5868         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5869         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5870         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5871
5872         //Create a second channel with a channel_id collision
5873         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5874 }
5875
5876 #[test]
5877 fn bolt2_open_channel_sending_node_checks_part2() {
5878         let chanmon_cfgs = create_chanmon_cfgs(2);
5879         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5880         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5881         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5882
5883         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5884         let channel_value_satoshis=2^24;
5885         let push_msat=10001;
5886         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5887
5888         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5889         let channel_value_satoshis=10000;
5890         // Test when push_msat is equal to 1000 * funding_satoshis.
5891         let push_msat=1000*channel_value_satoshis+1;
5892         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5893
5894         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5895         let channel_value_satoshis=10000;
5896         let push_msat=10001;
5897         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
5898         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5899         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5900
5901         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5902         // 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
5903         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5904
5905         // 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.
5906         assert!(BREAKDOWN_TIMEOUT>0);
5907         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5908
5909         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5910         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5911         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5912
5913         // 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.
5914         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5915         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5916         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5917         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5918         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5919 }
5920
5921 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5922 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5923 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5924 // is no longer affordable once it's freed.
5925 #[test]
5926 fn test_fail_holding_cell_htlc_upon_free() {
5927         let chanmon_cfgs = create_chanmon_cfgs(2);
5928         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5929         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5930         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5931         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5932         let logger = test_utils::TestLogger::new();
5933
5934         // First nodes[0] generates an update_fee, setting the channel's
5935         // pending_update_fee.
5936         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
5937         check_added_monitors!(nodes[0], 1);
5938
5939         let events = nodes[0].node.get_and_clear_pending_msg_events();
5940         assert_eq!(events.len(), 1);
5941         let (update_msg, commitment_signed) = match events[0] {
5942                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5943                         (update_fee.as_ref(), commitment_signed)
5944                 },
5945                 _ => panic!("Unexpected event"),
5946         };
5947
5948         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5949
5950         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5951         let channel_reserve = chan_stat.channel_reserve_msat;
5952         let feerate = get_feerate!(nodes[0], chan.2);
5953
5954         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5955         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5956         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5957         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5958         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();
5959
5960         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5961         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5962         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5963         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5964
5965         // Flush the pending fee update.
5966         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5967         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5968         check_added_monitors!(nodes[1], 1);
5969         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5970         check_added_monitors!(nodes[0], 1);
5971
5972         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5973         // HTLC, but now that the fee has been raised the payment will now fail, causing
5974         // us to surface its failure to the user.
5975         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5976         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5977         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
5978         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);
5979         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5980
5981         // Check that the payment failed to be sent out.
5982         let events = nodes[0].node.get_and_clear_pending_events();
5983         assert_eq!(events.len(), 1);
5984         match &events[0] {
5985                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
5986                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5987                         assert_eq!(*rejected_by_dest, false);
5988                         assert_eq!(*error_code, None);
5989                         assert_eq!(*error_data, None);
5990                 },
5991                 _ => panic!("Unexpected event"),
5992         }
5993 }
5994
5995 // Test that if multiple HTLCs are released from the holding cell and one is
5996 // valid but the other is no longer valid upon release, the valid HTLC can be
5997 // successfully completed while the other one fails as expected.
5998 #[test]
5999 fn test_free_and_fail_holding_cell_htlcs() {
6000         let chanmon_cfgs = create_chanmon_cfgs(2);
6001         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6002         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6003         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6004         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6005         let logger = test_utils::TestLogger::new();
6006
6007         // First nodes[0] generates an update_fee, setting the channel's
6008         // pending_update_fee.
6009         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6010         check_added_monitors!(nodes[0], 1);
6011
6012         let events = nodes[0].node.get_and_clear_pending_msg_events();
6013         assert_eq!(events.len(), 1);
6014         let (update_msg, commitment_signed) = match events[0] {
6015                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6016                         (update_fee.as_ref(), commitment_signed)
6017                 },
6018                 _ => panic!("Unexpected event"),
6019         };
6020
6021         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6022
6023         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6024         let channel_reserve = chan_stat.channel_reserve_msat;
6025         let feerate = get_feerate!(nodes[0], chan.2);
6026
6027         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6028         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6029         let amt_1 = 20000;
6030         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6031         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6032         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6033         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();
6034         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();
6035
6036         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6037         nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6038         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6039         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6040         nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6041         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6042         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6043
6044         // Flush the pending fee update.
6045         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6046         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6047         check_added_monitors!(nodes[1], 1);
6048         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6049         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6050         check_added_monitors!(nodes[0], 2);
6051
6052         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6053         // but now that the fee has been raised the second payment will now fail, causing us
6054         // to surface its failure to the user. The first payment should succeed.
6055         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6056         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6057         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6058         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);
6059         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6060
6061         // Check that the second payment failed to be sent out.
6062         let events = nodes[0].node.get_and_clear_pending_events();
6063         assert_eq!(events.len(), 1);
6064         match &events[0] {
6065                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6066                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6067                         assert_eq!(*rejected_by_dest, false);
6068                         assert_eq!(*error_code, None);
6069                         assert_eq!(*error_data, None);
6070                 },
6071                 _ => panic!("Unexpected event"),
6072         }
6073
6074         // Complete the first payment and the RAA from the fee update.
6075         let (payment_event, send_raa_event) = {
6076                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6077                 assert_eq!(msgs.len(), 2);
6078                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6079         };
6080         let raa = match send_raa_event {
6081                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6082                 _ => panic!("Unexpected event"),
6083         };
6084         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6085         check_added_monitors!(nodes[1], 1);
6086         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6087         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6088         let events = nodes[1].node.get_and_clear_pending_events();
6089         assert_eq!(events.len(), 1);
6090         match events[0] {
6091                 Event::PendingHTLCsForwardable { .. } => {},
6092                 _ => panic!("Unexpected event"),
6093         }
6094         nodes[1].node.process_pending_htlc_forwards();
6095         let events = nodes[1].node.get_and_clear_pending_events();
6096         assert_eq!(events.len(), 1);
6097         match events[0] {
6098                 Event::PaymentReceived { .. } => {},
6099                 _ => panic!("Unexpected event"),
6100         }
6101         nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6102         check_added_monitors!(nodes[1], 1);
6103         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6104         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6105         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6106         let events = nodes[0].node.get_and_clear_pending_events();
6107         assert_eq!(events.len(), 1);
6108         match events[0] {
6109                 Event::PaymentSent { ref payment_preimage } => {
6110                         assert_eq!(*payment_preimage, payment_preimage_1);
6111                 }
6112                 _ => panic!("Unexpected event"),
6113         }
6114 }
6115
6116 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6117 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6118 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6119 // once it's freed.
6120 #[test]
6121 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6122         let chanmon_cfgs = create_chanmon_cfgs(3);
6123         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6124         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6125         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6126         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6127         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6128         let logger = test_utils::TestLogger::new();
6129
6130         // First nodes[1] generates an update_fee, setting the channel's
6131         // pending_update_fee.
6132         nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6133         check_added_monitors!(nodes[1], 1);
6134
6135         let events = nodes[1].node.get_and_clear_pending_msg_events();
6136         assert_eq!(events.len(), 1);
6137         let (update_msg, commitment_signed) = match events[0] {
6138                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6139                         (update_fee.as_ref(), commitment_signed)
6140                 },
6141                 _ => panic!("Unexpected event"),
6142         };
6143
6144         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6145
6146         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6147         let channel_reserve = chan_stat.channel_reserve_msat;
6148         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6149
6150         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6151         let feemsat = 239;
6152         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6153         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6154         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6155         let payment_event = {
6156                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6157                 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();
6158                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6159                 check_added_monitors!(nodes[0], 1);
6160
6161                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6162                 assert_eq!(events.len(), 1);
6163
6164                 SendEvent::from_event(events.remove(0))
6165         };
6166         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6167         check_added_monitors!(nodes[1], 0);
6168         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6169         expect_pending_htlcs_forwardable!(nodes[1]);
6170
6171         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6172         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6173
6174         // Flush the pending fee update.
6175         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6176         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6177         check_added_monitors!(nodes[2], 1);
6178         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6179         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6180         check_added_monitors!(nodes[1], 2);
6181
6182         // A final RAA message is generated to finalize the fee update.
6183         let events = nodes[1].node.get_and_clear_pending_msg_events();
6184         assert_eq!(events.len(), 1);
6185
6186         let raa_msg = match &events[0] {
6187                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6188                         msg.clone()
6189                 },
6190                 _ => panic!("Unexpected event"),
6191         };
6192
6193         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6194         check_added_monitors!(nodes[2], 1);
6195         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6196
6197         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6198         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6199         assert_eq!(process_htlc_forwards_event.len(), 1);
6200         match &process_htlc_forwards_event[0] {
6201                 &Event::PendingHTLCsForwardable { .. } => {},
6202                 _ => panic!("Unexpected event"),
6203         }
6204
6205         // In response, we call ChannelManager's process_pending_htlc_forwards
6206         nodes[1].node.process_pending_htlc_forwards();
6207         check_added_monitors!(nodes[1], 1);
6208
6209         // This causes the HTLC to be failed backwards.
6210         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6211         assert_eq!(fail_event.len(), 1);
6212         let (fail_msg, commitment_signed) = match &fail_event[0] {
6213                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6214                         assert_eq!(updates.update_add_htlcs.len(), 0);
6215                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6216                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6217                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6218                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6219                 },
6220                 _ => panic!("Unexpected event"),
6221         };
6222
6223         // Pass the failure messages back to nodes[0].
6224         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6225         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6226
6227         // Complete the HTLC failure+removal process.
6228         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6229         check_added_monitors!(nodes[0], 1);
6230         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6231         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6232         check_added_monitors!(nodes[1], 2);
6233         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6234         assert_eq!(final_raa_event.len(), 1);
6235         let raa = match &final_raa_event[0] {
6236                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6237                 _ => panic!("Unexpected event"),
6238         };
6239         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6240         let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6241         assert_eq!(fail_msg_event.len(), 1);
6242         match &fail_msg_event[0] {
6243                 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6244                 _ => panic!("Unexpected event"),
6245         }
6246         let failure_event = nodes[0].node.get_and_clear_pending_events();
6247         assert_eq!(failure_event.len(), 1);
6248         match &failure_event[0] {
6249                 &Event::PaymentFailed { rejected_by_dest, .. } => {
6250                         assert!(!rejected_by_dest);
6251                 },
6252                 _ => panic!("Unexpected event"),
6253         }
6254         check_added_monitors!(nodes[0], 1);
6255 }
6256
6257 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6258 // 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.
6259 //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.
6260
6261 #[test]
6262 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6263         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6264         let chanmon_cfgs = create_chanmon_cfgs(2);
6265         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6266         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6267         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6268         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6269
6270         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6271         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6272         let logger = test_utils::TestLogger::new();
6273         let 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();
6274         route.paths[0][0].fee_msat = 100;
6275
6276         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6277                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6278         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6279         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6280 }
6281
6282 #[test]
6283 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6284         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6285         let chanmon_cfgs = create_chanmon_cfgs(2);
6286         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6287         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6288         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6289         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6290         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6291
6292         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6293         let logger = test_utils::TestLogger::new();
6294         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();
6295         route.paths[0][0].fee_msat = 0;
6296         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6297                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6298
6299         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6300         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6301 }
6302
6303 #[test]
6304 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6305         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6306         let chanmon_cfgs = create_chanmon_cfgs(2);
6307         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6308         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6309         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6310         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6311
6312         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6313         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6314         let logger = test_utils::TestLogger::new();
6315         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();
6316         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6317         check_added_monitors!(nodes[0], 1);
6318         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6319         updates.update_add_htlcs[0].amount_msat = 0;
6320
6321         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6322         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6323         check_closed_broadcast!(nodes[1], true).unwrap();
6324         check_added_monitors!(nodes[1], 1);
6325 }
6326
6327 #[test]
6328 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6329         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6330         //It is enforced when constructing a route.
6331         let chanmon_cfgs = create_chanmon_cfgs(2);
6332         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6333         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6334         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6335         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6336         let logger = test_utils::TestLogger::new();
6337
6338         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6339
6340         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6341         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();
6342         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6343                 assert_eq!(err, &"Channel CLTV overflowed?"));
6344 }
6345
6346 #[test]
6347 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6348         //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.
6349         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6350         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6351         let chanmon_cfgs = create_chanmon_cfgs(2);
6352         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6353         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6354         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6355         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6356         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6357
6358         let logger = test_utils::TestLogger::new();
6359         for i in 0..max_accepted_htlcs {
6360                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6361                 let payment_event = {
6362                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6363                         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();
6364                         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6365                         check_added_monitors!(nodes[0], 1);
6366
6367                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6368                         assert_eq!(events.len(), 1);
6369                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6370                                 assert_eq!(htlcs[0].htlc_id, i);
6371                         } else {
6372                                 assert!(false);
6373                         }
6374                         SendEvent::from_event(events.remove(0))
6375                 };
6376                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6377                 check_added_monitors!(nodes[1], 0);
6378                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6379
6380                 expect_pending_htlcs_forwardable!(nodes[1]);
6381                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6382         }
6383         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6384         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6385         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();
6386         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6387                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6388
6389         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6390         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6391 }
6392
6393 #[test]
6394 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6395         //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.
6396         let chanmon_cfgs = create_chanmon_cfgs(2);
6397         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6398         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6399         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6400         let channel_value = 100000;
6401         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6402         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6403
6404         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6405
6406         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6407         // Manually create a route over our max in flight (which our router normally automatically
6408         // limits us to.
6409         let route = Route { paths: vec![vec![RouteHop {
6410            pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6411            short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6412            fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6413         }]] };
6414         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6415                 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)));
6416
6417         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6418         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);
6419
6420         send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6421 }
6422
6423 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6424 #[test]
6425 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6426         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6427         let chanmon_cfgs = create_chanmon_cfgs(2);
6428         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6429         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6430         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6431         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6432         let htlc_minimum_msat: u64;
6433         {
6434                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6435                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6436                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6437         }
6438
6439         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6440         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6441         let logger = test_utils::TestLogger::new();
6442         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();
6443         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6444         check_added_monitors!(nodes[0], 1);
6445         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6446         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6447         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6448         assert!(nodes[1].node.list_channels().is_empty());
6449         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6450         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()));
6451         check_added_monitors!(nodes[1], 1);
6452 }
6453
6454 #[test]
6455 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6456         //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
6457         let chanmon_cfgs = create_chanmon_cfgs(2);
6458         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6459         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6460         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6461         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6462         let logger = test_utils::TestLogger::new();
6463
6464         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6465         let channel_reserve = chan_stat.channel_reserve_msat;
6466         let feerate = get_feerate!(nodes[0], chan.2);
6467         // The 2* and +1 are for the fee spike reserve.
6468         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6469
6470         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6471         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6472         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6473         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();
6474         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6475         check_added_monitors!(nodes[0], 1);
6476         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6477
6478         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6479         // at this time channel-initiatee receivers are not required to enforce that senders
6480         // respect the fee_spike_reserve.
6481         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6482         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6483
6484         assert!(nodes[1].node.list_channels().is_empty());
6485         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6486         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6487         check_added_monitors!(nodes[1], 1);
6488 }
6489
6490 #[test]
6491 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6492         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6493         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6494         let chanmon_cfgs = create_chanmon_cfgs(2);
6495         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6496         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6497         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6498         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6499         let logger = test_utils::TestLogger::new();
6500
6501         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6502         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6503
6504         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6505         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();
6506
6507         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6508         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6509         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6510         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6511
6512         let mut msg = msgs::UpdateAddHTLC {
6513                 channel_id: chan.2,
6514                 htlc_id: 0,
6515                 amount_msat: 1000,
6516                 payment_hash: our_payment_hash,
6517                 cltv_expiry: htlc_cltv,
6518                 onion_routing_packet: onion_packet.clone(),
6519         };
6520
6521         for i in 0..super::channel::OUR_MAX_HTLCS {
6522                 msg.htlc_id = i as u64;
6523                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6524         }
6525         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6526         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6527
6528         assert!(nodes[1].node.list_channels().is_empty());
6529         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6530         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6531         check_added_monitors!(nodes[1], 1);
6532 }
6533
6534 #[test]
6535 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6536         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6537         let chanmon_cfgs = create_chanmon_cfgs(2);
6538         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6539         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6540         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6541         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6542         let logger = test_utils::TestLogger::new();
6543
6544         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6545         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6546         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();
6547         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6548         check_added_monitors!(nodes[0], 1);
6549         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6550         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6551         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6552
6553         assert!(nodes[1].node.list_channels().is_empty());
6554         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6555         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6556         check_added_monitors!(nodes[1], 1);
6557 }
6558
6559 #[test]
6560 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6561         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6562         let chanmon_cfgs = create_chanmon_cfgs(2);
6563         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6564         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6565         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6566         let logger = test_utils::TestLogger::new();
6567
6568         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6569         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6570         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6571         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();
6572         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6573         check_added_monitors!(nodes[0], 1);
6574         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6575         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6576         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6577
6578         assert!(nodes[1].node.list_channels().is_empty());
6579         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6580         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6581         check_added_monitors!(nodes[1], 1);
6582 }
6583
6584 #[test]
6585 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6586         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6587         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6588         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6589         let chanmon_cfgs = create_chanmon_cfgs(2);
6590         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6591         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6592         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6593         let logger = test_utils::TestLogger::new();
6594
6595         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6596         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6597         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6598         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();
6599         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6600         check_added_monitors!(nodes[0], 1);
6601         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6602         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6603
6604         //Disconnect and Reconnect
6605         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6606         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6607         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6608         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6609         assert_eq!(reestablish_1.len(), 1);
6610         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6611         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6612         assert_eq!(reestablish_2.len(), 1);
6613         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6614         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6615         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6616         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6617
6618         //Resend HTLC
6619         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6620         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6621         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6622         check_added_monitors!(nodes[1], 1);
6623         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6624
6625         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6626
6627         assert!(nodes[1].node.list_channels().is_empty());
6628         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6629         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6630         check_added_monitors!(nodes[1], 1);
6631 }
6632
6633 #[test]
6634 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6635         //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.
6636
6637         let chanmon_cfgs = create_chanmon_cfgs(2);
6638         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6639         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6640         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6641         let logger = test_utils::TestLogger::new();
6642         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6643         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6644         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6645         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();
6646         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6647
6648         check_added_monitors!(nodes[0], 1);
6649         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6650         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6651
6652         let update_msg = msgs::UpdateFulfillHTLC{
6653                 channel_id: chan.2,
6654                 htlc_id: 0,
6655                 payment_preimage: our_payment_preimage,
6656         };
6657
6658         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6659
6660         assert!(nodes[0].node.list_channels().is_empty());
6661         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6662         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()));
6663         check_added_monitors!(nodes[0], 1);
6664 }
6665
6666 #[test]
6667 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6668         //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.
6669
6670         let chanmon_cfgs = create_chanmon_cfgs(2);
6671         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6672         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6673         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6674         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6675         let logger = test_utils::TestLogger::new();
6676
6677         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6678         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6679         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();
6680         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6681         check_added_monitors!(nodes[0], 1);
6682         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6683         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6684
6685         let update_msg = msgs::UpdateFailHTLC{
6686                 channel_id: chan.2,
6687                 htlc_id: 0,
6688                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6689         };
6690
6691         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6692
6693         assert!(nodes[0].node.list_channels().is_empty());
6694         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6695         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()));
6696         check_added_monitors!(nodes[0], 1);
6697 }
6698
6699 #[test]
6700 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6701         //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.
6702
6703         let chanmon_cfgs = create_chanmon_cfgs(2);
6704         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6705         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6706         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6707         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6708         let logger = test_utils::TestLogger::new();
6709
6710         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6711         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6712         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();
6713         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6714         check_added_monitors!(nodes[0], 1);
6715         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6716         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6717         let update_msg = msgs::UpdateFailMalformedHTLC{
6718                 channel_id: chan.2,
6719                 htlc_id: 0,
6720                 sha256_of_onion: [1; 32],
6721                 failure_code: 0x8000,
6722         };
6723
6724         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6725
6726         assert!(nodes[0].node.list_channels().is_empty());
6727         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6728         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()));
6729         check_added_monitors!(nodes[0], 1);
6730 }
6731
6732 #[test]
6733 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6734         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6735
6736         let chanmon_cfgs = create_chanmon_cfgs(2);
6737         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6738         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6739         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6740         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6741
6742         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6743
6744         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6745         check_added_monitors!(nodes[1], 1);
6746
6747         let events = nodes[1].node.get_and_clear_pending_msg_events();
6748         assert_eq!(events.len(), 1);
6749         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6750                 match events[0] {
6751                         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, .. } } => {
6752                                 assert!(update_add_htlcs.is_empty());
6753                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6754                                 assert!(update_fail_htlcs.is_empty());
6755                                 assert!(update_fail_malformed_htlcs.is_empty());
6756                                 assert!(update_fee.is_none());
6757                                 update_fulfill_htlcs[0].clone()
6758                         },
6759                         _ => panic!("Unexpected event"),
6760                 }
6761         };
6762
6763         update_fulfill_msg.htlc_id = 1;
6764
6765         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6766
6767         assert!(nodes[0].node.list_channels().is_empty());
6768         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6769         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6770         check_added_monitors!(nodes[0], 1);
6771 }
6772
6773 #[test]
6774 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6775         //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.
6776
6777         let chanmon_cfgs = create_chanmon_cfgs(2);
6778         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6779         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6780         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6781         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6782
6783         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6784
6785         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6786         check_added_monitors!(nodes[1], 1);
6787
6788         let events = nodes[1].node.get_and_clear_pending_msg_events();
6789         assert_eq!(events.len(), 1);
6790         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6791                 match events[0] {
6792                         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, .. } } => {
6793                                 assert!(update_add_htlcs.is_empty());
6794                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6795                                 assert!(update_fail_htlcs.is_empty());
6796                                 assert!(update_fail_malformed_htlcs.is_empty());
6797                                 assert!(update_fee.is_none());
6798                                 update_fulfill_htlcs[0].clone()
6799                         },
6800                         _ => panic!("Unexpected event"),
6801                 }
6802         };
6803
6804         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6805
6806         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6807
6808         assert!(nodes[0].node.list_channels().is_empty());
6809         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6810         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6811         check_added_monitors!(nodes[0], 1);
6812 }
6813
6814 #[test]
6815 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6816         //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.
6817
6818         let chanmon_cfgs = create_chanmon_cfgs(2);
6819         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6820         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6821         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6822         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6823         let logger = test_utils::TestLogger::new();
6824
6825         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6826         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6827         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();
6828         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6829         check_added_monitors!(nodes[0], 1);
6830
6831         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6832         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6833
6834         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6835         check_added_monitors!(nodes[1], 0);
6836         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6837
6838         let events = nodes[1].node.get_and_clear_pending_msg_events();
6839
6840         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6841                 match events[0] {
6842                         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, .. } } => {
6843                                 assert!(update_add_htlcs.is_empty());
6844                                 assert!(update_fulfill_htlcs.is_empty());
6845                                 assert!(update_fail_htlcs.is_empty());
6846                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6847                                 assert!(update_fee.is_none());
6848                                 update_fail_malformed_htlcs[0].clone()
6849                         },
6850                         _ => panic!("Unexpected event"),
6851                 }
6852         };
6853         update_msg.failure_code &= !0x8000;
6854         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6855
6856         assert!(nodes[0].node.list_channels().is_empty());
6857         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6858         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6859         check_added_monitors!(nodes[0], 1);
6860 }
6861
6862 #[test]
6863 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6864         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6865         //    * 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.
6866
6867         let chanmon_cfgs = create_chanmon_cfgs(3);
6868         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6869         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6870         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6871         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6872         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6873         let logger = test_utils::TestLogger::new();
6874
6875         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6876
6877         //First hop
6878         let mut payment_event = {
6879                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6880                 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();
6881                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6882                 check_added_monitors!(nodes[0], 1);
6883                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6884                 assert_eq!(events.len(), 1);
6885                 SendEvent::from_event(events.remove(0))
6886         };
6887         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6888         check_added_monitors!(nodes[1], 0);
6889         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6890         expect_pending_htlcs_forwardable!(nodes[1]);
6891         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6892         assert_eq!(events_2.len(), 1);
6893         check_added_monitors!(nodes[1], 1);
6894         payment_event = SendEvent::from_event(events_2.remove(0));
6895         assert_eq!(payment_event.msgs.len(), 1);
6896
6897         //Second Hop
6898         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6899         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6900         check_added_monitors!(nodes[2], 0);
6901         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6902
6903         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6904         assert_eq!(events_3.len(), 1);
6905         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6906                 match events_3[0] {
6907                         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 } } => {
6908                                 assert!(update_add_htlcs.is_empty());
6909                                 assert!(update_fulfill_htlcs.is_empty());
6910                                 assert!(update_fail_htlcs.is_empty());
6911                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6912                                 assert!(update_fee.is_none());
6913                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6914                         },
6915                         _ => panic!("Unexpected event"),
6916                 }
6917         };
6918
6919         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6920
6921         check_added_monitors!(nodes[1], 0);
6922         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6923         expect_pending_htlcs_forwardable!(nodes[1]);
6924         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6925         assert_eq!(events_4.len(), 1);
6926
6927         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6928         match events_4[0] {
6929                 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, .. } } => {
6930                         assert!(update_add_htlcs.is_empty());
6931                         assert!(update_fulfill_htlcs.is_empty());
6932                         assert_eq!(update_fail_htlcs.len(), 1);
6933                         assert!(update_fail_malformed_htlcs.is_empty());
6934                         assert!(update_fee.is_none());
6935                 },
6936                 _ => panic!("Unexpected event"),
6937         };
6938
6939         check_added_monitors!(nodes[1], 1);
6940 }
6941
6942 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6943         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6944         // 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
6945         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6946
6947         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6948         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6949         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6950         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6951         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6952         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6953
6954         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6955
6956         // We route 2 dust-HTLCs between A and B
6957         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6958         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6959         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6960
6961         // Cache one local commitment tx as previous
6962         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6963
6964         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6965         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
6966         check_added_monitors!(nodes[1], 0);
6967         expect_pending_htlcs_forwardable!(nodes[1]);
6968         check_added_monitors!(nodes[1], 1);
6969
6970         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6971         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6972         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6973         check_added_monitors!(nodes[0], 1);
6974
6975         // Cache one local commitment tx as lastest
6976         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6977
6978         let events = nodes[0].node.get_and_clear_pending_msg_events();
6979         match events[0] {
6980                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6981                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6982                 },
6983                 _ => panic!("Unexpected event"),
6984         }
6985         match events[1] {
6986                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6987                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6988                 },
6989                 _ => panic!("Unexpected event"),
6990         }
6991
6992         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6993         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6994         if announce_latest {
6995                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6996         } else {
6997                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6998         }
6999
7000         check_closed_broadcast!(nodes[0], true);
7001         check_added_monitors!(nodes[0], 1);
7002
7003         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7004         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7005         let events = nodes[0].node.get_and_clear_pending_events();
7006         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7007         assert_eq!(events.len(), 2);
7008         let mut first_failed = false;
7009         for event in events {
7010                 match event {
7011                         Event::PaymentFailed { payment_hash, .. } => {
7012                                 if payment_hash == payment_hash_1 {
7013                                         assert!(!first_failed);
7014                                         first_failed = true;
7015                                 } else {
7016                                         assert_eq!(payment_hash, payment_hash_2);
7017                                 }
7018                         }
7019                         _ => panic!("Unexpected event"),
7020                 }
7021         }
7022 }
7023
7024 #[test]
7025 fn test_failure_delay_dust_htlc_local_commitment() {
7026         do_test_failure_delay_dust_htlc_local_commitment(true);
7027         do_test_failure_delay_dust_htlc_local_commitment(false);
7028 }
7029
7030 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7031         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7032         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7033         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7034         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7035         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7036         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7037
7038         let chanmon_cfgs = create_chanmon_cfgs(3);
7039         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7040         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7041         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7042         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7043
7044         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7045
7046         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7047         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7048
7049         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7050         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7051
7052         // We revoked bs_commitment_tx
7053         if revoked {
7054                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7055                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7056         }
7057
7058         let mut timeout_tx = Vec::new();
7059         if local {
7060                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7061                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7062                 check_closed_broadcast!(nodes[0], true);
7063                 check_added_monitors!(nodes[0], 1);
7064                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7065                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7066                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7067                 expect_payment_failed!(nodes[0], dust_hash, true);
7068                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7069                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7070                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7071                 mine_transaction(&nodes[0], &timeout_tx[0]);
7072                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7073                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7074         } else {
7075                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7076                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7077                 check_closed_broadcast!(nodes[0], true);
7078                 check_added_monitors!(nodes[0], 1);
7079                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7080                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7081                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7082                 if !revoked {
7083                         expect_payment_failed!(nodes[0], dust_hash, true);
7084                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7085                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7086                         mine_transaction(&nodes[0], &timeout_tx[0]);
7087                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7088                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7089                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7090                 } else {
7091                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7092                         // commitment tx
7093                         let events = nodes[0].node.get_and_clear_pending_events();
7094                         assert_eq!(events.len(), 2);
7095                         let first;
7096                         match events[0] {
7097                                 Event::PaymentFailed { payment_hash, .. } => {
7098                                         if payment_hash == dust_hash { first = true; }
7099                                         else { first = false; }
7100                                 },
7101                                 _ => panic!("Unexpected event"),
7102                         }
7103                         match events[1] {
7104                                 Event::PaymentFailed { payment_hash, .. } => {
7105                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7106                                         else { assert_eq!(payment_hash, dust_hash); }
7107                                 },
7108                                 _ => panic!("Unexpected event"),
7109                         }
7110                 }
7111         }
7112 }
7113
7114 #[test]
7115 fn test_sweep_outbound_htlc_failure_update() {
7116         do_test_sweep_outbound_htlc_failure_update(false, true);
7117         do_test_sweep_outbound_htlc_failure_update(false, false);
7118         do_test_sweep_outbound_htlc_failure_update(true, false);
7119 }
7120
7121 #[test]
7122 fn test_upfront_shutdown_script() {
7123         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7124         // enforce it at shutdown message
7125
7126         let mut config = UserConfig::default();
7127         config.channel_options.announced_channel = true;
7128         config.peer_channel_config_limits.force_announced_channel_preference = false;
7129         config.channel_options.commit_upfront_shutdown_pubkey = false;
7130         let user_cfgs = [None, Some(config), None];
7131         let chanmon_cfgs = create_chanmon_cfgs(3);
7132         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7133         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7134         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7135
7136         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7137         let flags = InitFeatures::known();
7138         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7139         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7140         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7141         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7142         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
7143         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7144     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()));
7145         check_added_monitors!(nodes[2], 1);
7146
7147         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7148         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7149         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7150         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7151         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7152         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7153         let events = nodes[2].node.get_and_clear_pending_msg_events();
7154         assert_eq!(events.len(), 1);
7155         match events[0] {
7156                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7157                 _ => panic!("Unexpected event"),
7158         }
7159
7160         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7161         let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7162         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7163         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7164         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7165         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7166         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
7167         let events = nodes[1].node.get_and_clear_pending_msg_events();
7168         assert_eq!(events.len(), 1);
7169         match events[0] {
7170                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7171                 _ => panic!("Unexpected event"),
7172         }
7173
7174         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7175         // channel smoothly, opt-out is from channel initiator here
7176         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7177         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7178         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7179         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7180         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7181         let events = nodes[0].node.get_and_clear_pending_msg_events();
7182         assert_eq!(events.len(), 1);
7183         match events[0] {
7184                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7185                 _ => panic!("Unexpected event"),
7186         }
7187
7188         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7189         //// channel smoothly
7190         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7191         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7192         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7193         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7194         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7195         let events = nodes[0].node.get_and_clear_pending_msg_events();
7196         assert_eq!(events.len(), 2);
7197         match events[0] {
7198                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7199                 _ => panic!("Unexpected event"),
7200         }
7201         match events[1] {
7202                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7203                 _ => panic!("Unexpected event"),
7204         }
7205 }
7206
7207 #[test]
7208 fn test_upfront_shutdown_script_unsupport_segwit() {
7209         // We test that channel is closed early
7210         // if a segwit program is passed as upfront shutdown script,
7211         // but the peer does not support segwit.
7212         let chanmon_cfgs = create_chanmon_cfgs(2);
7213         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7214         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7215         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7216
7217         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
7218
7219         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7220         open_channel.shutdown_scriptpubkey = Present(Builder::new().push_int(16)
7221                 .push_slice(&[0, 0])
7222                 .into_script());
7223
7224         let features = InitFeatures::known().clear_shutdown_anysegwit();
7225         nodes[0].node.handle_open_channel(&nodes[0].node.get_our_node_id(), features, &open_channel);
7226
7227         let events = nodes[0].node.get_and_clear_pending_msg_events();
7228         assert_eq!(events.len(), 1);
7229         match events[0] {
7230                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7231                         assert_eq!(node_id, nodes[0].node.get_our_node_id());
7232                         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));
7233                 },
7234                 _ => panic!("Unexpected event"),
7235         }
7236 }
7237
7238 #[test]
7239 fn test_shutdown_script_any_segwit_allowed() {
7240         let mut config = UserConfig::default();
7241         config.channel_options.announced_channel = true;
7242         config.peer_channel_config_limits.force_announced_channel_preference = false;
7243         config.channel_options.commit_upfront_shutdown_pubkey = false;
7244         let user_cfgs = [None, Some(config), None];
7245         let chanmon_cfgs = create_chanmon_cfgs(3);
7246         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7247         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7248         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7249
7250         //// We test if the remote peer accepts opt_shutdown_anysegwit, a witness program can be used on shutdown
7251         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7252         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7253         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7254         node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7255                 .push_slice(&[0, 0])
7256                 .into_script();
7257         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7258         let events = nodes[0].node.get_and_clear_pending_msg_events();
7259         assert_eq!(events.len(), 2);
7260         match events[0] {
7261                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7262                 _ => panic!("Unexpected event"),
7263         }
7264         match events[1] {
7265                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7266                 _ => panic!("Unexpected event"),
7267         }
7268 }
7269
7270 #[test]
7271 fn test_shutdown_script_any_segwit_not_allowed() {
7272         let mut config = UserConfig::default();
7273         config.channel_options.announced_channel = true;
7274         config.peer_channel_config_limits.force_announced_channel_preference = false;
7275         config.channel_options.commit_upfront_shutdown_pubkey = false;
7276         let user_cfgs = [None, Some(config), None];
7277         let chanmon_cfgs = create_chanmon_cfgs(3);
7278         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7279         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7280         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7281
7282         //// We test that if the remote peer does not accept opt_shutdown_anysegwit, the witness program cannot be used on shutdown
7283         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7284         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7285         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7286         // Make an any segwit version script
7287         node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7288                 .push_slice(&[0, 0])
7289                 .into_script();
7290         let flags_no = InitFeatures::known().clear_shutdown_anysegwit();
7291         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &flags_no, &node_0_shutdown);
7292         let events = nodes[0].node.get_and_clear_pending_msg_events();
7293         assert_eq!(events.len(), 2);
7294         match events[1] {
7295                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7296                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7297                         assert_eq!(msg.data, "Got a nonstandard scriptpubkey (60020000) from remote peer".to_owned())
7298                 },
7299                 _ => panic!("Unexpected event"),
7300         }
7301         check_added_monitors!(nodes[0], 1);
7302 }
7303
7304 #[test]
7305 fn test_shutdown_script_segwit_but_not_anysegwit() {
7306         let mut config = UserConfig::default();
7307         config.channel_options.announced_channel = true;
7308         config.peer_channel_config_limits.force_announced_channel_preference = false;
7309         config.channel_options.commit_upfront_shutdown_pubkey = false;
7310         let user_cfgs = [None, Some(config), None];
7311         let chanmon_cfgs = create_chanmon_cfgs(3);
7312         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7313         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7314         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7315
7316         //// We test that if shutdown any segwit is supported and we send a witness script with 0 version, this is not accepted
7317         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7318         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7319         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7320         // Make a segwit script that is not a valid as any segwit
7321         node_0_shutdown.scriptpubkey = Builder::new().push_int(0)
7322                 .push_slice(&[0, 0])
7323                 .into_script();
7324         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7325         let events = nodes[0].node.get_and_clear_pending_msg_events();
7326         assert_eq!(events.len(), 2);
7327         match events[1] {
7328                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7329                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7330                         assert_eq!(msg.data, "Got a nonstandard scriptpubkey (00020000) from remote peer".to_owned())
7331                 },
7332                 _ => panic!("Unexpected event"),
7333         }
7334         check_added_monitors!(nodes[0], 1);
7335 }
7336
7337 #[test]
7338 fn test_user_configurable_csv_delay() {
7339         // We test our channel constructors yield errors when we pass them absurd csv delay
7340
7341         let mut low_our_to_self_config = UserConfig::default();
7342         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7343         let mut high_their_to_self_config = UserConfig::default();
7344         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7345         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7346         let chanmon_cfgs = create_chanmon_cfgs(2);
7347         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7348         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7349         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7350
7351         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7352         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) {
7353                 match error {
7354                         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())); },
7355                         _ => panic!("Unexpected event"),
7356                 }
7357         } else { assert!(false) }
7358
7359         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7360         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7361         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7362         open_channel.to_self_delay = 200;
7363         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) {
7364                 match error {
7365                         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()));  },
7366                         _ => panic!("Unexpected event"),
7367                 }
7368         } else { assert!(false); }
7369
7370         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7371         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7372         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()));
7373         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7374         accept_channel.to_self_delay = 200;
7375         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7376         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7377                 match action {
7378                         &ErrorAction::SendErrorMessage { ref msg } => {
7379                                 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()));
7380                         },
7381                         _ => { assert!(false); }
7382                 }
7383         } else { assert!(false); }
7384
7385         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7386         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7387         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7388         open_channel.to_self_delay = 200;
7389         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) {
7390                 match error {
7391                         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())); },
7392                         _ => panic!("Unexpected event"),
7393                 }
7394         } else { assert!(false); }
7395 }
7396
7397 #[test]
7398 fn test_data_loss_protect() {
7399         // We want to be sure that :
7400         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7401         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7402         // * we close channel in case of detecting other being fallen behind
7403         // * we are able to claim our own outputs thanks to to_remote being static
7404         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7405         let persister;
7406         let logger;
7407         let fee_estimator;
7408         let tx_broadcaster;
7409         let chain_source;
7410         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7411         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7412         // during signing due to revoked tx
7413         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7414         let keys_manager = &chanmon_cfgs[0].keys_manager;
7415         let monitor;
7416         let node_state_0;
7417         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7418         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7419         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7420
7421         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7422
7423         // Cache node A state before any channel update
7424         let previous_node_state = nodes[0].node.encode();
7425         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7426         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7427
7428         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7429         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7430
7431         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7432         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7433
7434         // Restore node A from previous state
7435         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7436         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7437         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7438         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7439         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7440         persister = test_utils::TestPersister::new();
7441         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7442         node_state_0 = {
7443                 let mut channel_monitors = HashMap::new();
7444                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7445                 <(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 {
7446                         keys_manager: keys_manager,
7447                         fee_estimator: &fee_estimator,
7448                         chain_monitor: &monitor,
7449                         logger: &logger,
7450                         tx_broadcaster: &tx_broadcaster,
7451                         default_config: UserConfig::default(),
7452                         channel_monitors,
7453                 }).unwrap().1
7454         };
7455         nodes[0].node = &node_state_0;
7456         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7457         nodes[0].chain_monitor = &monitor;
7458         nodes[0].chain_source = &chain_source;
7459
7460         check_added_monitors!(nodes[0], 1);
7461
7462         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7463         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7464
7465         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7466
7467         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7468         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7469         check_added_monitors!(nodes[0], 1);
7470
7471         {
7472                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7473                 assert_eq!(node_txn.len(), 0);
7474         }
7475
7476         let mut reestablish_1 = Vec::with_capacity(1);
7477         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7478                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7479                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7480                         reestablish_1.push(msg.clone());
7481                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7482                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7483                         match action {
7484                                 &ErrorAction::SendErrorMessage { ref msg } => {
7485                                         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");
7486                                 },
7487                                 _ => panic!("Unexpected event!"),
7488                         }
7489                 } else {
7490                         panic!("Unexpected event")
7491                 }
7492         }
7493
7494         // Check we close channel detecting A is fallen-behind
7495         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7496         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7497         check_added_monitors!(nodes[1], 1);
7498
7499
7500         // Check A is able to claim to_remote output
7501         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7502         assert_eq!(node_txn.len(), 1);
7503         check_spends!(node_txn[0], chan.3);
7504         assert_eq!(node_txn[0].output.len(), 2);
7505         mine_transaction(&nodes[0], &node_txn[0]);
7506         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7507         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 1000000);
7508         assert_eq!(spend_txn.len(), 1);
7509         check_spends!(spend_txn[0], node_txn[0]);
7510 }
7511
7512 #[test]
7513 fn test_check_htlc_underpaying() {
7514         // Send payment through A -> B but A is maliciously
7515         // sending a probe payment (i.e less than expected value0
7516         // to B, B should refuse payment.
7517
7518         let chanmon_cfgs = create_chanmon_cfgs(2);
7519         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7520         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7521         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7522
7523         // Create some initial channels
7524         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7525
7526         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7527
7528         // Node 3 is expecting payment of 100_000 but receive 10_000,
7529         // fail htlc like we didn't know the preimage.
7530         nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7531         nodes[1].node.process_pending_htlc_forwards();
7532
7533         let events = nodes[1].node.get_and_clear_pending_msg_events();
7534         assert_eq!(events.len(), 1);
7535         let (update_fail_htlc, commitment_signed) = match events[0] {
7536                 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 } } => {
7537                         assert!(update_add_htlcs.is_empty());
7538                         assert!(update_fulfill_htlcs.is_empty());
7539                         assert_eq!(update_fail_htlcs.len(), 1);
7540                         assert!(update_fail_malformed_htlcs.is_empty());
7541                         assert!(update_fee.is_none());
7542                         (update_fail_htlcs[0].clone(), commitment_signed)
7543                 },
7544                 _ => panic!("Unexpected event"),
7545         };
7546         check_added_monitors!(nodes[1], 1);
7547
7548         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7549         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7550
7551         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7552         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7553         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7554         expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7555         nodes[1].node.get_and_clear_pending_events();
7556 }
7557
7558 #[test]
7559 fn test_announce_disable_channels() {
7560         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7561         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7562
7563         let chanmon_cfgs = create_chanmon_cfgs(2);
7564         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7565         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7566         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7567
7568         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7569         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7570         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7571
7572         // Disconnect peers
7573         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7574         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7575
7576         nodes[0].node.timer_tick_occurred(); // dirty -> stagged
7577         nodes[0].node.timer_tick_occurred(); // staged -> fresh
7578         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7579         assert_eq!(msg_events.len(), 3);
7580         for e in msg_events {
7581                 match e {
7582                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7583                                 let short_id = msg.contents.short_channel_id;
7584                                 // Check generated channel_update match list in PendingChannelUpdate
7585                                 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7586                                         panic!("Generated ChannelUpdate for wrong chan!");
7587                                 }
7588                         },
7589                         _ => panic!("Unexpected event"),
7590                 }
7591         }
7592         // Reconnect peers
7593         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7594         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7595         assert_eq!(reestablish_1.len(), 3);
7596         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7597         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7598         assert_eq!(reestablish_2.len(), 3);
7599
7600         // Reestablish chan_1
7601         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7602         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7603         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7604         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7605         // Reestablish chan_2
7606         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7607         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7608         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7609         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7610         // Reestablish chan_3
7611         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7612         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7613         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7614         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7615
7616         nodes[0].node.timer_tick_occurred();
7617         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7618 }
7619
7620 #[test]
7621 fn test_bump_penalty_txn_on_revoked_commitment() {
7622         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7623         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7624
7625         let chanmon_cfgs = create_chanmon_cfgs(2);
7626         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7627         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7628         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7629
7630         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7631         let logger = test_utils::TestLogger::new();
7632
7633         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7634         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7635         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();
7636         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7637
7638         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7639         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7640         assert_eq!(revoked_txn[0].output.len(), 4);
7641         assert_eq!(revoked_txn[0].input.len(), 1);
7642         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7643         let revoked_txid = revoked_txn[0].txid();
7644
7645         let mut penalty_sum = 0;
7646         for outp in revoked_txn[0].output.iter() {
7647                 if outp.script_pubkey.is_v0_p2wsh() {
7648                         penalty_sum += outp.value;
7649                 }
7650         }
7651
7652         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7653         let header_114 = connect_blocks(&nodes[1], 14);
7654
7655         // Actually revoke tx by claiming a HTLC
7656         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7657         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7658         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7659         check_added_monitors!(nodes[1], 1);
7660
7661         // One or more justice tx should have been broadcast, check it
7662         let penalty_1;
7663         let feerate_1;
7664         {
7665                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7666                 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7667                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7668                 assert_eq!(node_txn[0].output.len(), 1);
7669                 check_spends!(node_txn[0], revoked_txn[0]);
7670                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7671                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7672                 penalty_1 = node_txn[0].txid();
7673                 node_txn.clear();
7674         };
7675
7676         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7677         connect_blocks(&nodes[1], 15);
7678         let mut penalty_2 = penalty_1;
7679         let mut feerate_2 = 0;
7680         {
7681                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7682                 assert_eq!(node_txn.len(), 1);
7683                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7684                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7685                         assert_eq!(node_txn[0].output.len(), 1);
7686                         check_spends!(node_txn[0], revoked_txn[0]);
7687                         penalty_2 = node_txn[0].txid();
7688                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7689                         assert_ne!(penalty_2, penalty_1);
7690                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7691                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7692                         // Verify 25% bump heuristic
7693                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7694                         node_txn.clear();
7695                 }
7696         }
7697         assert_ne!(feerate_2, 0);
7698
7699         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7700         connect_blocks(&nodes[1], 1);
7701         let penalty_3;
7702         let mut feerate_3 = 0;
7703         {
7704                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7705                 assert_eq!(node_txn.len(), 1);
7706                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7707                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7708                         assert_eq!(node_txn[0].output.len(), 1);
7709                         check_spends!(node_txn[0], revoked_txn[0]);
7710                         penalty_3 = node_txn[0].txid();
7711                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7712                         assert_ne!(penalty_3, penalty_2);
7713                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7714                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7715                         // Verify 25% bump heuristic
7716                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7717                         node_txn.clear();
7718                 }
7719         }
7720         assert_ne!(feerate_3, 0);
7721
7722         nodes[1].node.get_and_clear_pending_events();
7723         nodes[1].node.get_and_clear_pending_msg_events();
7724 }
7725
7726 #[test]
7727 fn test_bump_penalty_txn_on_revoked_htlcs() {
7728         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7729         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7730
7731         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7732         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7733         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7734         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7735         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7736
7737         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7738         // Lock HTLC in both directions
7739         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7740         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7741
7742         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7743         assert_eq!(revoked_local_txn[0].input.len(), 1);
7744         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7745
7746         // Revoke local commitment tx
7747         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7748
7749         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7750         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7751         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7752         check_closed_broadcast!(nodes[1], true);
7753         check_added_monitors!(nodes[1], 1);
7754
7755         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7756         assert_eq!(revoked_htlc_txn.len(), 4);
7757         if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7758                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7759                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7760                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7761                 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7762                 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7763                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7764         } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7765                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7766                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7767                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7768                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7769                 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7770                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7771         }
7772
7773         // Broadcast set of revoked txn on A
7774         let hash_128 = connect_blocks(&nodes[0], 40);
7775         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7776         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7777         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7778         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7779         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7780         let first;
7781         let feerate_1;
7782         let penalty_txn;
7783         {
7784                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7785                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7786                 // Verify claim tx are spending revoked HTLC txn
7787
7788                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7789                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7790                 // which are included in the same block (they are broadcasted because we scan the
7791                 // transactions linearly and generate claims as we go, they likely should be removed in the
7792                 // future).
7793                 assert_eq!(node_txn[0].input.len(), 1);
7794                 check_spends!(node_txn[0], revoked_local_txn[0]);
7795                 assert_eq!(node_txn[1].input.len(), 1);
7796                 check_spends!(node_txn[1], revoked_local_txn[0]);
7797                 assert_eq!(node_txn[2].input.len(), 1);
7798                 check_spends!(node_txn[2], revoked_local_txn[0]);
7799
7800                 // Each of the three justice transactions claim a separate (single) output of the three
7801                 // available, which we check here:
7802                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7803                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7804                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7805
7806                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7807                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7808
7809                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7810                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7811                 // a remote commitment tx has already been confirmed).
7812                 check_spends!(node_txn[3], chan.3);
7813
7814                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7815                 // output, checked above).
7816                 assert_eq!(node_txn[4].input.len(), 2);
7817                 assert_eq!(node_txn[4].output.len(), 1);
7818                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7819
7820                 first = node_txn[4].txid();
7821                 // Store both feerates for later comparison
7822                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7823                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7824                 penalty_txn = vec![node_txn[2].clone()];
7825                 node_txn.clear();
7826         }
7827
7828         // Connect one more block to see if bumped penalty are issued for HTLC txn
7829         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7830         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7831         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7832         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7833         {
7834                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7835                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7836
7837                 check_spends!(node_txn[0], revoked_local_txn[0]);
7838                 check_spends!(node_txn[1], revoked_local_txn[0]);
7839                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7840                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7841                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7842                 } else {
7843                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7844                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7845                 }
7846
7847                 node_txn.clear();
7848         };
7849
7850         // Few more blocks to confirm penalty txn
7851         connect_blocks(&nodes[0], 4);
7852         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7853         let header_144 = connect_blocks(&nodes[0], 9);
7854         let node_txn = {
7855                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7856                 assert_eq!(node_txn.len(), 1);
7857
7858                 assert_eq!(node_txn[0].input.len(), 2);
7859                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7860                 // Verify bumped tx is different and 25% bump heuristic
7861                 assert_ne!(first, node_txn[0].txid());
7862                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7863                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7864                 assert!(feerate_2 * 100 > feerate_1 * 125);
7865                 let txn = vec![node_txn[0].clone()];
7866                 node_txn.clear();
7867                 txn
7868         };
7869         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7870         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7871         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7872         connect_blocks(&nodes[0], 20);
7873         {
7874                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7875                 // We verify than no new transaction has been broadcast because previously
7876                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7877                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7878                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7879                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7880                 // up bumped justice generation.
7881                 assert_eq!(node_txn.len(), 0);
7882                 node_txn.clear();
7883         }
7884         check_closed_broadcast!(nodes[0], true);
7885         check_added_monitors!(nodes[0], 1);
7886 }
7887
7888 #[test]
7889 fn test_bump_penalty_txn_on_remote_commitment() {
7890         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7891         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7892
7893         // Create 2 HTLCs
7894         // Provide preimage for one
7895         // Check aggregation
7896
7897         let chanmon_cfgs = create_chanmon_cfgs(2);
7898         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7899         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7900         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7901
7902         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7903         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7904         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7905
7906         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7907         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7908         assert_eq!(remote_txn[0].output.len(), 4);
7909         assert_eq!(remote_txn[0].input.len(), 1);
7910         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7911
7912         // Claim a HTLC without revocation (provide B monitor with preimage)
7913         nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7914         mine_transaction(&nodes[1], &remote_txn[0]);
7915         check_added_monitors!(nodes[1], 2);
7916
7917         // One or more claim tx should have been broadcast, check it
7918         let timeout;
7919         let preimage;
7920         let feerate_timeout;
7921         let feerate_preimage;
7922         {
7923                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7924                 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7925                 assert_eq!(node_txn[0].input.len(), 1);
7926                 assert_eq!(node_txn[1].input.len(), 1);
7927                 check_spends!(node_txn[0], remote_txn[0]);
7928                 check_spends!(node_txn[1], remote_txn[0]);
7929                 check_spends!(node_txn[2], chan.3);
7930                 check_spends!(node_txn[3], node_txn[2]);
7931                 check_spends!(node_txn[4], node_txn[2]);
7932                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7933                         timeout = node_txn[0].txid();
7934                         let index = node_txn[0].input[0].previous_output.vout;
7935                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7936                         feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7937
7938                         preimage = node_txn[1].txid();
7939                         let index = node_txn[1].input[0].previous_output.vout;
7940                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7941                         feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7942                 } else {
7943                         timeout = node_txn[1].txid();
7944                         let index = node_txn[1].input[0].previous_output.vout;
7945                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7946                         feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7947
7948                         preimage = node_txn[0].txid();
7949                         let index = node_txn[0].input[0].previous_output.vout;
7950                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7951                         feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7952                 }
7953                 node_txn.clear();
7954         };
7955         assert_ne!(feerate_timeout, 0);
7956         assert_ne!(feerate_preimage, 0);
7957
7958         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7959         connect_blocks(&nodes[1], 15);
7960         {
7961                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7962                 assert_eq!(node_txn.len(), 2);
7963                 assert_eq!(node_txn[0].input.len(), 1);
7964                 assert_eq!(node_txn[1].input.len(), 1);
7965                 check_spends!(node_txn[0], remote_txn[0]);
7966                 check_spends!(node_txn[1], remote_txn[0]);
7967                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7968                         let index = node_txn[0].input[0].previous_output.vout;
7969                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7970                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7971                         assert!(new_feerate * 100 > feerate_timeout * 125);
7972                         assert_ne!(timeout, node_txn[0].txid());
7973
7974                         let index = node_txn[1].input[0].previous_output.vout;
7975                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7976                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7977                         assert!(new_feerate * 100 > feerate_preimage * 125);
7978                         assert_ne!(preimage, node_txn[1].txid());
7979                 } else {
7980                         let index = node_txn[1].input[0].previous_output.vout;
7981                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7982                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7983                         assert!(new_feerate * 100 > feerate_timeout * 125);
7984                         assert_ne!(timeout, node_txn[1].txid());
7985
7986                         let index = node_txn[0].input[0].previous_output.vout;
7987                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7988                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7989                         assert!(new_feerate * 100 > feerate_preimage * 125);
7990                         assert_ne!(preimage, node_txn[0].txid());
7991                 }
7992                 node_txn.clear();
7993         }
7994
7995         nodes[1].node.get_and_clear_pending_events();
7996         nodes[1].node.get_and_clear_pending_msg_events();
7997 }
7998
7999 #[test]
8000 fn test_counterparty_raa_skip_no_crash() {
8001         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8002         // commitment transaction, we would have happily carried on and provided them the next
8003         // commitment transaction based on one RAA forward. This would probably eventually have led to
8004         // channel closure, but it would not have resulted in funds loss. Still, our
8005         // EnforcingSigner would have paniced as it doesn't like jumps into the future. Here, we
8006         // check simply that the channel is closed in response to such an RAA, but don't check whether
8007         // we decide to punish our counterparty for revoking their funds (as we don't currently
8008         // implement that).
8009         let chanmon_cfgs = create_chanmon_cfgs(2);
8010         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8011         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8012         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8013         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8014
8015         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8016         let keys = &guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8017         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8018         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8019         // Must revoke without gaps
8020         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8021         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8022                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8023
8024         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8025                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8026         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8027         check_added_monitors!(nodes[1], 1);
8028 }
8029
8030 #[test]
8031 fn test_bump_txn_sanitize_tracking_maps() {
8032         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8033         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8034
8035         let chanmon_cfgs = create_chanmon_cfgs(2);
8036         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8037         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8038         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8039
8040         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8041         // Lock HTLC in both directions
8042         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8043         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8044
8045         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8046         assert_eq!(revoked_local_txn[0].input.len(), 1);
8047         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8048
8049         // Revoke local commitment tx
8050         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8051
8052         // Broadcast set of revoked txn on A
8053         connect_blocks(&nodes[0], 52 - CHAN_CONFIRM_DEPTH);
8054         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8055         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8056
8057         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8058         check_closed_broadcast!(nodes[0], true);
8059         check_added_monitors!(nodes[0], 1);
8060         let penalty_txn = {
8061                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8062                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8063                 check_spends!(node_txn[0], revoked_local_txn[0]);
8064                 check_spends!(node_txn[1], revoked_local_txn[0]);
8065                 check_spends!(node_txn[2], revoked_local_txn[0]);
8066                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8067                 node_txn.clear();
8068                 penalty_txn
8069         };
8070         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8071         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8072         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8073         {
8074                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8075                 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8076                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8077                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8078                 }
8079         }
8080 }
8081
8082 #[test]
8083 fn test_override_channel_config() {
8084         let chanmon_cfgs = create_chanmon_cfgs(2);
8085         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8086         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8087         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8088
8089         // Node0 initiates a channel to node1 using the override config.
8090         let mut override_config = UserConfig::default();
8091         override_config.own_channel_config.our_to_self_delay = 200;
8092
8093         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8094
8095         // Assert the channel created by node0 is using the override config.
8096         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8097         assert_eq!(res.channel_flags, 0);
8098         assert_eq!(res.to_self_delay, 200);
8099 }
8100
8101 #[test]
8102 fn test_override_0msat_htlc_minimum() {
8103         let mut zero_config = UserConfig::default();
8104         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8105         let chanmon_cfgs = create_chanmon_cfgs(2);
8106         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8107         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8108         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8109
8110         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8111         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8112         assert_eq!(res.htlc_minimum_msat, 1);
8113
8114         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8115         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8116         assert_eq!(res.htlc_minimum_msat, 1);
8117 }
8118
8119 #[test]
8120 fn test_simple_payment_secret() {
8121         // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8122         // features, however.
8123         let chanmon_cfgs = create_chanmon_cfgs(3);
8124         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8125         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8126         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8127
8128         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8129         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8130         let logger = test_utils::TestLogger::new();
8131
8132         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8133         let payment_secret = PaymentSecret([0xdb; 32]);
8134         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8135         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();
8136         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8137         // Claiming with all the correct values but the wrong secret should result in nothing...
8138         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8139         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8140         // ...but with the right secret we should be able to claim all the way back
8141         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8142 }
8143
8144 #[test]
8145 fn test_simple_mpp() {
8146         // Simple test of sending a multi-path payment.
8147         let chanmon_cfgs = create_chanmon_cfgs(4);
8148         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8149         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8150         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8151
8152         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8153         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8154         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8155         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8156         let logger = test_utils::TestLogger::new();
8157
8158         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8159         let payment_secret = PaymentSecret([0xdb; 32]);
8160         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8161         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();
8162         let path = route.paths[0].clone();
8163         route.paths.push(path);
8164         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8165         route.paths[0][0].short_channel_id = chan_1_id;
8166         route.paths[0][1].short_channel_id = chan_3_id;
8167         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8168         route.paths[1][0].short_channel_id = chan_2_id;
8169         route.paths[1][1].short_channel_id = chan_4_id;
8170         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8171         // Claiming with all the correct values but the wrong secret should result in nothing...
8172         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8173         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8174         // ...but with the right secret we should be able to claim all the way back
8175         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8176 }
8177
8178 #[test]
8179 fn test_update_err_monitor_lockdown() {
8180         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8181         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8182         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8183         //
8184         // This scenario may happen in a watchtower setup, where watchtower process a block height
8185         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8186         // commitment at same time.
8187
8188         let chanmon_cfgs = create_chanmon_cfgs(2);
8189         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8190         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8191         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8192
8193         // Create some initial channel
8194         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8195         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8196
8197         // Rebalance the network to generate htlc in the two directions
8198         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8199
8200         // Route a HTLC from node 0 to node 1 (but don't settle)
8201         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8202
8203         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8204         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8205         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8206         let persister = test_utils::TestPersister::new();
8207         let watchtower = {
8208                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8209                 let monitor = monitors.get(&outpoint).unwrap();
8210                 let mut w = test_utils::TestVecWriter(Vec::new());
8211                 monitor.write(&mut w).unwrap();
8212                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8213                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8214                 assert!(new_monitor == *monitor);
8215                 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);
8216                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8217                 watchtower
8218         };
8219         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8220         watchtower.chain_monitor.block_connected(&header, &[], 200);
8221
8222         // Try to update ChannelMonitor
8223         assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8224         check_added_monitors!(nodes[1], 1);
8225         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8226         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8227         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8228         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8229                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8230                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8231                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8232                 } else { assert!(false); }
8233         } else { assert!(false); };
8234         // Our local monitor is in-sync and hasn't processed yet timeout
8235         check_added_monitors!(nodes[0], 1);
8236         let events = nodes[0].node.get_and_clear_pending_events();
8237         assert_eq!(events.len(), 1);
8238 }
8239
8240 #[test]
8241 fn test_concurrent_monitor_claim() {
8242         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8243         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8244         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8245         // state N+1 confirms. Alice claims output from state N+1.
8246
8247         let chanmon_cfgs = create_chanmon_cfgs(2);
8248         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8249         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8250         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8251
8252         // Create some initial channel
8253         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8254         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8255
8256         // Rebalance the network to generate htlc in the two directions
8257         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8258
8259         // Route a HTLC from node 0 to node 1 (but don't settle)
8260         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8261
8262         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8263         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8264         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8265         let persister = test_utils::TestPersister::new();
8266         let watchtower_alice = {
8267                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8268                 let monitor = monitors.get(&outpoint).unwrap();
8269                 let mut w = test_utils::TestVecWriter(Vec::new());
8270                 monitor.write(&mut w).unwrap();
8271                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8272                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8273                 assert!(new_monitor == *monitor);
8274                 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);
8275                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8276                 watchtower
8277         };
8278         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8279         watchtower_alice.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8280
8281         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8282         {
8283                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8284                 assert_eq!(txn.len(), 2);
8285                 txn.clear();
8286         }
8287
8288         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8289         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8290         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8291         let persister = test_utils::TestPersister::new();
8292         let watchtower_bob = {
8293                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8294                 let monitor = monitors.get(&outpoint).unwrap();
8295                 let mut w = test_utils::TestVecWriter(Vec::new());
8296                 monitor.write(&mut w).unwrap();
8297                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8298                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8299                 assert!(new_monitor == *monitor);
8300                 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);
8301                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8302                 watchtower
8303         };
8304         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8305         watchtower_bob.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8306
8307         // Route another payment to generate another update with still previous HTLC pending
8308         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8309         {
8310                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8311                 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();
8312                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8313         }
8314         check_added_monitors!(nodes[1], 1);
8315
8316         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8317         assert_eq!(updates.update_add_htlcs.len(), 1);
8318         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8319         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8320                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8321                         // Watchtower Alice should already have seen the block and reject the update
8322                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8323                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8324                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8325                 } else { assert!(false); }
8326         } else { assert!(false); };
8327         // Our local monitor is in-sync and hasn't processed yet timeout
8328         check_added_monitors!(nodes[0], 1);
8329
8330         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8331         watchtower_bob.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8332
8333         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8334         let bob_state_y;
8335         {
8336                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8337                 assert_eq!(txn.len(), 2);
8338                 bob_state_y = txn[0].clone();
8339                 txn.clear();
8340         };
8341
8342         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8343         watchtower_alice.chain_monitor.block_connected(&header, &vec![(0, &bob_state_y)], CHAN_CONFIRM_DEPTH + 2 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8344         {
8345                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8346                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8347                 // the onchain detection of the HTLC output
8348                 assert_eq!(htlc_txn.len(), 2);
8349                 check_spends!(htlc_txn[0], bob_state_y);
8350                 check_spends!(htlc_txn[1], bob_state_y);
8351         }
8352 }
8353
8354 #[test]
8355 fn test_pre_lockin_no_chan_closed_update() {
8356         // Test that if a peer closes a channel in response to a funding_created message we don't
8357         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8358         // message).
8359         //
8360         // Doing so would imply a channel monitor update before the initial channel monitor
8361         // registration, violating our API guarantees.
8362         //
8363         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8364         // then opening a second channel with the same funding output as the first (which is not
8365         // rejected because the first channel does not exist in the ChannelManager) and closing it
8366         // before receiving funding_signed.
8367         let chanmon_cfgs = create_chanmon_cfgs(2);
8368         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8369         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8370         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8371
8372         // Create an initial channel
8373         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8374         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8375         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8376         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8377         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8378
8379         // Move the first channel through the funding flow...
8380         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8381
8382         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8383         check_added_monitors!(nodes[0], 0);
8384
8385         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8386         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8387         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8388         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8389 }
8390
8391 #[test]
8392 fn test_htlc_no_detection() {
8393         // This test is a mutation to underscore the detection logic bug we had
8394         // before #653. HTLC value routed is above the remaining balance, thus
8395         // inverting HTLC and `to_remote` output. HTLC will come second and
8396         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8397         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8398         // outputs order detection for correct spending children filtring.
8399
8400         let chanmon_cfgs = create_chanmon_cfgs(2);
8401         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8402         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8403         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8404
8405         // Create some initial channels
8406         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8407
8408         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000, 1_000_000);
8409         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8410         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8411         assert_eq!(local_txn[0].input.len(), 1);
8412         assert_eq!(local_txn[0].output.len(), 3);
8413         check_spends!(local_txn[0], chan_1.3);
8414
8415         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8416         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8417         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8418         // We deliberately connect the local tx twice as this should provoke a failure calling
8419         // this test before #653 fix.
8420         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);
8421         check_closed_broadcast!(nodes[0], true);
8422         check_added_monitors!(nodes[0], 1);
8423
8424         let htlc_timeout = {
8425                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8426                 assert_eq!(node_txn[0].input.len(), 1);
8427                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8428                 check_spends!(node_txn[0], local_txn[0]);
8429                 node_txn[0].clone()
8430         };
8431
8432         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8433         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8434         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8435         expect_payment_failed!(nodes[0], our_payment_hash, true);
8436 }
8437
8438 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8439         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8440         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8441         // Carol, Alice would be the upstream node, and Carol the downstream.)
8442         //
8443         // Steps of the test:
8444         // 1) Alice sends a HTLC to Carol through Bob.
8445         // 2) Carol doesn't settle the HTLC.
8446         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8447         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8448         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8449         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8450         // 5) Carol release the preimage to Bob off-chain.
8451         // 6) Bob claims the offered output on the broadcasted commitment.
8452         let chanmon_cfgs = create_chanmon_cfgs(3);
8453         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8454         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8455         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8456
8457         // Create some initial channels
8458         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8459         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8460
8461         // Steps (1) and (2):
8462         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8463         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8464
8465         // Check that Alice's commitment transaction now contains an output for this HTLC.
8466         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8467         check_spends!(alice_txn[0], chan_ab.3);
8468         assert_eq!(alice_txn[0].output.len(), 2);
8469         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8470         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8471         assert_eq!(alice_txn.len(), 2);
8472
8473         // Steps (3) and (4):
8474         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8475         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8476         let mut force_closing_node = 0; // Alice force-closes
8477         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8478         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8479         check_closed_broadcast!(nodes[force_closing_node], true);
8480         check_added_monitors!(nodes[force_closing_node], 1);
8481         if go_onchain_before_fulfill {
8482                 let txn_to_broadcast = match broadcast_alice {
8483                         true => alice_txn.clone(),
8484                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8485                 };
8486                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8487                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8488                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8489                 if broadcast_alice {
8490                         check_closed_broadcast!(nodes[1], true);
8491                         check_added_monitors!(nodes[1], 1);
8492                 }
8493                 assert_eq!(bob_txn.len(), 1);
8494                 check_spends!(bob_txn[0], chan_ab.3);
8495         }
8496
8497         // Step (5):
8498         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8499         // process of removing the HTLC from their commitment transactions.
8500         assert!(nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000));
8501         check_added_monitors!(nodes[2], 1);
8502         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8503         assert!(carol_updates.update_add_htlcs.is_empty());
8504         assert!(carol_updates.update_fail_htlcs.is_empty());
8505         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8506         assert!(carol_updates.update_fee.is_none());
8507         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8508
8509         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8510         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8511         if !go_onchain_before_fulfill && broadcast_alice {
8512                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8513                 assert_eq!(events.len(), 1);
8514                 match events[0] {
8515                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8516                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8517                         },
8518                         _ => panic!("Unexpected event"),
8519                 };
8520         }
8521         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8522         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8523         // Carol<->Bob's updated commitment transaction info.
8524         check_added_monitors!(nodes[1], 2);
8525
8526         let events = nodes[1].node.get_and_clear_pending_msg_events();
8527         assert_eq!(events.len(), 2);
8528         let bob_revocation = match events[0] {
8529                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8530                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8531                         (*msg).clone()
8532                 },
8533                 _ => panic!("Unexpected event"),
8534         };
8535         let bob_updates = match events[1] {
8536                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8537                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8538                         (*updates).clone()
8539                 },
8540                 _ => panic!("Unexpected event"),
8541         };
8542
8543         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8544         check_added_monitors!(nodes[2], 1);
8545         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8546         check_added_monitors!(nodes[2], 1);
8547
8548         let events = nodes[2].node.get_and_clear_pending_msg_events();
8549         assert_eq!(events.len(), 1);
8550         let carol_revocation = match events[0] {
8551                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8552                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8553                         (*msg).clone()
8554                 },
8555                 _ => panic!("Unexpected event"),
8556         };
8557         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8558         check_added_monitors!(nodes[1], 1);
8559
8560         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8561         // here's where we put said channel's commitment tx on-chain.
8562         let mut txn_to_broadcast = alice_txn.clone();
8563         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8564         if !go_onchain_before_fulfill {
8565                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8566                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8567                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8568                 if broadcast_alice {
8569                         check_closed_broadcast!(nodes[1], true);
8570                         check_added_monitors!(nodes[1], 1);
8571                 }
8572                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8573                 if broadcast_alice {
8574                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8575                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8576                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8577                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8578                         // broadcasted.
8579                         assert_eq!(bob_txn.len(), 3);
8580                         check_spends!(bob_txn[1], chan_ab.3);
8581                 } else {
8582                         assert_eq!(bob_txn.len(), 2);
8583                         check_spends!(bob_txn[0], chan_ab.3);
8584                 }
8585         }
8586
8587         // Step (6):
8588         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8589         // broadcasted commitment transaction.
8590         {
8591                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8592                 if go_onchain_before_fulfill {
8593                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8594                         assert_eq!(bob_txn.len(), 2);
8595                 }
8596                 let script_weight = match broadcast_alice {
8597                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8598                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8599                 };
8600                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8601                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8602                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8603                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8604                 if broadcast_alice && !go_onchain_before_fulfill {
8605                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8606                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8607                 } else {
8608                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8609                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8610                 }
8611         }
8612 }
8613
8614 #[test]
8615 fn test_onchain_htlc_settlement_after_close() {
8616         do_test_onchain_htlc_settlement_after_close(true, true);
8617         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8618         do_test_onchain_htlc_settlement_after_close(true, false);
8619         do_test_onchain_htlc_settlement_after_close(false, false);
8620 }
8621
8622 #[test]
8623 fn test_duplicate_chan_id() {
8624         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8625         // already open we reject it and keep the old channel.
8626         //
8627         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8628         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8629         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8630         // updating logic for the existing channel.
8631         let chanmon_cfgs = create_chanmon_cfgs(2);
8632         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8633         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8634         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8635
8636         // Create an initial channel
8637         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8638         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8639         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8640         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()));
8641
8642         // Try to create a second channel with the same temporary_channel_id as the first and check
8643         // that it is rejected.
8644         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8645         {
8646                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8647                 assert_eq!(events.len(), 1);
8648                 match events[0] {
8649                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8650                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8651                                 // first (valid) and second (invalid) channels are closed, given they both have
8652                                 // the same non-temporary channel_id. However, currently we do not, so we just
8653                                 // move forward with it.
8654                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8655                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8656                         },
8657                         _ => panic!("Unexpected event"),
8658                 }
8659         }
8660
8661         // Move the first channel through the funding flow...
8662         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8663
8664         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8665         check_added_monitors!(nodes[0], 0);
8666
8667         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8668         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8669         {
8670                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8671                 assert_eq!(added_monitors.len(), 1);
8672                 assert_eq!(added_monitors[0].0, funding_output);
8673                 added_monitors.clear();
8674         }
8675         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8676
8677         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8678         let channel_id = funding_outpoint.to_channel_id();
8679
8680         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8681         // temporary one).
8682
8683         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8684         // Technically this is allowed by the spec, but we don't support it and there's little reason
8685         // to. Still, it shouldn't cause any other issues.
8686         open_chan_msg.temporary_channel_id = channel_id;
8687         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8688         {
8689                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8690                 assert_eq!(events.len(), 1);
8691                 match events[0] {
8692                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8693                                 // Technically, at this point, nodes[1] would be justified in thinking both
8694                                 // channels are closed, but currently we do not, so we just move forward with it.
8695                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8696                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8697                         },
8698                         _ => panic!("Unexpected event"),
8699                 }
8700         }
8701
8702         // Now try to create a second channel which has a duplicate funding output.
8703         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8704         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8705         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8706         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()));
8707         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8708
8709         let funding_created = {
8710                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8711                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8712                 let logger = test_utils::TestLogger::new();
8713                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8714         };
8715         check_added_monitors!(nodes[0], 0);
8716         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8717         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8718         // still needs to be cleared here.
8719         check_added_monitors!(nodes[1], 1);
8720
8721         // ...still, nodes[1] will reject the duplicate channel.
8722         {
8723                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8724                 assert_eq!(events.len(), 1);
8725                 match events[0] {
8726                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8727                                 // Technically, at this point, nodes[1] would be justified in thinking both
8728                                 // channels are closed, but currently we do not, so we just move forward with it.
8729                                 assert_eq!(msg.channel_id, channel_id);
8730                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8731                         },
8732                         _ => panic!("Unexpected event"),
8733                 }
8734         }
8735
8736         // finally, finish creating the original channel and send a payment over it to make sure
8737         // everything is functional.
8738         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8739         {
8740                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8741                 assert_eq!(added_monitors.len(), 1);
8742                 assert_eq!(added_monitors[0].0, funding_output);
8743                 added_monitors.clear();
8744         }
8745
8746         let events_4 = nodes[0].node.get_and_clear_pending_events();
8747         assert_eq!(events_4.len(), 0);
8748         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8749         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
8750
8751         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8752         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8753         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8754         send_payment(&nodes[0], &[&nodes[1]], 8000000, 8_000_000);
8755 }
8756
8757 #[test]
8758 fn test_error_chans_closed() {
8759         // Test that we properly handle error messages, closing appropriate channels.
8760         //
8761         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8762         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8763         // we can test various edge cases around it to ensure we don't regress.
8764         let chanmon_cfgs = create_chanmon_cfgs(3);
8765         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8766         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8767         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8768
8769         // Create some initial channels
8770         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8771         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8772         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8773
8774         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8775         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8776         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8777
8778         // Closing a channel from a different peer has no effect
8779         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8780         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8781
8782         // Closing one channel doesn't impact others
8783         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8784         check_added_monitors!(nodes[0], 1);
8785         check_closed_broadcast!(nodes[0], false);
8786         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8787         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8788         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);
8789         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);
8790
8791         // A null channel ID should close all channels
8792         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8793         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8794         check_added_monitors!(nodes[0], 2);
8795         let events = nodes[0].node.get_and_clear_pending_msg_events();
8796         assert_eq!(events.len(), 2);
8797         match events[0] {
8798                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8799                         assert_eq!(msg.contents.flags & 2, 2);
8800                 },
8801                 _ => panic!("Unexpected event"),
8802         }
8803         match events[1] {
8804                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8805                         assert_eq!(msg.contents.flags & 2, 2);
8806                 },
8807                 _ => panic!("Unexpected event"),
8808         }
8809         // Note that at this point users of a standard PeerHandler will end up calling
8810         // peer_disconnected with no_connection_possible set to false, duplicating the
8811         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8812         // users with their own peer handling logic. We duplicate the call here, however.
8813         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8814         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8815
8816         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8817         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8818         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8819 }