Add an Option<>al InvoiceFeatures object for the payee in get_route
[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::Watch;
15 use chain::channelmonitor;
16 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
17 use chain::transaction::OutPoint;
18 use chain::keysinterface::{Sign, KeysInterface};
19 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
20 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
21 use ln::channel::{Channel, ChannelError};
22 use ln::{chan_utils, onion_utils};
23 use routing::router::{Route, RouteHop, get_route};
24 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
25 use ln::msgs;
26 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
27 use util::enforcing_trait_impls::EnforcingSigner;
28 use util::{byte_utils, test_utils};
29 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
30 use util::errors::APIError;
31 use util::ser::{Writeable, ReadableArgs};
32 use util::config::UserConfig;
33
34 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
35 use bitcoin::hash_types::{Txid, BlockHash};
36 use bitcoin::blockdata::block::{Block, BlockHeader};
37 use bitcoin::blockdata::script::Builder;
38 use bitcoin::blockdata::opcodes;
39 use bitcoin::blockdata::constants::genesis_block;
40 use bitcoin::network::constants::Network;
41
42 use bitcoin::hashes::sha256::Hash as Sha256;
43 use bitcoin::hashes::Hash;
44
45 use bitcoin::secp256k1::{Secp256k1, Message};
46 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
47
48 use regex;
49
50 use std::collections::{BTreeSet, HashMap, HashSet};
51 use std::default::Default;
52 use std::sync::Mutex;
53 use std::sync::atomic::Ordering;
54
55 use ln::functional_test_utils::*;
56 use ln::chan_utils::CommitmentTransaction;
57 use ln::msgs::OptionalField::Present;
58
59 #[test]
60 fn test_insane_channel_opens() {
61         // Stand up a network of 2 nodes
62         let chanmon_cfgs = create_chanmon_cfgs(2);
63         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
64         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
65         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
66
67         // Instantiate channel parameters where we push the maximum msats given our
68         // funding satoshis
69         let channel_value_sat = 31337; // same as funding satoshis
70         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
71         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
72
73         // Have node0 initiate a channel to node1 with aforementioned parameters
74         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
75
76         // Extract the channel open message from node0 to node1
77         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
78
79         // Test helper that asserts we get the correct error string given a mutator
80         // that supposedly makes the channel open message insane
81         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
82                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
83                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
84                 assert_eq!(msg_events.len(), 1);
85                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
86                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
87                         match action {
88                                 &ErrorAction::SendErrorMessage { .. } => {
89                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
90                                 },
91                                 _ => panic!("unexpected event!"),
92                         }
93                 } else { assert!(false); }
94         };
95
96         use ln::channel::MAX_FUNDING_SATOSHIS;
97         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
98
99         // Test all mutations that would make the channel open message insane
100         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 });
101
102         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
103
104         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 });
105
106         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
107
108         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 });
109
110         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 });
111
112         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 });
113
114         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
115
116         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
117 }
118
119 #[test]
120 fn test_async_inbound_update_fee() {
121         let chanmon_cfgs = create_chanmon_cfgs(2);
122         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
123         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
124         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
125         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
126         let logger = test_utils::TestLogger::new();
127         let channel_id = chan.2;
128
129         // balancing
130         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
131
132         // A                                        B
133         // update_fee                            ->
134         // send (1) commitment_signed            -.
135         //                                       <- update_add_htlc/commitment_signed
136         // send (2) RAA (awaiting remote revoke) -.
137         // (1) commitment_signed is delivered    ->
138         //                                       .- send (3) RAA (awaiting remote revoke)
139         // (2) RAA is delivered                  ->
140         //                                       .- send (4) commitment_signed
141         //                                       <- (3) RAA is delivered
142         // send (5) commitment_signed            -.
143         //                                       <- (4) commitment_signed is delivered
144         // send (6) RAA                          -.
145         // (5) commitment_signed is delivered    ->
146         //                                       <- RAA
147         // (6) RAA is delivered                  ->
148
149         // First nodes[0] generates an update_fee
150         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
151         check_added_monitors!(nodes[0], 1);
152
153         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
154         assert_eq!(events_0.len(), 1);
155         let (update_msg, commitment_signed) = match events_0[0] { // (1)
156                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
157                         (update_fee.as_ref(), commitment_signed)
158                 },
159                 _ => panic!("Unexpected event"),
160         };
161
162         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
163
164         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
165         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
166         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
167         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();
168         check_added_monitors!(nodes[1], 1);
169
170         let payment_event = {
171                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
172                 assert_eq!(events_1.len(), 1);
173                 SendEvent::from_event(events_1.remove(0))
174         };
175         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
176         assert_eq!(payment_event.msgs.len(), 1);
177
178         // ...now when the messages get delivered everyone should be happy
179         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
180         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
181         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
182         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
183         check_added_monitors!(nodes[0], 1);
184
185         // deliver(1), generate (3):
186         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
187         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
188         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
189         check_added_monitors!(nodes[1], 1);
190
191         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
192         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
193         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
194         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
195         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
196         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
197         assert!(bs_update.update_fee.is_none()); // (4)
198         check_added_monitors!(nodes[1], 1);
199
200         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
201         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
202         assert!(as_update.update_add_htlcs.is_empty()); // (5)
203         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
204         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
205         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
206         assert!(as_update.update_fee.is_none()); // (5)
207         check_added_monitors!(nodes[0], 1);
208
209         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
210         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
211         // only (6) so get_event_msg's assert(len == 1) passes
212         check_added_monitors!(nodes[0], 1);
213
214         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
215         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
216         check_added_monitors!(nodes[1], 1);
217
218         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
219         check_added_monitors!(nodes[0], 1);
220
221         let events_2 = nodes[0].node.get_and_clear_pending_events();
222         assert_eq!(events_2.len(), 1);
223         match events_2[0] {
224                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
225                 _ => panic!("Unexpected event"),
226         }
227
228         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
229         check_added_monitors!(nodes[1], 1);
230 }
231
232 #[test]
233 fn test_update_fee_unordered_raa() {
234         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
235         // crash in an earlier version of the update_fee patch)
236         let chanmon_cfgs = create_chanmon_cfgs(2);
237         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
238         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
239         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
240         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
241         let channel_id = chan.2;
242         let logger = test_utils::TestLogger::new();
243
244         // balancing
245         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
246
247         // First nodes[0] generates an update_fee
248         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
249         check_added_monitors!(nodes[0], 1);
250
251         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
252         assert_eq!(events_0.len(), 1);
253         let update_msg = match events_0[0] { // (1)
254                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
255                         update_fee.as_ref()
256                 },
257                 _ => panic!("Unexpected event"),
258         };
259
260         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
261
262         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
263         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
264         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
265         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();
266         check_added_monitors!(nodes[1], 1);
267
268         let payment_event = {
269                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
270                 assert_eq!(events_1.len(), 1);
271                 SendEvent::from_event(events_1.remove(0))
272         };
273         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
274         assert_eq!(payment_event.msgs.len(), 1);
275
276         // ...now when the messages get delivered everyone should be happy
277         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
278         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
279         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
280         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
281         check_added_monitors!(nodes[0], 1);
282
283         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
284         check_added_monitors!(nodes[1], 1);
285
286         // We can't continue, sadly, because our (1) now has a bogus signature
287 }
288
289 #[test]
290 fn test_multi_flight_update_fee() {
291         let chanmon_cfgs = create_chanmon_cfgs(2);
292         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
293         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
294         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
295         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
296         let channel_id = chan.2;
297
298         // A                                        B
299         // update_fee/commitment_signed          ->
300         //                                       .- send (1) RAA and (2) commitment_signed
301         // update_fee (never committed)          ->
302         // (3) update_fee                        ->
303         // We have to manually generate the above update_fee, it is allowed by the protocol but we
304         // don't track which updates correspond to which revoke_and_ack responses so we're in
305         // AwaitingRAA mode and will not generate the update_fee yet.
306         //                                       <- (1) RAA delivered
307         // (3) is generated and send (4) CS      -.
308         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
309         // know the per_commitment_point to use for it.
310         //                                       <- (2) commitment_signed delivered
311         // revoke_and_ack                        ->
312         //                                          B should send no response here
313         // (4) commitment_signed delivered       ->
314         //                                       <- RAA/commitment_signed delivered
315         // revoke_and_ack                        ->
316
317         // First nodes[0] generates an update_fee
318         let initial_feerate = get_feerate!(nodes[0], channel_id);
319         nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
320         check_added_monitors!(nodes[0], 1);
321
322         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
323         assert_eq!(events_0.len(), 1);
324         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
325                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
326                         (update_fee.as_ref().unwrap(), commitment_signed)
327                 },
328                 _ => panic!("Unexpected event"),
329         };
330
331         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
332         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
333         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
334         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
335         check_added_monitors!(nodes[1], 1);
336
337         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
338         // transaction:
339         nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
340         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
341         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
342
343         // Create the (3) update_fee message that nodes[0] will generate before it does...
344         let mut update_msg_2 = msgs::UpdateFee {
345                 channel_id: update_msg_1.channel_id.clone(),
346                 feerate_per_kw: (initial_feerate + 30) as u32,
347         };
348
349         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
350
351         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
352         // Deliver (3)
353         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
354
355         // Deliver (1), generating (3) and (4)
356         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
357         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
358         check_added_monitors!(nodes[0], 1);
359         assert!(as_second_update.update_add_htlcs.is_empty());
360         assert!(as_second_update.update_fulfill_htlcs.is_empty());
361         assert!(as_second_update.update_fail_htlcs.is_empty());
362         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
363         // Check that the update_fee newly generated matches what we delivered:
364         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
365         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
366
367         // Deliver (2) commitment_signed
368         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
369         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
370         check_added_monitors!(nodes[0], 1);
371         // No commitment_signed so get_event_msg's assert(len == 1) passes
372
373         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
374         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
375         check_added_monitors!(nodes[1], 1);
376
377         // Delever (4)
378         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
379         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
380         check_added_monitors!(nodes[1], 1);
381
382         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
383         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
384         check_added_monitors!(nodes[0], 1);
385
386         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
387         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
388         // No commitment_signed so get_event_msg's assert(len == 1) passes
389         check_added_monitors!(nodes[0], 1);
390
391         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
392         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
393         check_added_monitors!(nodes[1], 1);
394 }
395
396 #[test]
397 fn test_1_conf_open() {
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 nodes = create_network(2, &node_cfgs, &node_chanmgrs);
412
413         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
414         let block = Block {
415                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
416                 txdata: vec![tx],
417         };
418         connect_block(&nodes[1], &block, 1);
419         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()));
420
421         connect_block(&nodes[0], &block, 1);
422         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
423         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
424
425         for node in nodes {
426                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
427                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
428                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
429         }
430 }
431
432 fn do_test_sanity_on_in_flight_opens(steps: u8) {
433         // Previously, we had issues deserializing channels when we hadn't connected the first block
434         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
435         // serialization round-trips and simply do steps towards opening a channel and then drop the
436         // Node objects.
437
438         let chanmon_cfgs = create_chanmon_cfgs(2);
439         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
440         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
441         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
442
443         if steps & 0b1000_0000 != 0{
444                 let block = Block {
445                         header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
446                         txdata: vec![],
447                 };
448                 connect_block(&nodes[0], &block, 1);
449                 connect_block(&nodes[1], &block, 1);
450         }
451
452         if steps & 0x0f == 0 { return; }
453         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
454         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
455
456         if steps & 0x0f == 1 { return; }
457         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
458         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
459
460         if steps & 0x0f == 2 { return; }
461         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
462
463         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
464
465         if steps & 0x0f == 3 { return; }
466         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
467         check_added_monitors!(nodes[0], 0);
468         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
469
470         if steps & 0x0f == 4 { return; }
471         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
472         {
473                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
474                 assert_eq!(added_monitors.len(), 1);
475                 assert_eq!(added_monitors[0].0, funding_output);
476                 added_monitors.clear();
477         }
478         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
479
480         if steps & 0x0f == 5 { return; }
481         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
482         {
483                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
484                 assert_eq!(added_monitors.len(), 1);
485                 assert_eq!(added_monitors[0].0, funding_output);
486                 added_monitors.clear();
487         }
488
489         let events_4 = nodes[0].node.get_and_clear_pending_events();
490         assert_eq!(events_4.len(), 1);
491         match events_4[0] {
492                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
493                         assert_eq!(user_channel_id, 42);
494                         assert_eq!(*funding_txo, funding_output);
495                 },
496                 _ => panic!("Unexpected event"),
497         };
498
499         if steps & 0x0f == 6 { return; }
500         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
501
502         if steps & 0x0f == 7 { return; }
503         confirm_transaction(&nodes[0], &tx);
504         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
505 }
506
507 #[test]
508 fn test_sanity_on_in_flight_opens() {
509         do_test_sanity_on_in_flight_opens(0);
510         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
511         do_test_sanity_on_in_flight_opens(1);
512         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
513         do_test_sanity_on_in_flight_opens(2);
514         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
515         do_test_sanity_on_in_flight_opens(3);
516         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
517         do_test_sanity_on_in_flight_opens(4);
518         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
519         do_test_sanity_on_in_flight_opens(5);
520         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
521         do_test_sanity_on_in_flight_opens(6);
522         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
523         do_test_sanity_on_in_flight_opens(7);
524         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
525         do_test_sanity_on_in_flight_opens(8);
526         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
527 }
528
529 #[test]
530 fn test_update_fee_vanilla() {
531         let chanmon_cfgs = create_chanmon_cfgs(2);
532         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
533         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
534         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
535         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
536         let channel_id = chan.2;
537
538         let feerate = get_feerate!(nodes[0], channel_id);
539         nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
540         check_added_monitors!(nodes[0], 1);
541
542         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
543         assert_eq!(events_0.len(), 1);
544         let (update_msg, commitment_signed) = match events_0[0] {
545                         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 } } => {
546                         (update_fee.as_ref(), commitment_signed)
547                 },
548                 _ => panic!("Unexpected event"),
549         };
550         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
551
552         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
553         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
554         check_added_monitors!(nodes[1], 1);
555
556         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
557         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
558         check_added_monitors!(nodes[0], 1);
559
560         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
561         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
562         // No commitment_signed so get_event_msg's assert(len == 1) passes
563         check_added_monitors!(nodes[0], 1);
564
565         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
566         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
567         check_added_monitors!(nodes[1], 1);
568 }
569
570 #[test]
571 fn test_update_fee_that_funder_cannot_afford() {
572         let chanmon_cfgs = create_chanmon_cfgs(2);
573         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
574         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
575         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
576         let channel_value = 1888;
577         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
578         let channel_id = chan.2;
579
580         let feerate = 260;
581         nodes[0].node.update_fee(channel_id, feerate).unwrap();
582         check_added_monitors!(nodes[0], 1);
583         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
584
585         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
586
587         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
588
589         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
590         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
591         {
592                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
593
594                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
595                 let num_htlcs = commitment_tx.output.len() - 2;
596                 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
597                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
598                 actual_fee = channel_value - actual_fee;
599                 assert_eq!(total_fee, actual_fee);
600         }
601
602         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
603         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
604         nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
605         check_added_monitors!(nodes[0], 1);
606
607         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
608
609         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
610
611         //While producing the commitment_signed response after handling a received update_fee request the
612         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
613         //Should produce and error.
614         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
615         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
616         check_added_monitors!(nodes[1], 1);
617         check_closed_broadcast!(nodes[1], true);
618 }
619
620 #[test]
621 fn test_update_fee_with_fundee_update_add_htlc() {
622         let chanmon_cfgs = create_chanmon_cfgs(2);
623         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
624         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
625         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
626         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
627         let channel_id = chan.2;
628         let logger = test_utils::TestLogger::new();
629
630         // balancing
631         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
632
633         let feerate = get_feerate!(nodes[0], channel_id);
634         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
635         check_added_monitors!(nodes[0], 1);
636
637         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
638         assert_eq!(events_0.len(), 1);
639         let (update_msg, commitment_signed) = match events_0[0] {
640                         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 } } => {
641                         (update_fee.as_ref(), commitment_signed)
642                 },
643                 _ => panic!("Unexpected event"),
644         };
645         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
646         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
647         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
648         check_added_monitors!(nodes[1], 1);
649
650         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
651         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
652         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();
653
654         // nothing happens since node[1] is in AwaitingRemoteRevoke
655         nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
656         {
657                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
658                 assert_eq!(added_monitors.len(), 0);
659                 added_monitors.clear();
660         }
661         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
662         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
663         // node[1] has nothing to do
664
665         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
666         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
667         check_added_monitors!(nodes[0], 1);
668
669         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
670         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
671         // No commitment_signed so get_event_msg's assert(len == 1) passes
672         check_added_monitors!(nodes[0], 1);
673         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
674         check_added_monitors!(nodes[1], 1);
675         // AwaitingRemoteRevoke ends here
676
677         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
678         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
679         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
680         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
681         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
682         assert_eq!(commitment_update.update_fee.is_none(), true);
683
684         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
685         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
686         check_added_monitors!(nodes[0], 1);
687         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
688
689         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
690         check_added_monitors!(nodes[1], 1);
691         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
692
693         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
694         check_added_monitors!(nodes[1], 1);
695         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
696         // No commitment_signed so get_event_msg's assert(len == 1) passes
697
698         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
699         check_added_monitors!(nodes[0], 1);
700         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
701
702         expect_pending_htlcs_forwardable!(nodes[0]);
703
704         let events = nodes[0].node.get_and_clear_pending_events();
705         assert_eq!(events.len(), 1);
706         match events[0] {
707                 Event::PaymentReceived { .. } => { },
708                 _ => panic!("Unexpected event"),
709         };
710
711         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
712
713         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
714         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
715         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
716 }
717
718 #[test]
719 fn test_update_fee() {
720         let chanmon_cfgs = create_chanmon_cfgs(2);
721         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
722         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
723         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
724         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
725         let channel_id = chan.2;
726
727         // A                                        B
728         // (1) update_fee/commitment_signed      ->
729         //                                       <- (2) revoke_and_ack
730         //                                       .- send (3) commitment_signed
731         // (4) update_fee/commitment_signed      ->
732         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
733         //                                       <- (3) commitment_signed delivered
734         // send (6) revoke_and_ack               -.
735         //                                       <- (5) deliver revoke_and_ack
736         // (6) deliver revoke_and_ack            ->
737         //                                       .- send (7) commitment_signed in response to (4)
738         //                                       <- (7) deliver commitment_signed
739         // revoke_and_ack                        ->
740
741         // Create and deliver (1)...
742         let feerate = get_feerate!(nodes[0], channel_id);
743         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
744         check_added_monitors!(nodes[0], 1);
745
746         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
747         assert_eq!(events_0.len(), 1);
748         let (update_msg, commitment_signed) = match events_0[0] {
749                         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 } } => {
750                         (update_fee.as_ref(), commitment_signed)
751                 },
752                 _ => panic!("Unexpected event"),
753         };
754         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
755
756         // Generate (2) and (3):
757         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
758         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
759         check_added_monitors!(nodes[1], 1);
760
761         // Deliver (2):
762         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
763         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
764         check_added_monitors!(nodes[0], 1);
765
766         // Create and deliver (4)...
767         nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
768         check_added_monitors!(nodes[0], 1);
769         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
770         assert_eq!(events_0.len(), 1);
771         let (update_msg, commitment_signed) = match events_0[0] {
772                         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 } } => {
773                         (update_fee.as_ref(), commitment_signed)
774                 },
775                 _ => panic!("Unexpected event"),
776         };
777
778         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
779         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
780         check_added_monitors!(nodes[1], 1);
781         // ... creating (5)
782         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
783         // No commitment_signed so get_event_msg's assert(len == 1) passes
784
785         // Handle (3), creating (6):
786         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
787         check_added_monitors!(nodes[0], 1);
788         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
789         // No commitment_signed so get_event_msg's assert(len == 1) passes
790
791         // Deliver (5):
792         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
793         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
794         check_added_monitors!(nodes[0], 1);
795
796         // Deliver (6), creating (7):
797         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
798         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
799         assert!(commitment_update.update_add_htlcs.is_empty());
800         assert!(commitment_update.update_fulfill_htlcs.is_empty());
801         assert!(commitment_update.update_fail_htlcs.is_empty());
802         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
803         assert!(commitment_update.update_fee.is_none());
804         check_added_monitors!(nodes[1], 1);
805
806         // Deliver (7)
807         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
808         check_added_monitors!(nodes[0], 1);
809         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
810         // No commitment_signed so get_event_msg's assert(len == 1) passes
811
812         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
813         check_added_monitors!(nodes[1], 1);
814         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
815
816         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
817         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
818         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
819 }
820
821 #[test]
822 fn pre_funding_lock_shutdown_test() {
823         // Test sending a shutdown prior to funding_locked after funding generation
824         let chanmon_cfgs = create_chanmon_cfgs(2);
825         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
826         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
827         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
828         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
829         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
830         connect_block(&nodes[0], &Block { header, txdata: vec![tx.clone()]}, 1);
831         connect_block(&nodes[1], &Block { header, txdata: vec![tx.clone()]}, 1);
832
833         nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
834         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
835         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
836         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
837         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
838
839         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
840         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
841         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
842         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
843         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
844         assert!(node_0_none.is_none());
845
846         assert!(nodes[0].node.list_channels().is_empty());
847         assert!(nodes[1].node.list_channels().is_empty());
848 }
849
850 #[test]
851 fn updates_shutdown_wait() {
852         // Test sending a shutdown with outstanding updates pending
853         let chanmon_cfgs = create_chanmon_cfgs(3);
854         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
855         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
856         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
857         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
858         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
859         let logger = test_utils::TestLogger::new();
860
861         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
862
863         nodes[0].node.close_channel(&chan_1.2).unwrap();
864         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
865         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
866         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
867         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
868
869         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
870         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
871
872         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
873
874         let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
875         let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
876         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();
877         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();
878         unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
879         unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
880
881         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
882         check_added_monitors!(nodes[2], 1);
883         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
884         assert!(updates.update_add_htlcs.is_empty());
885         assert!(updates.update_fail_htlcs.is_empty());
886         assert!(updates.update_fail_malformed_htlcs.is_empty());
887         assert!(updates.update_fee.is_none());
888         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
889         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
890         check_added_monitors!(nodes[1], 1);
891         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
892         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
893
894         assert!(updates_2.update_add_htlcs.is_empty());
895         assert!(updates_2.update_fail_htlcs.is_empty());
896         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
897         assert!(updates_2.update_fee.is_none());
898         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
899         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
900         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
901
902         let events = nodes[0].node.get_and_clear_pending_events();
903         assert_eq!(events.len(), 1);
904         match events[0] {
905                 Event::PaymentSent { ref payment_preimage } => {
906                         assert_eq!(our_payment_preimage, *payment_preimage);
907                 },
908                 _ => panic!("Unexpected event"),
909         }
910
911         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
912         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
913         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
914         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
915         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
916         assert!(node_0_none.is_none());
917
918         assert!(nodes[0].node.list_channels().is_empty());
919
920         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
921         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
922         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
923         assert!(nodes[1].node.list_channels().is_empty());
924         assert!(nodes[2].node.list_channels().is_empty());
925 }
926
927 #[test]
928 fn htlc_fail_async_shutdown() {
929         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
930         let chanmon_cfgs = create_chanmon_cfgs(3);
931         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
932         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
933         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
934         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
935         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
936         let logger = test_utils::TestLogger::new();
937
938         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
939         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
940         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();
941         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
942         check_added_monitors!(nodes[0], 1);
943         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
944         assert_eq!(updates.update_add_htlcs.len(), 1);
945         assert!(updates.update_fulfill_htlcs.is_empty());
946         assert!(updates.update_fail_htlcs.is_empty());
947         assert!(updates.update_fail_malformed_htlcs.is_empty());
948         assert!(updates.update_fee.is_none());
949
950         nodes[1].node.close_channel(&chan_1.2).unwrap();
951         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
952         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
953         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
954
955         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
956         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
957         check_added_monitors!(nodes[1], 1);
958         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
959         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
960
961         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
962         assert!(updates_2.update_add_htlcs.is_empty());
963         assert!(updates_2.update_fulfill_htlcs.is_empty());
964         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
965         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
966         assert!(updates_2.update_fee.is_none());
967
968         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
969         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
970
971         expect_payment_failed!(nodes[0], our_payment_hash, false);
972
973         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
974         assert_eq!(msg_events.len(), 2);
975         let node_0_closing_signed = match msg_events[0] {
976                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
977                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
978                         (*msg).clone()
979                 },
980                 _ => panic!("Unexpected event"),
981         };
982         match msg_events[1] {
983                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
984                         assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
985                 },
986                 _ => panic!("Unexpected event"),
987         }
988
989         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
990         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
991         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
992         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
993         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
994         assert!(node_0_none.is_none());
995
996         assert!(nodes[0].node.list_channels().is_empty());
997
998         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
999         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1000         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1001         assert!(nodes[1].node.list_channels().is_empty());
1002         assert!(nodes[2].node.list_channels().is_empty());
1003 }
1004
1005 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1006         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1007         // messages delivered prior to disconnect
1008         let chanmon_cfgs = create_chanmon_cfgs(3);
1009         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1010         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1011         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1012         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1013         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1014
1015         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1016
1017         nodes[1].node.close_channel(&chan_1.2).unwrap();
1018         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1019         if recv_count > 0 {
1020                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
1021                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1022                 if recv_count > 1 {
1023                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
1024                 }
1025         }
1026
1027         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1028         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1029
1030         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1031         let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1032         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1033         let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1034
1035         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1036         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1037         assert!(node_1_shutdown == node_1_2nd_shutdown);
1038
1039         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1040         let node_0_2nd_shutdown = if recv_count > 0 {
1041                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1042                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1043                 node_0_2nd_shutdown
1044         } else {
1045                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1046                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1047                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1048         };
1049         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_2nd_shutdown);
1050
1051         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1052         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1053
1054         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1055         check_added_monitors!(nodes[2], 1);
1056         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1057         assert!(updates.update_add_htlcs.is_empty());
1058         assert!(updates.update_fail_htlcs.is_empty());
1059         assert!(updates.update_fail_malformed_htlcs.is_empty());
1060         assert!(updates.update_fee.is_none());
1061         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1062         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1063         check_added_monitors!(nodes[1], 1);
1064         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1065         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1066
1067         assert!(updates_2.update_add_htlcs.is_empty());
1068         assert!(updates_2.update_fail_htlcs.is_empty());
1069         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1070         assert!(updates_2.update_fee.is_none());
1071         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1072         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1073         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1074
1075         let events = nodes[0].node.get_and_clear_pending_events();
1076         assert_eq!(events.len(), 1);
1077         match events[0] {
1078                 Event::PaymentSent { ref payment_preimage } => {
1079                         assert_eq!(our_payment_preimage, *payment_preimage);
1080                 },
1081                 _ => panic!("Unexpected event"),
1082         }
1083
1084         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1085         if recv_count > 0 {
1086                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1087                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1088                 assert!(node_1_closing_signed.is_some());
1089         }
1090
1091         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1092         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1093
1094         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1095         let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1096         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1097         if recv_count == 0 {
1098                 // If all closing_signeds weren't delivered we can just resume where we left off...
1099                 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1100
1101                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1102                 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1103                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1104
1105                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1106                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1107                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1108
1109                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_3rd_shutdown);
1110                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1111
1112                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_3rd_shutdown);
1113                 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1114                 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1115
1116                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1117                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1118                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1119                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1120                 assert!(node_0_none.is_none());
1121         } else {
1122                 // If one node, however, received + responded with an identical closing_signed we end
1123                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1124                 // There isn't really anything better we can do simply, but in the future we might
1125                 // explore storing a set of recently-closed channels that got disconnected during
1126                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1127                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1128                 // transaction.
1129                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1130
1131                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1132                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1133                 assert_eq!(msg_events.len(), 1);
1134                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1135                         match action {
1136                                 &ErrorAction::SendErrorMessage { ref msg } => {
1137                                         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1138                                         assert_eq!(msg.channel_id, chan_1.2);
1139                                 },
1140                                 _ => panic!("Unexpected event!"),
1141                         }
1142                 } else { panic!("Needed SendErrorMessage close"); }
1143
1144                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1145                 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1146                 // closing_signed so we do it ourselves
1147                 check_closed_broadcast!(nodes[0], false);
1148                 check_added_monitors!(nodes[0], 1);
1149         }
1150
1151         assert!(nodes[0].node.list_channels().is_empty());
1152
1153         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1154         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1155         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1156         assert!(nodes[1].node.list_channels().is_empty());
1157         assert!(nodes[2].node.list_channels().is_empty());
1158 }
1159
1160 #[test]
1161 fn test_shutdown_rebroadcast() {
1162         do_test_shutdown_rebroadcast(0);
1163         do_test_shutdown_rebroadcast(1);
1164         do_test_shutdown_rebroadcast(2);
1165 }
1166
1167 #[test]
1168 fn fake_network_test() {
1169         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1170         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1171         let chanmon_cfgs = create_chanmon_cfgs(4);
1172         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1173         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1174         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1175
1176         // Create some initial channels
1177         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1178         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1179         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1180
1181         // Rebalance the network a bit by relaying one payment through all the channels...
1182         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1183         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1184         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1185         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1186
1187         // Send some more payments
1188         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1189         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1190         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1191
1192         // Test failure packets
1193         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1194         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1195
1196         // Add a new channel that skips 3
1197         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1198
1199         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1200         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1201         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1202         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1203         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1204         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1205         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1206
1207         // Do some rebalance loop payments, simultaneously
1208         let mut hops = Vec::with_capacity(3);
1209         hops.push(RouteHop {
1210                 pubkey: nodes[2].node.get_our_node_id(),
1211                 node_features: NodeFeatures::empty(),
1212                 short_channel_id: chan_2.0.contents.short_channel_id,
1213                 channel_features: ChannelFeatures::empty(),
1214                 fee_msat: 0,
1215                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1216         });
1217         hops.push(RouteHop {
1218                 pubkey: nodes[3].node.get_our_node_id(),
1219                 node_features: NodeFeatures::empty(),
1220                 short_channel_id: chan_3.0.contents.short_channel_id,
1221                 channel_features: ChannelFeatures::empty(),
1222                 fee_msat: 0,
1223                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1224         });
1225         hops.push(RouteHop {
1226                 pubkey: nodes[1].node.get_our_node_id(),
1227                 node_features: NodeFeatures::empty(),
1228                 short_channel_id: chan_4.0.contents.short_channel_id,
1229                 channel_features: ChannelFeatures::empty(),
1230                 fee_msat: 1000000,
1231                 cltv_expiry_delta: TEST_FINAL_CLTV,
1232         });
1233         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;
1234         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;
1235         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1236
1237         let mut hops = Vec::with_capacity(3);
1238         hops.push(RouteHop {
1239                 pubkey: nodes[3].node.get_our_node_id(),
1240                 node_features: NodeFeatures::empty(),
1241                 short_channel_id: chan_4.0.contents.short_channel_id,
1242                 channel_features: ChannelFeatures::empty(),
1243                 fee_msat: 0,
1244                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1245         });
1246         hops.push(RouteHop {
1247                 pubkey: nodes[2].node.get_our_node_id(),
1248                 node_features: NodeFeatures::empty(),
1249                 short_channel_id: chan_3.0.contents.short_channel_id,
1250                 channel_features: ChannelFeatures::empty(),
1251                 fee_msat: 0,
1252                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1253         });
1254         hops.push(RouteHop {
1255                 pubkey: nodes[1].node.get_our_node_id(),
1256                 node_features: NodeFeatures::empty(),
1257                 short_channel_id: chan_2.0.contents.short_channel_id,
1258                 channel_features: ChannelFeatures::empty(),
1259                 fee_msat: 1000000,
1260                 cltv_expiry_delta: TEST_FINAL_CLTV,
1261         });
1262         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;
1263         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;
1264         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1265
1266         // Claim the rebalances...
1267         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1268         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1269
1270         // Add a duplicate new channel from 2 to 4
1271         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1272
1273         // Send some payments across both channels
1274         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1275         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1276         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1277
1278
1279         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1280         let events = nodes[0].node.get_and_clear_pending_msg_events();
1281         assert_eq!(events.len(), 0);
1282         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);
1283
1284         //TODO: Test that routes work again here as we've been notified that the channel is full
1285
1286         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1287         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1288         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1289
1290         // Close down the channels...
1291         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1292         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1293         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1294         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1295         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1296 }
1297
1298 #[test]
1299 fn holding_cell_htlc_counting() {
1300         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1301         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1302         // commitment dance rounds.
1303         let chanmon_cfgs = create_chanmon_cfgs(3);
1304         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1305         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1306         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1307         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1308         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1309         let logger = test_utils::TestLogger::new();
1310
1311         let mut payments = Vec::new();
1312         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1313                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1314                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1315                 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();
1316                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1317                 payments.push((payment_preimage, payment_hash));
1318         }
1319         check_added_monitors!(nodes[1], 1);
1320
1321         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1322         assert_eq!(events.len(), 1);
1323         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1324         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1325
1326         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1327         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1328         // another HTLC.
1329         let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1330         {
1331                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1332                 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();
1333                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1334                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1335                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1336                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1337         }
1338
1339         // This should also be true if we try to forward a payment.
1340         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1341         {
1342                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1343                 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();
1344                 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1345                 check_added_monitors!(nodes[0], 1);
1346         }
1347
1348         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1349         assert_eq!(events.len(), 1);
1350         let payment_event = SendEvent::from_event(events.pop().unwrap());
1351         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1352
1353         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1354         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1355         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1356         // fails), the second will process the resulting failure and fail the HTLC backward.
1357         expect_pending_htlcs_forwardable!(nodes[1]);
1358         expect_pending_htlcs_forwardable!(nodes[1]);
1359         check_added_monitors!(nodes[1], 1);
1360
1361         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1362         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1363         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1364
1365         let events = nodes[0].node.get_and_clear_pending_msg_events();
1366         assert_eq!(events.len(), 1);
1367         match events[0] {
1368                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1369                         assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1370                 },
1371                 _ => panic!("Unexpected event"),
1372         }
1373
1374         expect_payment_failed!(nodes[0], payment_hash_2, false);
1375
1376         // Now forward all the pending HTLCs and claim them back
1377         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1378         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1379         check_added_monitors!(nodes[2], 1);
1380
1381         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1382         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1383         check_added_monitors!(nodes[1], 1);
1384         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1385
1386         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1387         check_added_monitors!(nodes[1], 1);
1388         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1389
1390         for ref update in as_updates.update_add_htlcs.iter() {
1391                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1392         }
1393         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1394         check_added_monitors!(nodes[2], 1);
1395         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1396         check_added_monitors!(nodes[2], 1);
1397         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1398
1399         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1400         check_added_monitors!(nodes[1], 1);
1401         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1402         check_added_monitors!(nodes[1], 1);
1403         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1404
1405         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1406         check_added_monitors!(nodes[2], 1);
1407
1408         expect_pending_htlcs_forwardable!(nodes[2]);
1409
1410         let events = nodes[2].node.get_and_clear_pending_events();
1411         assert_eq!(events.len(), payments.len());
1412         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1413                 match event {
1414                         &Event::PaymentReceived { ref payment_hash, .. } => {
1415                                 assert_eq!(*payment_hash, *hash);
1416                         },
1417                         _ => panic!("Unexpected event"),
1418                 };
1419         }
1420
1421         for (preimage, _) in payments.drain(..) {
1422                 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1423         }
1424
1425         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1426 }
1427
1428 #[test]
1429 fn duplicate_htlc_test() {
1430         // Test that we accept duplicate payment_hash HTLCs across the network and that
1431         // claiming/failing them are all separate and don't affect each other
1432         let chanmon_cfgs = create_chanmon_cfgs(6);
1433         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1434         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1435         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1436
1437         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1438         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1439         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1440         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1441         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1442         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1443
1444         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1445
1446         *nodes[0].network_payment_count.borrow_mut() -= 1;
1447         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1448
1449         *nodes[0].network_payment_count.borrow_mut() -= 1;
1450         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1451
1452         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1453         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1454         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1455 }
1456
1457 #[test]
1458 fn test_duplicate_htlc_different_direction_onchain() {
1459         // Test that ChannelMonitor doesn't generate 2 preimage txn
1460         // when we have 2 HTLCs with same preimage that go across a node
1461         // in opposite directions.
1462         let chanmon_cfgs = create_chanmon_cfgs(2);
1463         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1464         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1465         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1466
1467         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1468         let logger = test_utils::TestLogger::new();
1469
1470         // balancing
1471         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1472
1473         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1474
1475         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1476         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();
1477         send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1478
1479         // Provide preimage to node 0 by claiming payment
1480         nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1481         check_added_monitors!(nodes[0], 1);
1482
1483         // Broadcast node 1 commitment txn
1484         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1485
1486         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1487         let mut has_both_htlcs = 0; // check htlcs match ones committed
1488         for outp in remote_txn[0].output.iter() {
1489                 if outp.value == 800_000 / 1000 {
1490                         has_both_htlcs += 1;
1491                 } else if outp.value == 900_000 / 1000 {
1492                         has_both_htlcs += 1;
1493                 }
1494         }
1495         assert_eq!(has_both_htlcs, 2);
1496
1497         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1498         connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1499         check_added_monitors!(nodes[0], 1);
1500
1501         // Check we only broadcast 1 timeout tx
1502         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1503         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()) };
1504         assert_eq!(claim_txn.len(), 5);
1505         check_spends!(claim_txn[2], chan_1.3);
1506         check_spends!(claim_txn[3], claim_txn[2]);
1507         assert_eq!(htlc_pair.0.input.len(), 1);
1508         assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1509         check_spends!(htlc_pair.0, remote_txn[0]);
1510         assert_eq!(htlc_pair.1.input.len(), 1);
1511         assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1512         check_spends!(htlc_pair.1, remote_txn[0]);
1513
1514         let events = nodes[0].node.get_and_clear_pending_msg_events();
1515         assert_eq!(events.len(), 2);
1516         for e in events {
1517                 match e {
1518                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1519                         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, .. } } => {
1520                                 assert!(update_add_htlcs.is_empty());
1521                                 assert!(update_fail_htlcs.is_empty());
1522                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1523                                 assert!(update_fail_malformed_htlcs.is_empty());
1524                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1525                         },
1526                         _ => panic!("Unexpected event"),
1527                 }
1528         }
1529 }
1530
1531 #[test]
1532 fn test_basic_channel_reserve() {
1533         let chanmon_cfgs = create_chanmon_cfgs(2);
1534         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1535         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1536         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1537         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1538         let logger = test_utils::TestLogger::new();
1539
1540         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1541         let channel_reserve = chan_stat.channel_reserve_msat;
1542
1543         // The 2* and +1 are for the fee spike reserve.
1544         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1545         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1546         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1547         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1548         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();
1549         let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1550         match err {
1551                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1552                         match &fails[0] {
1553                                 &APIError::ChannelUnavailable{ref err} =>
1554                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1555                                 _ => panic!("Unexpected error variant"),
1556                         }
1557                 },
1558                 _ => panic!("Unexpected error variant"),
1559         }
1560         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1561         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);
1562
1563         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1564 }
1565
1566 #[test]
1567 fn test_fee_spike_violation_fails_htlc() {
1568         let chanmon_cfgs = create_chanmon_cfgs(2);
1569         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1570         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1571         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1572         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1573         let logger = test_utils::TestLogger::new();
1574
1575         macro_rules! get_route_and_payment_hash {
1576                 ($recv_value: expr) => {{
1577                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1578                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1579                         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();
1580                         (route, payment_hash, payment_preimage)
1581                 }}
1582         }
1583
1584         let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1585         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1586         let secp_ctx = Secp256k1::new();
1587         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1588
1589         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1590
1591         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1592         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1593         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1594         let msg = msgs::UpdateAddHTLC {
1595                 channel_id: chan.2,
1596                 htlc_id: 0,
1597                 amount_msat: htlc_msat,
1598                 payment_hash: payment_hash,
1599                 cltv_expiry: htlc_cltv,
1600                 onion_routing_packet: onion_packet,
1601         };
1602
1603         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1604
1605         // Now manually create the commitment_signed message corresponding to the update_add
1606         // nodes[0] just sent. In the code for construction of this message, "local" refers
1607         // to the sender of the message, and "remote" refers to the receiver.
1608
1609         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1610
1611         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1612
1613         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1614         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1615         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point) = {
1616                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1617                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1618                 let chan_signer = local_chan.get_signer();
1619                 let pubkeys = chan_signer.pubkeys();
1620                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1621                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1622                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
1623         };
1624         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point) = {
1625                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1626                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1627                 let chan_signer = remote_chan.get_signer();
1628                 let pubkeys = chan_signer.pubkeys();
1629                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1630                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
1631         };
1632
1633         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1634         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1635                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1636
1637         // Build the remote commitment transaction so we can sign it, and then later use the
1638         // signature for the commitment_signed message.
1639         let local_chan_balance = 1313;
1640
1641         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1642                 offered: false,
1643                 amount_msat: 3460001,
1644                 cltv_expiry: htlc_cltv,
1645                 payment_hash,
1646                 transaction_output_index: Some(1),
1647         };
1648
1649         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1650
1651         let res = {
1652                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1653                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1654                 let local_chan_signer = local_chan.get_signer();
1655                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1656                         commitment_number,
1657                         95000,
1658                         local_chan_balance,
1659                         commit_tx_keys.clone(),
1660                         feerate_per_kw,
1661                         &mut vec![(accepted_htlc_info, ())],
1662                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1663                 );
1664                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1665         };
1666
1667         let commit_signed_msg = msgs::CommitmentSigned {
1668                 channel_id: chan.2,
1669                 signature: res.0,
1670                 htlc_signatures: res.1
1671         };
1672
1673         // Send the commitment_signed message to the nodes[1].
1674         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1675         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1676
1677         // Send the RAA to nodes[1].
1678         let raa_msg = msgs::RevokeAndACK {
1679                 channel_id: chan.2,
1680                 per_commitment_secret: local_secret,
1681                 next_per_commitment_point: next_local_point
1682         };
1683         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1684
1685         let events = nodes[1].node.get_and_clear_pending_msg_events();
1686         assert_eq!(events.len(), 1);
1687         // Make sure the HTLC failed in the way we expect.
1688         match events[0] {
1689                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1690                         assert_eq!(update_fail_htlcs.len(), 1);
1691                         update_fail_htlcs[0].clone()
1692                 },
1693                 _ => panic!("Unexpected event"),
1694         };
1695         nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1696
1697         check_added_monitors!(nodes[1], 2);
1698 }
1699
1700 #[test]
1701 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1702         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1703         // Set the fee rate for the channel very high, to the point where the fundee
1704         // sending any above-dust amount would result in a channel reserve violation.
1705         // In this test we check that we would be prevented from sending an HTLC in
1706         // this situation.
1707         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1708         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1709         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1710         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1711         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1712         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1713         let logger = test_utils::TestLogger::new();
1714
1715         macro_rules! get_route_and_payment_hash {
1716                 ($recv_value: expr) => {{
1717                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1718                         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1719                         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();
1720                         (route, payment_hash, payment_preimage)
1721                 }}
1722         }
1723
1724         let (route, our_payment_hash, _) = get_route_and_payment_hash!(4843000);
1725         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1726                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1727         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1728         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);
1729 }
1730
1731 #[test]
1732 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1733         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1734         // Set the fee rate for the channel very high, to the point where the funder
1735         // receiving 1 update_add_htlc would result in them closing the channel due
1736         // to channel reserve violation. This close could also happen if the fee went
1737         // up a more realistic amount, but many HTLCs were outstanding at the time of
1738         // the update_add_htlc.
1739         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1740         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1741         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1742         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1743         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1744         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1745         let logger = test_utils::TestLogger::new();
1746
1747         macro_rules! get_route_and_payment_hash {
1748                 ($recv_value: expr) => {{
1749                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1750                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1751                         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();
1752                         (route, payment_hash, payment_preimage)
1753                 }}
1754         }
1755
1756         let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1757         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1758         let secp_ctx = Secp256k1::new();
1759         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1760         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1761         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1762         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1763         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1764         let msg = msgs::UpdateAddHTLC {
1765                 channel_id: chan.2,
1766                 htlc_id: 1,
1767                 amount_msat: htlc_msat + 1,
1768                 payment_hash: payment_hash,
1769                 cltv_expiry: htlc_cltv,
1770                 onion_routing_packet: onion_packet,
1771         };
1772
1773         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1774         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1775         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);
1776         assert_eq!(nodes[0].node.list_channels().len(), 0);
1777         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1778         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1779         check_added_monitors!(nodes[0], 1);
1780 }
1781
1782 #[test]
1783 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1784         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1785         // calculating our commitment transaction fee (this was previously broken).
1786         let chanmon_cfgs = create_chanmon_cfgs(2);
1787         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1788         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1789         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1790
1791         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1792         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1793         // transaction fee with 0 HTLCs (183 sats)).
1794         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98817000, InitFeatures::known(), InitFeatures::known());
1795
1796         let dust_amt = 546000; // Dust amount
1797         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1798         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1799         // commitment transaction fee.
1800         let (_, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1801 }
1802
1803 #[test]
1804 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1805         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1806         // calculating our counterparty's commitment transaction fee (this was previously broken).
1807         let chanmon_cfgs = create_chanmon_cfgs(2);
1808         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1809         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1810         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1811         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1812
1813         let payment_amt = 46000; // Dust amount
1814         // In the previous code, these first four payments would succeed.
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         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1819
1820         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
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         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1826
1827         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1828         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1829         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1830         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1831 }
1832
1833 #[test]
1834 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1835         let chanmon_cfgs = create_chanmon_cfgs(3);
1836         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1837         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1838         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1839         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1840         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1841         let logger = test_utils::TestLogger::new();
1842
1843         macro_rules! get_route_and_payment_hash {
1844                 ($recv_value: expr) => {{
1845                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1846                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1847                         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();
1848                         (route, payment_hash, payment_preimage)
1849                 }}
1850         }
1851
1852         let feemsat = 239;
1853         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1854         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1855         let feerate = get_feerate!(nodes[0], chan.2);
1856
1857         // Add a 2* and +1 for the fee spike reserve.
1858         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1859         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;
1860         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1861
1862         // Add a pending HTLC.
1863         let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1864         let payment_event_1 = {
1865                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1866                 check_added_monitors!(nodes[0], 1);
1867
1868                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1869                 assert_eq!(events.len(), 1);
1870                 SendEvent::from_event(events.remove(0))
1871         };
1872         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1873
1874         // Attempt to trigger a channel reserve violation --> payment failure.
1875         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1876         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;
1877         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1878         let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1879
1880         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1881         let secp_ctx = Secp256k1::new();
1882         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1883         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1884         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1885         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1886         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1887         let msg = msgs::UpdateAddHTLC {
1888                 channel_id: chan.2,
1889                 htlc_id: 1,
1890                 amount_msat: htlc_msat + 1,
1891                 payment_hash: our_payment_hash_1,
1892                 cltv_expiry: htlc_cltv,
1893                 onion_routing_packet: onion_packet,
1894         };
1895
1896         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1897         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1898         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1899         assert_eq!(nodes[1].node.list_channels().len(), 1);
1900         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1901         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1902         check_added_monitors!(nodes[1], 1);
1903 }
1904
1905 #[test]
1906 fn test_inbound_outbound_capacity_is_not_zero() {
1907         let chanmon_cfgs = create_chanmon_cfgs(2);
1908         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1909         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1910         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1911         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1912         let channels0 = node_chanmgrs[0].list_channels();
1913         let channels1 = node_chanmgrs[1].list_channels();
1914         assert_eq!(channels0.len(), 1);
1915         assert_eq!(channels1.len(), 1);
1916
1917         assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1918         assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1919
1920         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1921         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1922 }
1923
1924 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1925         (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1926 }
1927
1928 #[test]
1929 fn test_channel_reserve_holding_cell_htlcs() {
1930         let chanmon_cfgs = create_chanmon_cfgs(3);
1931         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1932         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1933         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1934         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1935         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1936         let logger = test_utils::TestLogger::new();
1937
1938         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1939         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1940
1941         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1942         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1943
1944         macro_rules! get_route_and_payment_hash {
1945                 ($recv_value: expr) => {{
1946                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1947                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1948                         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();
1949                         (route, payment_hash, payment_preimage)
1950                 }}
1951         }
1952
1953         macro_rules! expect_forward {
1954                 ($node: expr) => {{
1955                         let mut events = $node.node.get_and_clear_pending_msg_events();
1956                         assert_eq!(events.len(), 1);
1957                         check_added_monitors!($node, 1);
1958                         let payment_event = SendEvent::from_event(events.remove(0));
1959                         payment_event
1960                 }}
1961         }
1962
1963         let feemsat = 239; // somehow we know?
1964         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1965         let feerate = get_feerate!(nodes[0], chan_1.2);
1966
1967         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1968
1969         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1970         {
1971                 let (mut route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0);
1972                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1973                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1974                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1975                         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)));
1976                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1977                 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);
1978         }
1979
1980         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1981         // nodes[0]'s wealth
1982         loop {
1983                 let amt_msat = recv_value_0 + total_fee_msat;
1984                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1985                 // Also, ensure that each payment has enough to be over the dust limit to
1986                 // ensure it'll be included in each commit tx fee calculation.
1987                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1988                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1989                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1990                         break;
1991                 }
1992                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1993
1994                 let (stat01_, stat11_, stat12_, stat22_) = (
1995                         get_channel_value_stat!(nodes[0], chan_1.2),
1996                         get_channel_value_stat!(nodes[1], chan_1.2),
1997                         get_channel_value_stat!(nodes[1], chan_2.2),
1998                         get_channel_value_stat!(nodes[2], chan_2.2),
1999                 );
2000
2001                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
2002                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
2003                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
2004                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
2005                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
2006         }
2007
2008         // adding pending output.
2009         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
2010         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2011         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2012         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2013         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2014         // cases where 1 msat over X amount will cause a payment failure, but anything less than
2015         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2016         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2017         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2018         // policy.
2019         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2020         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2021         let amt_msat_1 = recv_value_1 + total_fee_msat;
2022
2023         let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2024         let payment_event_1 = {
2025                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
2026                 check_added_monitors!(nodes[0], 1);
2027
2028                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2029                 assert_eq!(events.len(), 1);
2030                 SendEvent::from_event(events.remove(0))
2031         };
2032         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2033
2034         // channel reserve test with htlc pending output > 0
2035         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2036         {
2037                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2038                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2039                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2040                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2041         }
2042
2043         // split the rest to test holding cell
2044         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2045         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2046         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2047         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2048         {
2049                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2050                 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);
2051         }
2052
2053         // now see if they go through on both sides
2054         let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2055         // but this will stuck in the holding cell
2056         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2057         check_added_monitors!(nodes[0], 0);
2058         let events = nodes[0].node.get_and_clear_pending_events();
2059         assert_eq!(events.len(), 0);
2060
2061         // test with outbound holding cell amount > 0
2062         {
2063                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2064                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2065                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2066                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2067                 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);
2068         }
2069
2070         let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2071         // this will also stuck in the holding cell
2072         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2073         check_added_monitors!(nodes[0], 0);
2074         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2075         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2076
2077         // flush the pending htlc
2078         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2079         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2080         check_added_monitors!(nodes[1], 1);
2081
2082         // the pending htlc should be promoted to committed
2083         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2084         check_added_monitors!(nodes[0], 1);
2085         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2086
2087         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2088         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2089         // No commitment_signed so get_event_msg's assert(len == 1) passes
2090         check_added_monitors!(nodes[0], 1);
2091
2092         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2093         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2094         check_added_monitors!(nodes[1], 1);
2095
2096         expect_pending_htlcs_forwardable!(nodes[1]);
2097
2098         let ref payment_event_11 = expect_forward!(nodes[1]);
2099         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2100         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2101
2102         expect_pending_htlcs_forwardable!(nodes[2]);
2103         expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2104
2105         // flush the htlcs in the holding cell
2106         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2107         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2108         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2109         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2110         expect_pending_htlcs_forwardable!(nodes[1]);
2111
2112         let ref payment_event_3 = expect_forward!(nodes[1]);
2113         assert_eq!(payment_event_3.msgs.len(), 2);
2114         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2115         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2116
2117         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2118         expect_pending_htlcs_forwardable!(nodes[2]);
2119
2120         let events = nodes[2].node.get_and_clear_pending_events();
2121         assert_eq!(events.len(), 2);
2122         match events[0] {
2123                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2124                         assert_eq!(our_payment_hash_21, *payment_hash);
2125                         assert_eq!(*payment_secret, None);
2126                         assert_eq!(recv_value_21, amt);
2127                 },
2128                 _ => panic!("Unexpected event"),
2129         }
2130         match events[1] {
2131                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2132                         assert_eq!(our_payment_hash_22, *payment_hash);
2133                         assert_eq!(None, *payment_secret);
2134                         assert_eq!(recv_value_22, amt);
2135                 },
2136                 _ => panic!("Unexpected event"),
2137         }
2138
2139         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2140         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2141         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2142
2143         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2144         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2145         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2146
2147         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2148         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);
2149         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2150         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2151         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2152
2153         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2154         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2155 }
2156
2157 #[test]
2158 fn channel_reserve_in_flight_removes() {
2159         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2160         // can send to its counterparty, but due to update ordering, the other side may not yet have
2161         // considered those HTLCs fully removed.
2162         // This tests that we don't count HTLCs which will not be included in the next remote
2163         // commitment transaction towards the reserve value (as it implies no commitment transaction
2164         // will be generated which violates the remote reserve value).
2165         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2166         // To test this we:
2167         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2168         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2169         //    you only consider the value of the first HTLC, it may not),
2170         //  * start routing a third HTLC from A to B,
2171         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2172         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2173         //  * deliver the first fulfill from B
2174         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2175         //    claim,
2176         //  * deliver A's response CS and RAA.
2177         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2178         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2179         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2180         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2181         let chanmon_cfgs = create_chanmon_cfgs(2);
2182         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2183         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2184         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2185         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2186         let logger = test_utils::TestLogger::new();
2187
2188         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2189         // Route the first two HTLCs.
2190         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2191         let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2192
2193         // Start routing the third HTLC (this is just used to get everyone in the right state).
2194         let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2195         let send_1 = {
2196                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2197                 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();
2198                 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2199                 check_added_monitors!(nodes[0], 1);
2200                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2201                 assert_eq!(events.len(), 1);
2202                 SendEvent::from_event(events.remove(0))
2203         };
2204
2205         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2206         // initial fulfill/CS.
2207         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2208         check_added_monitors!(nodes[1], 1);
2209         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2210
2211         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2212         // remove the second HTLC when we send the HTLC back from B to A.
2213         assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2214         check_added_monitors!(nodes[1], 1);
2215         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2216
2217         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2218         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2219         check_added_monitors!(nodes[0], 1);
2220         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2221         expect_payment_sent!(nodes[0], payment_preimage_1);
2222
2223         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2224         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2225         check_added_monitors!(nodes[1], 1);
2226         // B is already AwaitingRAA, so cant generate a CS here
2227         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2228
2229         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2230         check_added_monitors!(nodes[1], 1);
2231         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2232
2233         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2234         check_added_monitors!(nodes[0], 1);
2235         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2236
2237         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2238         check_added_monitors!(nodes[1], 1);
2239         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2240
2241         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2242         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2243         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2244         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2245         // on-chain as necessary).
2246         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2247         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2248         check_added_monitors!(nodes[0], 1);
2249         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2250         expect_payment_sent!(nodes[0], payment_preimage_2);
2251
2252         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2253         check_added_monitors!(nodes[1], 1);
2254         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2255
2256         expect_pending_htlcs_forwardable!(nodes[1]);
2257         expect_payment_received!(nodes[1], payment_hash_3, 100000);
2258
2259         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2260         // resolve the second HTLC from A's point of view.
2261         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2262         check_added_monitors!(nodes[0], 1);
2263         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2264
2265         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2266         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2267         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2268         let send_2 = {
2269                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2270                 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();
2271                 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2272                 check_added_monitors!(nodes[1], 1);
2273                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2274                 assert_eq!(events.len(), 1);
2275                 SendEvent::from_event(events.remove(0))
2276         };
2277
2278         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2279         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2280         check_added_monitors!(nodes[0], 1);
2281         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2282
2283         // Now just resolve all the outstanding messages/HTLCs for completeness...
2284
2285         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2286         check_added_monitors!(nodes[1], 1);
2287         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2288
2289         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2290         check_added_monitors!(nodes[1], 1);
2291
2292         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2293         check_added_monitors!(nodes[0], 1);
2294         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2295
2296         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2297         check_added_monitors!(nodes[1], 1);
2298         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2299
2300         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2301         check_added_monitors!(nodes[0], 1);
2302
2303         expect_pending_htlcs_forwardable!(nodes[0]);
2304         expect_payment_received!(nodes[0], payment_hash_4, 10000);
2305
2306         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2307         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2308 }
2309
2310 #[test]
2311 fn channel_monitor_network_test() {
2312         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2313         // tests that ChannelMonitor is able to recover from various states.
2314         let chanmon_cfgs = create_chanmon_cfgs(5);
2315         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2316         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2317         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2318
2319         // Create some initial channels
2320         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2321         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2322         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2323         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2324
2325         // Rebalance the network a bit by relaying one payment through all the channels...
2326         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2327         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2328         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2329         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2330
2331         // Simple case with no pending HTLCs:
2332         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2333         check_added_monitors!(nodes[1], 1);
2334         {
2335                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2336                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2337                 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2338                 check_added_monitors!(nodes[0], 1);
2339                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2340         }
2341         get_announce_close_broadcast_events(&nodes, 0, 1);
2342         assert_eq!(nodes[0].node.list_channels().len(), 0);
2343         assert_eq!(nodes[1].node.list_channels().len(), 1);
2344
2345         // One pending HTLC is discarded by the force-close:
2346         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2347
2348         // Simple case of one pending HTLC to HTLC-Timeout
2349         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2350         check_added_monitors!(nodes[1], 1);
2351         {
2352                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2353                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2354                 connect_block(&nodes[2], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2355                 check_added_monitors!(nodes[2], 1);
2356                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2357         }
2358         get_announce_close_broadcast_events(&nodes, 1, 2);
2359         assert_eq!(nodes[1].node.list_channels().len(), 0);
2360         assert_eq!(nodes[2].node.list_channels().len(), 1);
2361
2362         macro_rules! claim_funds {
2363                 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2364                         {
2365                                 assert!($node.node.claim_funds($preimage, &None, $amount));
2366                                 check_added_monitors!($node, 1);
2367
2368                                 let events = $node.node.get_and_clear_pending_msg_events();
2369                                 assert_eq!(events.len(), 1);
2370                                 match events[0] {
2371                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2372                                                 assert!(update_add_htlcs.is_empty());
2373                                                 assert!(update_fail_htlcs.is_empty());
2374                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2375                                         },
2376                                         _ => panic!("Unexpected event"),
2377                                 };
2378                         }
2379                 }
2380         }
2381
2382         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2383         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2384         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2385         check_added_monitors!(nodes[2], 1);
2386         let node2_commitment_txid;
2387         {
2388                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2389                 node2_commitment_txid = node_txn[0].txid();
2390
2391                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2392                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2393
2394                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2395                 connect_block(&nodes[3], &Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2396                 check_added_monitors!(nodes[3], 1);
2397
2398                 check_preimage_claim(&nodes[3], &node_txn);
2399         }
2400         get_announce_close_broadcast_events(&nodes, 2, 3);
2401         assert_eq!(nodes[2].node.list_channels().len(), 0);
2402         assert_eq!(nodes[3].node.list_channels().len(), 1);
2403
2404         { // Cheat and reset nodes[4]'s height to 1
2405                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2406                 connect_block(&nodes[4], &Block { header, txdata: vec![] }, 1);
2407         }
2408
2409         assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2410         assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2411         // One pending HTLC to time out:
2412         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2413         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2414         // buffer space).
2415
2416         let (close_chan_update_1, close_chan_update_2) = {
2417                 let mut block = Block {
2418                         header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2419                         txdata: vec![],
2420                 };
2421                 connect_block(&nodes[3], &block, 2);
2422                 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2423                         block = Block {
2424                                 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2425                                 txdata: vec![],
2426                         };
2427                         connect_block(&nodes[3], &block, i);
2428                 }
2429                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2430                 assert_eq!(events.len(), 1);
2431                 let close_chan_update_1 = match events[0] {
2432                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2433                                 msg.clone()
2434                         },
2435                         _ => panic!("Unexpected event"),
2436                 };
2437                 check_added_monitors!(nodes[3], 1);
2438
2439                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2440                 {
2441                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2442                         node_txn.retain(|tx| {
2443                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2444                                         false
2445                                 } else { true }
2446                         });
2447                 }
2448
2449                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2450
2451                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2452                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2453
2454                 block = Block {
2455                         header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2456                         txdata: vec![],
2457                 };
2458
2459                 connect_block(&nodes[4], &block, 2);
2460                 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2461                         block = Block {
2462                                 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2463                                 txdata: vec![],
2464                         };
2465                         connect_block(&nodes[4], &block, i);
2466                 }
2467                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2468                 assert_eq!(events.len(), 1);
2469                 let close_chan_update_2 = match events[0] {
2470                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2471                                 msg.clone()
2472                         },
2473                         _ => panic!("Unexpected event"),
2474                 };
2475                 check_added_monitors!(nodes[4], 1);
2476                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2477
2478                 block = Block {
2479                         header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2480                         txdata: vec![node_txn[0].clone()],
2481                 };
2482                 connect_block(&nodes[4], &block, TEST_FINAL_CLTV - 5);
2483
2484                 check_preimage_claim(&nodes[4], &node_txn);
2485                 (close_chan_update_1, close_chan_update_2)
2486         };
2487         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2488         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2489         assert_eq!(nodes[3].node.list_channels().len(), 0);
2490         assert_eq!(nodes[4].node.list_channels().len(), 0);
2491 }
2492
2493 #[test]
2494 fn test_justice_tx() {
2495         // Test justice txn built on revoked HTLC-Success tx, against both sides
2496         let mut alice_config = UserConfig::default();
2497         alice_config.channel_options.announced_channel = true;
2498         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2499         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2500         let mut bob_config = UserConfig::default();
2501         bob_config.channel_options.announced_channel = true;
2502         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2503         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2504         let user_cfgs = [Some(alice_config), Some(bob_config)];
2505         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2506         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2507         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2508         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2509         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2510         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2511         // Create some new channels:
2512         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2513
2514         // A pending HTLC which will be revoked:
2515         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2516         // Get the will-be-revoked local txn from nodes[0]
2517         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2518         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2519         assert_eq!(revoked_local_txn[0].input.len(), 1);
2520         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2521         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2522         assert_eq!(revoked_local_txn[1].input.len(), 1);
2523         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2524         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2525         // Revoke the old state
2526         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2527
2528         {
2529                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2530                 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2531                 {
2532                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2533                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2534                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2535
2536                         check_spends!(node_txn[0], revoked_local_txn[0]);
2537                         node_txn.swap_remove(0);
2538                         node_txn.truncate(1);
2539                 }
2540                 check_added_monitors!(nodes[1], 1);
2541                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2542
2543                 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2544                 // Verify broadcast of revoked HTLC-timeout
2545                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2546                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2547                 check_added_monitors!(nodes[0], 1);
2548                 // Broadcast revoked HTLC-timeout on node 1
2549                 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2550                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2551         }
2552         get_announce_close_broadcast_events(&nodes, 0, 1);
2553
2554         assert_eq!(nodes[0].node.list_channels().len(), 0);
2555         assert_eq!(nodes[1].node.list_channels().len(), 0);
2556
2557         // We test justice_tx build by A on B's revoked HTLC-Success tx
2558         // Create some new channels:
2559         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2560         {
2561                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2562                 node_txn.clear();
2563         }
2564
2565         // A pending HTLC which will be revoked:
2566         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2567         // Get the will-be-revoked local txn from B
2568         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2569         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2570         assert_eq!(revoked_local_txn[0].input.len(), 1);
2571         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2572         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2573         // Revoke the old state
2574         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2575         {
2576                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2577                 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2578                 {
2579                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2580                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2581                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2582
2583                         check_spends!(node_txn[0], revoked_local_txn[0]);
2584                         node_txn.swap_remove(0);
2585                 }
2586                 check_added_monitors!(nodes[0], 1);
2587                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2588
2589                 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2590                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2591                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2592                 check_added_monitors!(nodes[1], 1);
2593                 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2594                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2595         }
2596         get_announce_close_broadcast_events(&nodes, 0, 1);
2597         assert_eq!(nodes[0].node.list_channels().len(), 0);
2598         assert_eq!(nodes[1].node.list_channels().len(), 0);
2599 }
2600
2601 #[test]
2602 fn revoked_output_claim() {
2603         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2604         // transaction is broadcast by its counterparty
2605         let chanmon_cfgs = create_chanmon_cfgs(2);
2606         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2607         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2608         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2609         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2610         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2611         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2612         assert_eq!(revoked_local_txn.len(), 1);
2613         // Only output is the full channel value back to nodes[0]:
2614         assert_eq!(revoked_local_txn[0].output.len(), 1);
2615         // Send a payment through, updating everyone's latest commitment txn
2616         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2617
2618         // Inform nodes[1] that nodes[0] broadcast a stale tx
2619         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2620         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2621         check_added_monitors!(nodes[1], 1);
2622         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2623         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2624
2625         check_spends!(node_txn[0], revoked_local_txn[0]);
2626         check_spends!(node_txn[1], chan_1.3);
2627
2628         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2629         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2630         get_announce_close_broadcast_events(&nodes, 0, 1);
2631         check_added_monitors!(nodes[0], 1)
2632 }
2633
2634 #[test]
2635 fn claim_htlc_outputs_shared_tx() {
2636         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2637         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2638         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2639         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2640         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2641         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2642
2643         // Create some new channel:
2644         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2645
2646         // Rebalance the network to generate htlc in the two directions
2647         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2648         // 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
2649         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2650         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2651
2652         // Get the will-be-revoked local txn from node[0]
2653         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2654         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2655         assert_eq!(revoked_local_txn[0].input.len(), 1);
2656         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2657         assert_eq!(revoked_local_txn[1].input.len(), 1);
2658         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2659         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2660         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2661
2662         //Revoke the old state
2663         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2664
2665         {
2666                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2667                 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2668                 check_added_monitors!(nodes[0], 1);
2669                 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2670                 check_added_monitors!(nodes[1], 1);
2671                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
2672                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2673
2674                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2675                 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2676
2677                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2678                 check_spends!(node_txn[0], revoked_local_txn[0]);
2679
2680                 let mut witness_lens = BTreeSet::new();
2681                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2682                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2683                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2684                 assert_eq!(witness_lens.len(), 3);
2685                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2686                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2687                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2688
2689                 // Next nodes[1] broadcasts its current local tx state:
2690                 assert_eq!(node_txn[1].input.len(), 1);
2691                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2692
2693                 assert_eq!(node_txn[2].input.len(), 1);
2694                 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2695                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2696                 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2697                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2698                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2699         }
2700         get_announce_close_broadcast_events(&nodes, 0, 1);
2701         assert_eq!(nodes[0].node.list_channels().len(), 0);
2702         assert_eq!(nodes[1].node.list_channels().len(), 0);
2703 }
2704
2705 #[test]
2706 fn claim_htlc_outputs_single_tx() {
2707         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2708         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2709         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2710         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2711         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2712         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2713
2714         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2715
2716         // Rebalance the network to generate htlc in the two directions
2717         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2718         // 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
2719         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2720         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2721         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2722
2723         // Get the will-be-revoked local txn from node[0]
2724         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2725
2726         //Revoke the old state
2727         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2728
2729         {
2730                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2731                 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2732                 check_added_monitors!(nodes[0], 1);
2733                 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2734                 check_added_monitors!(nodes[1], 1);
2735                 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2736
2737                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
2738                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2739
2740                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2741                 assert_eq!(node_txn.len(), 9);
2742                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2743                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2744                 // 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)
2745                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2746
2747                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2748                 assert_eq!(node_txn[2].input.len(), 1);
2749                 check_spends!(node_txn[2], chan_1.3);
2750                 assert_eq!(node_txn[3].input.len(), 1);
2751                 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2752                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2753                 check_spends!(node_txn[3], node_txn[2]);
2754
2755                 // Justice transactions are indices 1-2-4
2756                 assert_eq!(node_txn[0].input.len(), 1);
2757                 assert_eq!(node_txn[1].input.len(), 1);
2758                 assert_eq!(node_txn[4].input.len(), 1);
2759
2760                 check_spends!(node_txn[0], revoked_local_txn[0]);
2761                 check_spends!(node_txn[1], revoked_local_txn[0]);
2762                 check_spends!(node_txn[4], revoked_local_txn[0]);
2763
2764                 let mut witness_lens = BTreeSet::new();
2765                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2766                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2767                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2768                 assert_eq!(witness_lens.len(), 3);
2769                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2770                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2771                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2772         }
2773         get_announce_close_broadcast_events(&nodes, 0, 1);
2774         assert_eq!(nodes[0].node.list_channels().len(), 0);
2775         assert_eq!(nodes[1].node.list_channels().len(), 0);
2776 }
2777
2778 #[test]
2779 fn test_htlc_on_chain_success() {
2780         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2781         // the preimage backward accordingly. So here we test that ChannelManager is
2782         // broadcasting the right event to other nodes in payment path.
2783         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2784         // A --------------------> B ----------------------> C (preimage)
2785         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2786         // commitment transaction was broadcast.
2787         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2788         // towards B.
2789         // B should be able to claim via preimage if A then broadcasts its local tx.
2790         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2791         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2792         // PaymentSent event).
2793
2794         let chanmon_cfgs = create_chanmon_cfgs(3);
2795         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2796         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2797         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2798
2799         // Create some initial channels
2800         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2801         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2802
2803         // Rebalance the network a bit by relaying one payment through all the channels...
2804         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2805         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2806
2807         let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2808         let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2809         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2810
2811         // Broadcast legit commitment tx from C on B's chain
2812         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2813         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2814         assert_eq!(commitment_tx.len(), 1);
2815         check_spends!(commitment_tx[0], chan_2.3);
2816         nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2817         nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2818         check_added_monitors!(nodes[2], 2);
2819         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2820         assert!(updates.update_add_htlcs.is_empty());
2821         assert!(updates.update_fail_htlcs.is_empty());
2822         assert!(updates.update_fail_malformed_htlcs.is_empty());
2823         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2824
2825         connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2826         check_closed_broadcast!(nodes[2], false);
2827         check_added_monitors!(nodes[2], 1);
2828         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)
2829         assert_eq!(node_txn.len(), 5);
2830         assert_eq!(node_txn[0], node_txn[3]);
2831         assert_eq!(node_txn[1], node_txn[4]);
2832         assert_eq!(node_txn[2], commitment_tx[0]);
2833         check_spends!(node_txn[0], commitment_tx[0]);
2834         check_spends!(node_txn[1], commitment_tx[0]);
2835         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2836         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2837         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2838         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2839         assert_eq!(node_txn[0].lock_time, 0);
2840         assert_eq!(node_txn[1].lock_time, 0);
2841
2842         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2843         connect_block(&nodes[1], &Block { header, txdata: node_txn}, 1);
2844         {
2845                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2846                 assert_eq!(added_monitors.len(), 1);
2847                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2848                 added_monitors.clear();
2849         }
2850         let events = nodes[1].node.get_and_clear_pending_msg_events();
2851         {
2852                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2853                 assert_eq!(added_monitors.len(), 2);
2854                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2855                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2856                 added_monitors.clear();
2857         }
2858         assert_eq!(events.len(), 2);
2859         match events[0] {
2860                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2861                 _ => panic!("Unexpected event"),
2862         }
2863         match events[1] {
2864                 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, .. } } => {
2865                         assert!(update_add_htlcs.is_empty());
2866                         assert!(update_fail_htlcs.is_empty());
2867                         assert_eq!(update_fulfill_htlcs.len(), 1);
2868                         assert!(update_fail_malformed_htlcs.is_empty());
2869                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2870                 },
2871                 _ => panic!("Unexpected event"),
2872         };
2873         macro_rules! check_tx_local_broadcast {
2874                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2875                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2876                         assert_eq!(node_txn.len(), 5);
2877                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2878                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2879                         check_spends!(node_txn[0], $commitment_tx);
2880                         check_spends!(node_txn[1], $commitment_tx);
2881                         assert_ne!(node_txn[0].lock_time, 0);
2882                         assert_ne!(node_txn[1].lock_time, 0);
2883                         if $htlc_offered {
2884                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2885                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2886                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2887                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2888                         } else {
2889                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2890                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2891                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2892                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2893                         }
2894                         check_spends!(node_txn[2], $chan_tx);
2895                         check_spends!(node_txn[3], node_txn[2]);
2896                         check_spends!(node_txn[4], node_txn[2]);
2897                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2898                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2899                         assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2900                         assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2901                         assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2902                         assert_ne!(node_txn[3].lock_time, 0);
2903                         assert_ne!(node_txn[4].lock_time, 0);
2904                         node_txn.clear();
2905                 } }
2906         }
2907         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2908         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2909         // timeout-claim of the output that nodes[2] just claimed via success.
2910         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2911
2912         // Broadcast legit commitment tx from A on B's chain
2913         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2914         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2915         check_spends!(commitment_tx[0], chan_1.3);
2916         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2917         check_closed_broadcast!(nodes[1], false);
2918         check_added_monitors!(nodes[1], 1);
2919         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2920         assert_eq!(node_txn.len(), 4);
2921         check_spends!(node_txn[0], commitment_tx[0]);
2922         assert_eq!(node_txn[0].input.len(), 2);
2923         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2924         assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2925         assert_eq!(node_txn[0].lock_time, 0);
2926         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2927         check_spends!(node_txn[1], chan_1.3);
2928         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2929         check_spends!(node_txn[2], node_txn[1]);
2930         check_spends!(node_txn[3], node_txn[1]);
2931         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2932         // we already checked the same situation with A.
2933
2934         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2935         connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2936         check_closed_broadcast!(nodes[0], false);
2937         check_added_monitors!(nodes[0], 1);
2938         let events = nodes[0].node.get_and_clear_pending_events();
2939         assert_eq!(events.len(), 2);
2940         let mut first_claimed = false;
2941         for event in events {
2942                 match event {
2943                         Event::PaymentSent { payment_preimage } => {
2944                                 if payment_preimage == our_payment_preimage {
2945                                         assert!(!first_claimed);
2946                                         first_claimed = true;
2947                                 } else {
2948                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2949                                 }
2950                         },
2951                         _ => panic!("Unexpected event"),
2952                 }
2953         }
2954         check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2955 }
2956
2957 #[test]
2958 fn test_htlc_on_chain_timeout() {
2959         // Test that in case of a unilateral close onchain, we detect the state of output and
2960         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2961         // broadcasting the right event to other nodes in payment path.
2962         // A ------------------> B ----------------------> C (timeout)
2963         //    B's commitment tx                 C's commitment tx
2964         //            \                                  \
2965         //         B's HTLC timeout tx               B's timeout tx
2966
2967         let chanmon_cfgs = create_chanmon_cfgs(3);
2968         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2969         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2970         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2971
2972         // Create some intial channels
2973         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2974         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2975
2976         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2977         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2978         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2979
2980         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2981         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2982
2983         // Broadcast legit commitment tx from C on B's chain
2984         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2985         check_spends!(commitment_tx[0], chan_2.3);
2986         nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2987         check_added_monitors!(nodes[2], 0);
2988         expect_pending_htlcs_forwardable!(nodes[2]);
2989         check_added_monitors!(nodes[2], 1);
2990
2991         let events = nodes[2].node.get_and_clear_pending_msg_events();
2992         assert_eq!(events.len(), 1);
2993         match events[0] {
2994                 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, .. } } => {
2995                         assert!(update_add_htlcs.is_empty());
2996                         assert!(!update_fail_htlcs.is_empty());
2997                         assert!(update_fulfill_htlcs.is_empty());
2998                         assert!(update_fail_malformed_htlcs.is_empty());
2999                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3000                 },
3001                 _ => panic!("Unexpected event"),
3002         };
3003         connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
3004         check_closed_broadcast!(nodes[2], false);
3005         check_added_monitors!(nodes[2], 1);
3006         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
3007         assert_eq!(node_txn.len(), 1);
3008         check_spends!(node_txn[0], chan_2.3);
3009         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
3010
3011         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3012         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3013         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3014         let timeout_tx;
3015         {
3016                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3017                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
3018                 assert_eq!(node_txn[1], node_txn[3]);
3019                 assert_eq!(node_txn[2], node_txn[4]);
3020
3021                 check_spends!(node_txn[0], commitment_tx[0]);
3022                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3023
3024                 check_spends!(node_txn[1], chan_2.3);
3025                 check_spends!(node_txn[2], node_txn[1]);
3026                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3027                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3028
3029                 timeout_tx = node_txn[0].clone();
3030                 node_txn.clear();
3031         }
3032
3033         connect_block(&nodes[1], &Block { header, txdata: vec![timeout_tx]}, 1);
3034         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3035         check_added_monitors!(nodes[1], 1);
3036         check_closed_broadcast!(nodes[1], false);
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         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // Well... here we detect our own htlc_timeout_tx so no tx to be generated
3053         assert_eq!(node_txn.len(), 0);
3054
3055         // Broadcast legit commitment tx from B on A's chain
3056         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3057         check_spends!(commitment_tx[0], chan_1.3);
3058
3059         connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3060         check_closed_broadcast!(nodes[0], false);
3061         check_added_monitors!(nodes[0], 1);
3062         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3063         assert_eq!(node_txn.len(), 3);
3064         check_spends!(node_txn[0], commitment_tx[0]);
3065         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3066         check_spends!(node_txn[1], chan_1.3);
3067         check_spends!(node_txn[2], node_txn[1]);
3068         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3069         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3070 }
3071
3072 #[test]
3073 fn test_simple_commitment_revoked_fail_backward() {
3074         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3075         // and fail backward accordingly.
3076
3077         let chanmon_cfgs = create_chanmon_cfgs(3);
3078         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3079         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3080         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3081
3082         // Create some initial channels
3083         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3084         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3085
3086         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3087         // Get the will-be-revoked local txn from nodes[2]
3088         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3089         // Revoke the old state
3090         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3091
3092         let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3093
3094         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3095         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3096         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3097         check_added_monitors!(nodes[1], 1);
3098         check_closed_broadcast!(nodes[1], false);
3099
3100         expect_pending_htlcs_forwardable!(nodes[1]);
3101         check_added_monitors!(nodes[1], 1);
3102         let events = nodes[1].node.get_and_clear_pending_msg_events();
3103         assert_eq!(events.len(), 1);
3104         match events[0] {
3105                 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, .. } } => {
3106                         assert!(update_add_htlcs.is_empty());
3107                         assert_eq!(update_fail_htlcs.len(), 1);
3108                         assert!(update_fulfill_htlcs.is_empty());
3109                         assert!(update_fail_malformed_htlcs.is_empty());
3110                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3111
3112                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3113                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3114
3115                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3116                         assert_eq!(events.len(), 1);
3117                         match events[0] {
3118                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3119                                 _ => panic!("Unexpected event"),
3120                         }
3121                         expect_payment_failed!(nodes[0], payment_hash, false);
3122                 },
3123                 _ => panic!("Unexpected event"),
3124         }
3125 }
3126
3127 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3128         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3129         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3130         // commitment transaction anymore.
3131         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3132         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3133         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3134         // technically disallowed and we should probably handle it reasonably.
3135         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3136         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3137         // transactions:
3138         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3139         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3140         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3141         //   and once they revoke the previous commitment transaction (allowing us to send a new
3142         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3143         let chanmon_cfgs = create_chanmon_cfgs(3);
3144         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3145         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3146         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3147
3148         // Create some initial channels
3149         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3150         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3151
3152         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3153         // Get the will-be-revoked local txn from nodes[2]
3154         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3155         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3156         // Revoke the old state
3157         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3158
3159         let value = if use_dust {
3160                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3161                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3162                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3163         } else { 3000000 };
3164
3165         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3166         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3167         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3168
3169         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3170         expect_pending_htlcs_forwardable!(nodes[2]);
3171         check_added_monitors!(nodes[2], 1);
3172         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3173         assert!(updates.update_add_htlcs.is_empty());
3174         assert!(updates.update_fulfill_htlcs.is_empty());
3175         assert!(updates.update_fail_malformed_htlcs.is_empty());
3176         assert_eq!(updates.update_fail_htlcs.len(), 1);
3177         assert!(updates.update_fee.is_none());
3178         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3179         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3180         // Drop the last RAA from 3 -> 2
3181
3182         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3183         expect_pending_htlcs_forwardable!(nodes[2]);
3184         check_added_monitors!(nodes[2], 1);
3185         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3186         assert!(updates.update_add_htlcs.is_empty());
3187         assert!(updates.update_fulfill_htlcs.is_empty());
3188         assert!(updates.update_fail_malformed_htlcs.is_empty());
3189         assert_eq!(updates.update_fail_htlcs.len(), 1);
3190         assert!(updates.update_fee.is_none());
3191         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3192         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3193         check_added_monitors!(nodes[1], 1);
3194         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3195         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3196         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3197         check_added_monitors!(nodes[2], 1);
3198
3199         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3200         expect_pending_htlcs_forwardable!(nodes[2]);
3201         check_added_monitors!(nodes[2], 1);
3202         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3203         assert!(updates.update_add_htlcs.is_empty());
3204         assert!(updates.update_fulfill_htlcs.is_empty());
3205         assert!(updates.update_fail_malformed_htlcs.is_empty());
3206         assert_eq!(updates.update_fail_htlcs.len(), 1);
3207         assert!(updates.update_fee.is_none());
3208         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3209         // At this point first_payment_hash has dropped out of the latest two commitment
3210         // transactions that nodes[1] is tracking...
3211         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3212         check_added_monitors!(nodes[1], 1);
3213         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3214         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3215         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3216         check_added_monitors!(nodes[2], 1);
3217
3218         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3219         // on nodes[2]'s RAA.
3220         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3221         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3222         let logger = test_utils::TestLogger::new();
3223         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();
3224         nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3225         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3226         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3227         check_added_monitors!(nodes[1], 0);
3228
3229         if deliver_bs_raa {
3230                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3231                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3232                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3233                 check_added_monitors!(nodes[1], 1);
3234                 let events = nodes[1].node.get_and_clear_pending_events();
3235                 assert_eq!(events.len(), 1);
3236                 match events[0] {
3237                         Event::PendingHTLCsForwardable { .. } => { },
3238                         _ => panic!("Unexpected event"),
3239                 };
3240                 // Deliberately don't process the pending fail-back so they all fail back at once after
3241                 // block connection just like the !deliver_bs_raa case
3242         }
3243
3244         let mut failed_htlcs = HashSet::new();
3245         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3246
3247         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3248         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3249         check_added_monitors!(nodes[1], 1);
3250         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3251
3252         let events = nodes[1].node.get_and_clear_pending_events();
3253         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3254         match events[0] {
3255                 Event::PaymentFailed { ref payment_hash, .. } => {
3256                         assert_eq!(*payment_hash, fourth_payment_hash);
3257                 },
3258                 _ => panic!("Unexpected event"),
3259         }
3260         if !deliver_bs_raa {
3261                 match events[1] {
3262                         Event::PendingHTLCsForwardable { .. } => { },
3263                         _ => panic!("Unexpected event"),
3264                 };
3265         }
3266         nodes[1].node.process_pending_htlc_forwards();
3267         check_added_monitors!(nodes[1], 1);
3268
3269         let events = nodes[1].node.get_and_clear_pending_msg_events();
3270         assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3271         match events[if deliver_bs_raa { 1 } else { 0 }] {
3272                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3273                 _ => panic!("Unexpected event"),
3274         }
3275         if deliver_bs_raa {
3276                 match events[0] {
3277                         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, .. } } => {
3278                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3279                                 assert_eq!(update_add_htlcs.len(), 1);
3280                                 assert!(update_fulfill_htlcs.is_empty());
3281                                 assert!(update_fail_htlcs.is_empty());
3282                                 assert!(update_fail_malformed_htlcs.is_empty());
3283                         },
3284                         _ => panic!("Unexpected event"),
3285                 }
3286         }
3287         match events[if deliver_bs_raa { 2 } else { 1 }] {
3288                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3289                         assert!(update_add_htlcs.is_empty());
3290                         assert_eq!(update_fail_htlcs.len(), 3);
3291                         assert!(update_fulfill_htlcs.is_empty());
3292                         assert!(update_fail_malformed_htlcs.is_empty());
3293                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3294
3295                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3296                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3297                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3298
3299                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3300
3301                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3302                         // If we delivered B's RAA we got an unknown preimage error, not something
3303                         // that we should update our routing table for.
3304                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3305                         for event in events {
3306                                 match event {
3307                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3308                                         _ => panic!("Unexpected event"),
3309                                 }
3310                         }
3311                         let events = nodes[0].node.get_and_clear_pending_events();
3312                         assert_eq!(events.len(), 3);
3313                         match events[0] {
3314                                 Event::PaymentFailed { ref payment_hash, .. } => {
3315                                         assert!(failed_htlcs.insert(payment_hash.0));
3316                                 },
3317                                 _ => panic!("Unexpected event"),
3318                         }
3319                         match events[1] {
3320                                 Event::PaymentFailed { ref payment_hash, .. } => {
3321                                         assert!(failed_htlcs.insert(payment_hash.0));
3322                                 },
3323                                 _ => panic!("Unexpected event"),
3324                         }
3325                         match events[2] {
3326                                 Event::PaymentFailed { ref payment_hash, .. } => {
3327                                         assert!(failed_htlcs.insert(payment_hash.0));
3328                                 },
3329                                 _ => panic!("Unexpected event"),
3330                         }
3331                 },
3332                 _ => panic!("Unexpected event"),
3333         }
3334
3335         assert!(failed_htlcs.contains(&first_payment_hash.0));
3336         assert!(failed_htlcs.contains(&second_payment_hash.0));
3337         assert!(failed_htlcs.contains(&third_payment_hash.0));
3338 }
3339
3340 #[test]
3341 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3342         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3343         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3344         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3345         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3346 }
3347
3348 #[test]
3349 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3350         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3351         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3352         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3353         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3354 }
3355
3356 #[test]
3357 fn fail_backward_pending_htlc_upon_channel_failure() {
3358         let chanmon_cfgs = create_chanmon_cfgs(2);
3359         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3360         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3361         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3362         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3363         let logger = test_utils::TestLogger::new();
3364
3365         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3366         {
3367                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3368                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3369                 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();
3370                 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3371                 check_added_monitors!(nodes[0], 1);
3372
3373                 let payment_event = {
3374                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3375                         assert_eq!(events.len(), 1);
3376                         SendEvent::from_event(events.remove(0))
3377                 };
3378                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3379                 assert_eq!(payment_event.msgs.len(), 1);
3380         }
3381
3382         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3383         let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3384         {
3385                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3386                 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();
3387                 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3388                 check_added_monitors!(nodes[0], 0);
3389
3390                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3391         }
3392
3393         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3394         {
3395                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3396
3397                 let secp_ctx = Secp256k1::new();
3398                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3399                 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3400                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3401                 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();
3402                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3403                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3404                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3405
3406                 // Send a 0-msat update_add_htlc to fail the channel.
3407                 let update_add_htlc = msgs::UpdateAddHTLC {
3408                         channel_id: chan.2,
3409                         htlc_id: 0,
3410                         amount_msat: 0,
3411                         payment_hash,
3412                         cltv_expiry,
3413                         onion_routing_packet,
3414                 };
3415                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3416         }
3417
3418         // Check that Alice fails backward the pending HTLC from the second payment.
3419         expect_payment_failed!(nodes[0], failed_payment_hash, true);
3420         check_closed_broadcast!(nodes[0], true);
3421         check_added_monitors!(nodes[0], 1);
3422 }
3423
3424 #[test]
3425 fn test_htlc_ignore_latest_remote_commitment() {
3426         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3427         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3428         let chanmon_cfgs = create_chanmon_cfgs(2);
3429         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3430         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3431         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3432         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3433
3434         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3435         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3436         check_closed_broadcast!(nodes[0], false);
3437         check_added_monitors!(nodes[0], 1);
3438
3439         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3440         assert_eq!(node_txn.len(), 2);
3441
3442         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3443         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3444         check_closed_broadcast!(nodes[1], false);
3445         check_added_monitors!(nodes[1], 1);
3446
3447         // Duplicate the connect_block call since this may happen due to other listeners
3448         // registering new transactions
3449         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3450 }
3451
3452 #[test]
3453 fn test_force_close_fail_back() {
3454         // Check which HTLCs are failed-backwards on channel force-closure
3455         let chanmon_cfgs = create_chanmon_cfgs(3);
3456         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3457         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3458         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3459         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3460         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3461         let logger = test_utils::TestLogger::new();
3462
3463         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3464
3465         let mut payment_event = {
3466                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3467                 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();
3468                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3469                 check_added_monitors!(nodes[0], 1);
3470
3471                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3472                 assert_eq!(events.len(), 1);
3473                 SendEvent::from_event(events.remove(0))
3474         };
3475
3476         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3477         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3478
3479         expect_pending_htlcs_forwardable!(nodes[1]);
3480
3481         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3482         assert_eq!(events_2.len(), 1);
3483         payment_event = SendEvent::from_event(events_2.remove(0));
3484         assert_eq!(payment_event.msgs.len(), 1);
3485
3486         check_added_monitors!(nodes[1], 1);
3487         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3488         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3489         check_added_monitors!(nodes[2], 1);
3490         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3491
3492         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3493         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3494         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3495
3496         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3497         check_closed_broadcast!(nodes[2], false);
3498         check_added_monitors!(nodes[2], 1);
3499         let tx = {
3500                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3501                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3502                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3503                 // back to nodes[1] upon timeout otherwise.
3504                 assert_eq!(node_txn.len(), 1);
3505                 node_txn.remove(0)
3506         };
3507
3508         let block = Block {
3509                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3510                 txdata: vec![tx.clone()],
3511         };
3512         connect_block(&nodes[1], &block, 1);
3513
3514         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3515         check_closed_broadcast!(nodes[1], false);
3516         check_added_monitors!(nodes[1], 1);
3517
3518         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3519         {
3520                 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3521                 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3522                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3523         }
3524         connect_block(&nodes[2], &block, 1);
3525         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3526         assert_eq!(node_txn.len(), 1);
3527         assert_eq!(node_txn[0].input.len(), 1);
3528         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3529         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3530         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3531
3532         check_spends!(node_txn[0], tx);
3533 }
3534
3535 #[test]
3536 fn test_simple_peer_disconnect() {
3537         // Test that we can reconnect when there are no lost messages
3538         let chanmon_cfgs = create_chanmon_cfgs(3);
3539         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3540         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3541         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3542         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3543         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3544
3545         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3546         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3547         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3548
3549         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3550         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3551         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3552         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3553
3554         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3555         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3556         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3557
3558         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3559         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3560         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3561         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3562
3563         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3564         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3565
3566         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3567         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3568
3569         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3570         {
3571                 let events = nodes[0].node.get_and_clear_pending_events();
3572                 assert_eq!(events.len(), 2);
3573                 match events[0] {
3574                         Event::PaymentSent { payment_preimage } => {
3575                                 assert_eq!(payment_preimage, payment_preimage_3);
3576                         },
3577                         _ => panic!("Unexpected event"),
3578                 }
3579                 match events[1] {
3580                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3581                                 assert_eq!(payment_hash, payment_hash_5);
3582                                 assert!(rejected_by_dest);
3583                         },
3584                         _ => panic!("Unexpected event"),
3585                 }
3586         }
3587
3588         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3589         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3590 }
3591
3592 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3593         // Test that we can reconnect when in-flight HTLC updates get dropped
3594         let chanmon_cfgs = create_chanmon_cfgs(2);
3595         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3596         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3597         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3598         if messages_delivered == 0 {
3599                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3600                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3601         } else {
3602                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3603         }
3604
3605         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3606
3607         let logger = test_utils::TestLogger::new();
3608         let payment_event = {
3609                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3610                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3611                         &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3612                         &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3613                 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3614                 check_added_monitors!(nodes[0], 1);
3615
3616                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3617                 assert_eq!(events.len(), 1);
3618                 SendEvent::from_event(events.remove(0))
3619         };
3620         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3621
3622         if messages_delivered < 2 {
3623                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3624         } else {
3625                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3626                 if messages_delivered >= 3 {
3627                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3628                         check_added_monitors!(nodes[1], 1);
3629                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3630
3631                         if messages_delivered >= 4 {
3632                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3633                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3634                                 check_added_monitors!(nodes[0], 1);
3635
3636                                 if messages_delivered >= 5 {
3637                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3638                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3639                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3640                                         check_added_monitors!(nodes[0], 1);
3641
3642                                         if messages_delivered >= 6 {
3643                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3644                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3645                                                 check_added_monitors!(nodes[1], 1);
3646                                         }
3647                                 }
3648                         }
3649                 }
3650         }
3651
3652         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3653         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3654         if messages_delivered < 3 {
3655                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3656                 // received on either side, both sides will need to resend them.
3657                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3658         } else if messages_delivered == 3 {
3659                 // nodes[0] still wants its RAA + commitment_signed
3660                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3661         } else if messages_delivered == 4 {
3662                 // nodes[0] still wants its commitment_signed
3663                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3664         } else if messages_delivered == 5 {
3665                 // nodes[1] still wants its final RAA
3666                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3667         } else if messages_delivered == 6 {
3668                 // Everything was delivered...
3669                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3670         }
3671
3672         let events_1 = nodes[1].node.get_and_clear_pending_events();
3673         assert_eq!(events_1.len(), 1);
3674         match events_1[0] {
3675                 Event::PendingHTLCsForwardable { .. } => { },
3676                 _ => panic!("Unexpected event"),
3677         };
3678
3679         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3680         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3681         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3682
3683         nodes[1].node.process_pending_htlc_forwards();
3684
3685         let events_2 = nodes[1].node.get_and_clear_pending_events();
3686         assert_eq!(events_2.len(), 1);
3687         match events_2[0] {
3688                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3689                         assert_eq!(payment_hash_1, *payment_hash);
3690                         assert_eq!(*payment_secret, None);
3691                         assert_eq!(amt, 1000000);
3692                 },
3693                 _ => panic!("Unexpected event"),
3694         }
3695
3696         nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3697         check_added_monitors!(nodes[1], 1);
3698
3699         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3700         assert_eq!(events_3.len(), 1);
3701         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3702                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3703                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3704                         assert!(updates.update_add_htlcs.is_empty());
3705                         assert!(updates.update_fail_htlcs.is_empty());
3706                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3707                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3708                         assert!(updates.update_fee.is_none());
3709                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3710                 },
3711                 _ => panic!("Unexpected event"),
3712         };
3713
3714         if messages_delivered >= 1 {
3715                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3716
3717                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3718                 assert_eq!(events_4.len(), 1);
3719                 match events_4[0] {
3720                         Event::PaymentSent { ref payment_preimage } => {
3721                                 assert_eq!(payment_preimage_1, *payment_preimage);
3722                         },
3723                         _ => panic!("Unexpected event"),
3724                 }
3725
3726                 if messages_delivered >= 2 {
3727                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3728                         check_added_monitors!(nodes[0], 1);
3729                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3730
3731                         if messages_delivered >= 3 {
3732                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3733                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3734                                 check_added_monitors!(nodes[1], 1);
3735
3736                                 if messages_delivered >= 4 {
3737                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3738                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3739                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3740                                         check_added_monitors!(nodes[1], 1);
3741
3742                                         if messages_delivered >= 5 {
3743                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3744                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3745                                                 check_added_monitors!(nodes[0], 1);
3746                                         }
3747                                 }
3748                         }
3749                 }
3750         }
3751
3752         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3753         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3754         if messages_delivered < 2 {
3755                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3756                 //TODO: Deduplicate PaymentSent events, then enable this if:
3757                 //if messages_delivered < 1 {
3758                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3759                         assert_eq!(events_4.len(), 1);
3760                         match events_4[0] {
3761                                 Event::PaymentSent { ref payment_preimage } => {
3762                                         assert_eq!(payment_preimage_1, *payment_preimage);
3763                                 },
3764                                 _ => panic!("Unexpected event"),
3765                         }
3766                 //}
3767         } else if messages_delivered == 2 {
3768                 // nodes[0] still wants its RAA + commitment_signed
3769                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3770         } else if messages_delivered == 3 {
3771                 // nodes[0] still wants its commitment_signed
3772                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3773         } else if messages_delivered == 4 {
3774                 // nodes[1] still wants its final RAA
3775                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3776         } else if messages_delivered == 5 {
3777                 // Everything was delivered...
3778                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3779         }
3780
3781         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3782         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3783         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3784
3785         // Channel should still work fine...
3786         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3787         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3788                 &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3789                 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3790         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3791         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3792 }
3793
3794 #[test]
3795 fn test_drop_messages_peer_disconnect_a() {
3796         do_test_drop_messages_peer_disconnect(0);
3797         do_test_drop_messages_peer_disconnect(1);
3798         do_test_drop_messages_peer_disconnect(2);
3799         do_test_drop_messages_peer_disconnect(3);
3800 }
3801
3802 #[test]
3803 fn test_drop_messages_peer_disconnect_b() {
3804         do_test_drop_messages_peer_disconnect(4);
3805         do_test_drop_messages_peer_disconnect(5);
3806         do_test_drop_messages_peer_disconnect(6);
3807 }
3808
3809 #[test]
3810 fn test_funding_peer_disconnect() {
3811         // Test that we can lock in our funding tx while disconnected
3812         let chanmon_cfgs = create_chanmon_cfgs(2);
3813         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3814         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3815         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3816         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3817
3818         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3819         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3820
3821         confirm_transaction(&nodes[0], &tx);
3822         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3823         assert_eq!(events_1.len(), 1);
3824         match events_1[0] {
3825                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3826                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3827                 },
3828                 _ => panic!("Unexpected event"),
3829         }
3830
3831         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3832
3833         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3834         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3835
3836         confirm_transaction(&nodes[1], &tx);
3837         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3838         assert_eq!(events_2.len(), 2);
3839         let funding_locked = match events_2[0] {
3840                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3841                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3842                         msg.clone()
3843                 },
3844                 _ => panic!("Unexpected event"),
3845         };
3846         let bs_announcement_sigs = match events_2[1] {
3847                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3848                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3849                         msg.clone()
3850                 },
3851                 _ => panic!("Unexpected event"),
3852         };
3853
3854         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3855
3856         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3857         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3858         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3859         assert_eq!(events_3.len(), 2);
3860         let as_announcement_sigs = match events_3[0] {
3861                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3862                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3863                         msg.clone()
3864                 },
3865                 _ => panic!("Unexpected event"),
3866         };
3867         let (as_announcement, as_update) = match events_3[1] {
3868                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3869                         (msg.clone(), update_msg.clone())
3870                 },
3871                 _ => panic!("Unexpected event"),
3872         };
3873
3874         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3875         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3876         assert_eq!(events_4.len(), 1);
3877         let (_, bs_update) = match events_4[0] {
3878                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3879                         (msg.clone(), update_msg.clone())
3880                 },
3881                 _ => panic!("Unexpected event"),
3882         };
3883
3884         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3885         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3886         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3887
3888         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3889         let logger = test_utils::TestLogger::new();
3890         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();
3891         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3892         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3893 }
3894
3895 #[test]
3896 fn test_drop_messages_peer_disconnect_dual_htlc() {
3897         // Test that we can handle reconnecting when both sides of a channel have pending
3898         // commitment_updates when we disconnect.
3899         let chanmon_cfgs = create_chanmon_cfgs(2);
3900         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3901         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3902         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3903         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3904         let logger = test_utils::TestLogger::new();
3905
3906         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3907
3908         // Now try to send a second payment which will fail to send
3909         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3910         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3911         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();
3912         nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3913         check_added_monitors!(nodes[0], 1);
3914
3915         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3916         assert_eq!(events_1.len(), 1);
3917         match events_1[0] {
3918                 MessageSendEvent::UpdateHTLCs { .. } => {},
3919                 _ => panic!("Unexpected event"),
3920         }
3921
3922         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3923         check_added_monitors!(nodes[1], 1);
3924
3925         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3926         assert_eq!(events_2.len(), 1);
3927         match events_2[0] {
3928                 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 } } => {
3929                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3930                         assert!(update_add_htlcs.is_empty());
3931                         assert_eq!(update_fulfill_htlcs.len(), 1);
3932                         assert!(update_fail_htlcs.is_empty());
3933                         assert!(update_fail_malformed_htlcs.is_empty());
3934                         assert!(update_fee.is_none());
3935
3936                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3937                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3938                         assert_eq!(events_3.len(), 1);
3939                         match events_3[0] {
3940                                 Event::PaymentSent { ref payment_preimage } => {
3941                                         assert_eq!(*payment_preimage, payment_preimage_1);
3942                                 },
3943                                 _ => panic!("Unexpected event"),
3944                         }
3945
3946                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3947                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3948                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3949                         check_added_monitors!(nodes[0], 1);
3950                 },
3951                 _ => panic!("Unexpected event"),
3952         }
3953
3954         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3955         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3956
3957         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3958         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3959         assert_eq!(reestablish_1.len(), 1);
3960         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3961         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3962         assert_eq!(reestablish_2.len(), 1);
3963
3964         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3965         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3966         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3967         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3968
3969         assert!(as_resp.0.is_none());
3970         assert!(bs_resp.0.is_none());
3971
3972         assert!(bs_resp.1.is_none());
3973         assert!(bs_resp.2.is_none());
3974
3975         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3976
3977         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3978         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3979         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3980         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3981         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3982         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3983         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3984         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3985         // No commitment_signed so get_event_msg's assert(len == 1) passes
3986         check_added_monitors!(nodes[1], 1);
3987
3988         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3989         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3990         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3991         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3992         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3993         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3994         assert!(bs_second_commitment_signed.update_fee.is_none());
3995         check_added_monitors!(nodes[1], 1);
3996
3997         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3998         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3999         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4000         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4001         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4002         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4003         assert!(as_commitment_signed.update_fee.is_none());
4004         check_added_monitors!(nodes[0], 1);
4005
4006         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4007         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4008         // No commitment_signed so get_event_msg's assert(len == 1) passes
4009         check_added_monitors!(nodes[0], 1);
4010
4011         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4012         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4013         // No commitment_signed so get_event_msg's assert(len == 1) passes
4014         check_added_monitors!(nodes[1], 1);
4015
4016         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4017         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4018         check_added_monitors!(nodes[1], 1);
4019
4020         expect_pending_htlcs_forwardable!(nodes[1]);
4021
4022         let events_5 = nodes[1].node.get_and_clear_pending_events();
4023         assert_eq!(events_5.len(), 1);
4024         match events_5[0] {
4025                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4026                         assert_eq!(payment_hash_2, *payment_hash);
4027                         assert_eq!(*payment_secret, None);
4028                 },
4029                 _ => panic!("Unexpected event"),
4030         }
4031
4032         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4033         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4034         check_added_monitors!(nodes[0], 1);
4035
4036         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4037 }
4038
4039 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4040         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4041         // to avoid our counterparty failing the channel.
4042         let chanmon_cfgs = create_chanmon_cfgs(2);
4043         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4044         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4045         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4046
4047         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4048         let logger = test_utils::TestLogger::new();
4049
4050         let our_payment_hash = if send_partial_mpp {
4051                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4052                 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();
4053                 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4054                 let payment_secret = PaymentSecret([0xdb; 32]);
4055                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4056                 // indicates there are more HTLCs coming.
4057                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
4058                 check_added_monitors!(nodes[0], 1);
4059                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4060                 assert_eq!(events.len(), 1);
4061                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4062                 // hop should *not* yet generate any PaymentReceived event(s).
4063                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4064                 our_payment_hash
4065         } else {
4066                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4067         };
4068
4069         let mut block = Block {
4070                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4071                 txdata: vec![],
4072         };
4073         connect_block(&nodes[0], &block, 101);
4074         connect_block(&nodes[1], &block, 101);
4075         for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4076                 block.header.prev_blockhash = block.block_hash();
4077                 connect_block(&nodes[0], &block, i);
4078                 connect_block(&nodes[1], &block, i);
4079         }
4080
4081         expect_pending_htlcs_forwardable!(nodes[1]);
4082
4083         check_added_monitors!(nodes[1], 1);
4084         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4085         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4086         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4087         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4088         assert!(htlc_timeout_updates.update_fee.is_none());
4089
4090         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4091         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4092         // 100_000 msat as u64, followed by a height of 123 as u32
4093         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4094         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
4095         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4096 }
4097
4098 #[test]
4099 fn test_htlc_timeout() {
4100         do_test_htlc_timeout(true);
4101         do_test_htlc_timeout(false);
4102 }
4103
4104 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4105         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4106         let chanmon_cfgs = create_chanmon_cfgs(3);
4107         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4108         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4109         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4110         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4111         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4112         let logger = test_utils::TestLogger::new();
4113
4114         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4115         let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4116         {
4117                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4118                 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();
4119                 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4120         }
4121         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4122         check_added_monitors!(nodes[1], 1);
4123
4124         // Now attempt to route a second payment, which should be placed in the holding cell
4125         let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4126         if forwarded_htlc {
4127                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4128                 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();
4129                 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4130                 check_added_monitors!(nodes[0], 1);
4131                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4132                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4133                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4134                 expect_pending_htlcs_forwardable!(nodes[1]);
4135                 check_added_monitors!(nodes[1], 0);
4136         } else {
4137                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4138                 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();
4139                 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4140                 check_added_monitors!(nodes[1], 0);
4141         }
4142
4143         let mut block = Block {
4144                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4145                 txdata: vec![],
4146         };
4147         connect_block(&nodes[1], &block, 101);
4148         for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4149                 block.header.prev_blockhash = block.block_hash();
4150                 connect_block(&nodes[1], &block, i);
4151         }
4152
4153         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4154         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4155
4156         block.header.prev_blockhash = block.block_hash();
4157         connect_block(&nodes[1], &block, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4158
4159         if forwarded_htlc {
4160                 expect_pending_htlcs_forwardable!(nodes[1]);
4161                 check_added_monitors!(nodes[1], 1);
4162                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4163                 assert_eq!(fail_commit.len(), 1);
4164                 match fail_commit[0] {
4165                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4166                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4167                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4168                         },
4169                         _ => unreachable!(),
4170                 }
4171                 expect_payment_failed!(nodes[0], second_payment_hash, false);
4172                 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4173                         match update {
4174                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4175                                 _ => panic!("Unexpected event"),
4176                         }
4177                 } else {
4178                         panic!("Unexpected event");
4179                 }
4180         } else {
4181                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4182         }
4183 }
4184
4185 #[test]
4186 fn test_holding_cell_htlc_add_timeouts() {
4187         do_test_holding_cell_htlc_add_timeouts(false);
4188         do_test_holding_cell_htlc_add_timeouts(true);
4189 }
4190
4191 #[test]
4192 fn test_invalid_channel_announcement() {
4193         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4194         let secp_ctx = Secp256k1::new();
4195         let chanmon_cfgs = create_chanmon_cfgs(2);
4196         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4197         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4198         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4199
4200         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4201
4202         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4203         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4204         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4205         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4206
4207         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 } );
4208
4209         let as_bitcoin_key = as_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4210         let bs_bitcoin_key = bs_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4211
4212         let as_network_key = nodes[0].node.get_our_node_id();
4213         let bs_network_key = nodes[1].node.get_our_node_id();
4214
4215         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4216
4217         let mut chan_announcement;
4218
4219         macro_rules! dummy_unsigned_msg {
4220                 () => {
4221                         msgs::UnsignedChannelAnnouncement {
4222                                 features: ChannelFeatures::known(),
4223                                 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4224                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4225                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4226                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4227                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4228                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4229                                 excess_data: Vec::new(),
4230                         };
4231                 }
4232         }
4233
4234         macro_rules! sign_msg {
4235                 ($unsigned_msg: expr) => {
4236                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4237                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_signer().inner.funding_key);
4238                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_signer().inner.funding_key);
4239                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4240                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4241                         chan_announcement = msgs::ChannelAnnouncement {
4242                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4243                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4244                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4245                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4246                                 contents: $unsigned_msg
4247                         }
4248                 }
4249         }
4250
4251         let unsigned_msg = dummy_unsigned_msg!();
4252         sign_msg!(unsigned_msg);
4253         assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4254         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 } );
4255
4256         // Configured with Network::Testnet
4257         let mut unsigned_msg = dummy_unsigned_msg!();
4258         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4259         sign_msg!(unsigned_msg);
4260         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4261
4262         let mut unsigned_msg = dummy_unsigned_msg!();
4263         unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4264         sign_msg!(unsigned_msg);
4265         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4266 }
4267
4268 #[test]
4269 fn test_no_txn_manager_serialize_deserialize() {
4270         let chanmon_cfgs = create_chanmon_cfgs(2);
4271         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4272         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4273         let logger: test_utils::TestLogger;
4274         let fee_estimator: test_utils::TestFeeEstimator;
4275         let persister: test_utils::TestPersister;
4276         let new_chain_monitor: test_utils::TestChainMonitor;
4277         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4278         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4279
4280         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4281
4282         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4283
4284         let nodes_0_serialized = nodes[0].node.encode();
4285         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4286         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4287
4288         logger = test_utils::TestLogger::new();
4289         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4290         persister = test_utils::TestPersister::new();
4291         let keys_manager = &chanmon_cfgs[0].keys_manager;
4292         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4293         nodes[0].chain_monitor = &new_chain_monitor;
4294         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4295         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4296                 &mut chan_0_monitor_read, keys_manager).unwrap();
4297         assert!(chan_0_monitor_read.is_empty());
4298
4299         let mut nodes_0_read = &nodes_0_serialized[..];
4300         let config = UserConfig::default();
4301         let (_, nodes_0_deserialized_tmp) = {
4302                 let mut channel_monitors = HashMap::new();
4303                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4304                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4305                         default_config: config,
4306                         keys_manager,
4307                         fee_estimator: &fee_estimator,
4308                         chain_monitor: nodes[0].chain_monitor,
4309                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4310                         logger: &logger,
4311                         channel_monitors,
4312                 }).unwrap()
4313         };
4314         nodes_0_deserialized = nodes_0_deserialized_tmp;
4315         assert!(nodes_0_read.is_empty());
4316
4317         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4318         nodes[0].node = &nodes_0_deserialized;
4319         assert_eq!(nodes[0].node.list_channels().len(), 1);
4320         check_added_monitors!(nodes[0], 1);
4321
4322         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4323         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4324         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4325         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4326
4327         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4328         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4329         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4330         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4331
4332         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4333         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4334         for node in nodes.iter() {
4335                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4336                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4337                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4338         }
4339
4340         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4341 }
4342
4343 #[test]
4344 fn test_manager_serialize_deserialize_events() {
4345         // This test makes sure the events field in ChannelManager survives de/serialization
4346         let chanmon_cfgs = create_chanmon_cfgs(2);
4347         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4348         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4349         let fee_estimator: test_utils::TestFeeEstimator;
4350         let persister: test_utils::TestPersister;
4351         let logger: test_utils::TestLogger;
4352         let new_chain_monitor: test_utils::TestChainMonitor;
4353         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4354         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4355
4356         // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4357         let channel_value = 100000;
4358         let push_msat = 10001;
4359         let a_flags = InitFeatures::known();
4360         let b_flags = InitFeatures::known();
4361         let node_a = nodes.remove(0);
4362         let node_b = nodes.remove(0);
4363         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4364         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()));
4365         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()));
4366
4367         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4368
4369         node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4370         check_added_monitors!(node_a, 0);
4371
4372         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()));
4373         {
4374                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4375                 assert_eq!(added_monitors.len(), 1);
4376                 assert_eq!(added_monitors[0].0, funding_output);
4377                 added_monitors.clear();
4378         }
4379
4380         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()));
4381         {
4382                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4383                 assert_eq!(added_monitors.len(), 1);
4384                 assert_eq!(added_monitors[0].0, funding_output);
4385                 added_monitors.clear();
4386         }
4387         // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4388
4389         nodes.push(node_a);
4390         nodes.push(node_b);
4391
4392         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4393         let nodes_0_serialized = nodes[0].node.encode();
4394         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4395         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4396
4397         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4398         logger = test_utils::TestLogger::new();
4399         persister = test_utils::TestPersister::new();
4400         let keys_manager = &chanmon_cfgs[0].keys_manager;
4401         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4402         nodes[0].chain_monitor = &new_chain_monitor;
4403         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4404         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4405                 &mut chan_0_monitor_read, keys_manager).unwrap();
4406         assert!(chan_0_monitor_read.is_empty());
4407
4408         let mut nodes_0_read = &nodes_0_serialized[..];
4409         let config = UserConfig::default();
4410         let (_, nodes_0_deserialized_tmp) = {
4411                 let mut channel_monitors = HashMap::new();
4412                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4413                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4414                         default_config: config,
4415                         keys_manager,
4416                         fee_estimator: &fee_estimator,
4417                         chain_monitor: nodes[0].chain_monitor,
4418                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4419                         logger: &logger,
4420                         channel_monitors,
4421                 }).unwrap()
4422         };
4423         nodes_0_deserialized = nodes_0_deserialized_tmp;
4424         assert!(nodes_0_read.is_empty());
4425
4426         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4427
4428         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4429         nodes[0].node = &nodes_0_deserialized;
4430
4431         // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4432         let events_4 = nodes[0].node.get_and_clear_pending_events();
4433         assert_eq!(events_4.len(), 1);
4434         match events_4[0] {
4435                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4436                         assert_eq!(user_channel_id, 42);
4437                         assert_eq!(*funding_txo, funding_output);
4438                 },
4439                 _ => panic!("Unexpected event"),
4440         };
4441
4442         // Make sure the channel is functioning as though the de/serialization never happened
4443         assert_eq!(nodes[0].node.list_channels().len(), 1);
4444         check_added_monitors!(nodes[0], 1);
4445
4446         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4447         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4448         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4449         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4450
4451         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4452         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4453         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4454         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4455
4456         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4457         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4458         for node in nodes.iter() {
4459                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4460                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4461                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4462         }
4463
4464         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4465 }
4466
4467 #[test]
4468 fn test_simple_manager_serialize_deserialize() {
4469         let chanmon_cfgs = create_chanmon_cfgs(2);
4470         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4471         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4472         let logger: test_utils::TestLogger;
4473         let fee_estimator: test_utils::TestFeeEstimator;
4474         let persister: test_utils::TestPersister;
4475         let new_chain_monitor: test_utils::TestChainMonitor;
4476         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4477         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4478         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4479
4480         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4481         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4482
4483         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4484
4485         let nodes_0_serialized = nodes[0].node.encode();
4486         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4487         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4488
4489         logger = test_utils::TestLogger::new();
4490         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4491         persister = test_utils::TestPersister::new();
4492         let keys_manager = &chanmon_cfgs[0].keys_manager;
4493         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4494         nodes[0].chain_monitor = &new_chain_monitor;
4495         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4496         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4497                 &mut chan_0_monitor_read, keys_manager).unwrap();
4498         assert!(chan_0_monitor_read.is_empty());
4499
4500         let mut nodes_0_read = &nodes_0_serialized[..];
4501         let (_, nodes_0_deserialized_tmp) = {
4502                 let mut channel_monitors = HashMap::new();
4503                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4504                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4505                         default_config: UserConfig::default(),
4506                         keys_manager,
4507                         fee_estimator: &fee_estimator,
4508                         chain_monitor: nodes[0].chain_monitor,
4509                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4510                         logger: &logger,
4511                         channel_monitors,
4512                 }).unwrap()
4513         };
4514         nodes_0_deserialized = nodes_0_deserialized_tmp;
4515         assert!(nodes_0_read.is_empty());
4516
4517         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4518         nodes[0].node = &nodes_0_deserialized;
4519         check_added_monitors!(nodes[0], 1);
4520
4521         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4522
4523         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4524         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4525 }
4526
4527 #[test]
4528 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4529         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4530         let chanmon_cfgs = create_chanmon_cfgs(4);
4531         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4532         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4533         let logger: test_utils::TestLogger;
4534         let fee_estimator: test_utils::TestFeeEstimator;
4535         let persister: test_utils::TestPersister;
4536         let new_chain_monitor: test_utils::TestChainMonitor;
4537         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4538         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4539         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4540         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4541         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4542
4543         let mut node_0_stale_monitors_serialized = Vec::new();
4544         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4545                 let mut writer = test_utils::TestVecWriter(Vec::new());
4546                 monitor.1.write(&mut writer).unwrap();
4547                 node_0_stale_monitors_serialized.push(writer.0);
4548         }
4549
4550         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4551
4552         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4553         let nodes_0_serialized = nodes[0].node.encode();
4554
4555         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4556         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4557         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4558         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4559
4560         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4561         // nodes[3])
4562         let mut node_0_monitors_serialized = Vec::new();
4563         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4564                 let mut writer = test_utils::TestVecWriter(Vec::new());
4565                 monitor.1.write(&mut writer).unwrap();
4566                 node_0_monitors_serialized.push(writer.0);
4567         }
4568
4569         logger = test_utils::TestLogger::new();
4570         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4571         persister = test_utils::TestPersister::new();
4572         let keys_manager = &chanmon_cfgs[0].keys_manager;
4573         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4574         nodes[0].chain_monitor = &new_chain_monitor;
4575
4576
4577         let mut node_0_stale_monitors = Vec::new();
4578         for serialized in node_0_stale_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_stale_monitors.push(monitor);
4583         }
4584
4585         let mut node_0_monitors = Vec::new();
4586         for serialized in node_0_monitors_serialized.iter() {
4587                 let mut read = &serialized[..];
4588                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4589                 assert!(read.is_empty());
4590                 node_0_monitors.push(monitor);
4591         }
4592
4593         let mut nodes_0_read = &nodes_0_serialized[..];
4594         if let Err(msgs::DecodeError::InvalidValue) =
4595                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4596                 default_config: UserConfig::default(),
4597                 keys_manager,
4598                 fee_estimator: &fee_estimator,
4599                 chain_monitor: nodes[0].chain_monitor,
4600                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4601                 logger: &logger,
4602                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4603         }) { } else {
4604                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4605         };
4606
4607         let mut nodes_0_read = &nodes_0_serialized[..];
4608         let (_, nodes_0_deserialized_tmp) =
4609                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4610                 default_config: UserConfig::default(),
4611                 keys_manager,
4612                 fee_estimator: &fee_estimator,
4613                 chain_monitor: nodes[0].chain_monitor,
4614                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4615                 logger: &logger,
4616                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4617         }).unwrap();
4618         nodes_0_deserialized = nodes_0_deserialized_tmp;
4619         assert!(nodes_0_read.is_empty());
4620
4621         { // Channel close should result in a commitment tx and an HTLC tx
4622                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4623                 assert_eq!(txn.len(), 2);
4624                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4625                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4626         }
4627
4628         for monitor in node_0_monitors.drain(..) {
4629                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4630                 check_added_monitors!(nodes[0], 1);
4631         }
4632         nodes[0].node = &nodes_0_deserialized;
4633
4634         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4635         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4636         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4637         //... and we can even still claim the payment!
4638         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4639
4640         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4641         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4642         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4643         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4644         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4645         assert_eq!(msg_events.len(), 1);
4646         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4647                 match action {
4648                         &ErrorAction::SendErrorMessage { ref msg } => {
4649                                 assert_eq!(msg.channel_id, channel_id);
4650                         },
4651                         _ => panic!("Unexpected event!"),
4652                 }
4653         }
4654 }
4655
4656 macro_rules! check_spendable_outputs {
4657         ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4658                 {
4659                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4660                         let mut txn = Vec::new();
4661                         let mut all_outputs = Vec::new();
4662                         let secp_ctx = Secp256k1::new();
4663                         for event in events.drain(..) {
4664                                 match event {
4665                                         Event::SpendableOutputs { mut outputs } => {
4666                                                 for outp in outputs.drain(..) {
4667                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4668                                                         all_outputs.push(outp);
4669                                                 }
4670                                         },
4671                                         _ => panic!("Unexpected event"),
4672                                 };
4673                         }
4674                         if all_outputs.len() > 1 {
4675                                 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) {
4676                                         txn.push(tx);
4677                                 }
4678                         }
4679                         txn
4680                 }
4681         }
4682 }
4683
4684 #[test]
4685 fn test_claim_sizeable_push_msat() {
4686         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4687         let chanmon_cfgs = create_chanmon_cfgs(2);
4688         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4689         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4690         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4691
4692         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4693         nodes[1].node.force_close_channel(&chan.2).unwrap();
4694         check_closed_broadcast!(nodes[1], false);
4695         check_added_monitors!(nodes[1], 1);
4696         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4697         assert_eq!(node_txn.len(), 1);
4698         check_spends!(node_txn[0], chan.3);
4699         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
4700
4701         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4702         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4703         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4704
4705         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4706         assert_eq!(spend_txn.len(), 1);
4707         check_spends!(spend_txn[0], node_txn[0]);
4708 }
4709
4710 #[test]
4711 fn test_claim_on_remote_sizeable_push_msat() {
4712         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4713         // to_remote output is encumbered by a P2WPKH
4714         let chanmon_cfgs = create_chanmon_cfgs(2);
4715         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4716         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4717         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4718
4719         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4720         nodes[0].node.force_close_channel(&chan.2).unwrap();
4721         check_closed_broadcast!(nodes[0], false);
4722         check_added_monitors!(nodes[0], 1);
4723
4724         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4725         assert_eq!(node_txn.len(), 1);
4726         check_spends!(node_txn[0], chan.3);
4727         assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
4728
4729         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4730         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4731         check_closed_broadcast!(nodes[1], false);
4732         check_added_monitors!(nodes[1], 1);
4733         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4734
4735         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4736         assert_eq!(spend_txn.len(), 1);
4737         check_spends!(spend_txn[0], node_txn[0]);
4738 }
4739
4740 #[test]
4741 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4742         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4743         // to_remote output is encumbered by a P2WPKH
4744
4745         let chanmon_cfgs = create_chanmon_cfgs(2);
4746         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4747         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4748         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4749
4750         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4751         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4752         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4753         assert_eq!(revoked_local_txn[0].input.len(), 1);
4754         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4755
4756         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4757         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4758         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4759         check_closed_broadcast!(nodes[1], false);
4760         check_added_monitors!(nodes[1], 1);
4761
4762         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4763         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4764         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4765         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4766
4767         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4768         assert_eq!(spend_txn.len(), 3);
4769         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4770         check_spends!(spend_txn[1], node_txn[0]);
4771         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4772 }
4773
4774 #[test]
4775 fn test_static_spendable_outputs_preimage_tx() {
4776         let chanmon_cfgs = create_chanmon_cfgs(2);
4777         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4778         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4779         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4780
4781         // Create some initial channels
4782         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4783
4784         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4785
4786         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4787         assert_eq!(commitment_tx[0].input.len(), 1);
4788         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4789
4790         // Settle A's commitment tx on B's chain
4791         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4792         assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4793         check_added_monitors!(nodes[1], 1);
4794         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4795         check_added_monitors!(nodes[1], 1);
4796         let events = nodes[1].node.get_and_clear_pending_msg_events();
4797         match events[0] {
4798                 MessageSendEvent::UpdateHTLCs { .. } => {},
4799                 _ => panic!("Unexpected event"),
4800         }
4801         match events[1] {
4802                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4803                 _ => panic!("Unexepected event"),
4804         }
4805
4806         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4807         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4808         assert_eq!(node_txn.len(), 3);
4809         check_spends!(node_txn[0], commitment_tx[0]);
4810         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4811         check_spends!(node_txn[1], chan_1.3);
4812         check_spends!(node_txn[2], node_txn[1]);
4813
4814         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4815         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4816         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4817
4818         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4819         assert_eq!(spend_txn.len(), 1);
4820         check_spends!(spend_txn[0], node_txn[0]);
4821 }
4822
4823 #[test]
4824 fn test_static_spendable_outputs_timeout_tx() {
4825         let chanmon_cfgs = create_chanmon_cfgs(2);
4826         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4827         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4828         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4829
4830         // Create some initial channels
4831         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4832
4833         // Rebalance the network a bit by relaying one payment through all the channels ...
4834         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4835
4836         let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4837
4838         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4839         assert_eq!(commitment_tx[0].input.len(), 1);
4840         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4841
4842         // Settle A's commitment tx on B' chain
4843         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4844         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4845         check_added_monitors!(nodes[1], 1);
4846         let events = nodes[1].node.get_and_clear_pending_msg_events();
4847         match events[0] {
4848                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4849                 _ => panic!("Unexpected event"),
4850         }
4851
4852         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4853         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4854         assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4855         check_spends!(node_txn[0],  commitment_tx[0].clone());
4856         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4857         check_spends!(node_txn[1], chan_1.3.clone());
4858         check_spends!(node_txn[2], node_txn[1]);
4859
4860         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4861         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4862         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4863         expect_payment_failed!(nodes[1], our_payment_hash, true);
4864
4865         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4866         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4867         check_spends!(spend_txn[0], commitment_tx[0]);
4868         check_spends!(spend_txn[1], node_txn[0]);
4869         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4870 }
4871
4872 #[test]
4873 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4874         let chanmon_cfgs = create_chanmon_cfgs(2);
4875         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4876         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4877         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4878
4879         // Create some initial channels
4880         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4881
4882         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4883         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4884         assert_eq!(revoked_local_txn[0].input.len(), 1);
4885         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4886
4887         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4888
4889         let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4890         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4891         check_closed_broadcast!(nodes[1], false);
4892         check_added_monitors!(nodes[1], 1);
4893
4894         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4895         assert_eq!(node_txn.len(), 2);
4896         assert_eq!(node_txn[0].input.len(), 2);
4897         check_spends!(node_txn[0], revoked_local_txn[0]);
4898
4899         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4900         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4901         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4902
4903         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4904         assert_eq!(spend_txn.len(), 1);
4905         check_spends!(spend_txn[0], node_txn[0]);
4906 }
4907
4908 #[test]
4909 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4910         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4911         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4912         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4913         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4914         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4915
4916         // Create some initial channels
4917         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4918
4919         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4920         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4921         assert_eq!(revoked_local_txn[0].input.len(), 1);
4922         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4923
4924         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4925
4926         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4927         // A will generate HTLC-Timeout from revoked commitment tx
4928         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4929         check_closed_broadcast!(nodes[0], false);
4930         check_added_monitors!(nodes[0], 1);
4931
4932         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4933         assert_eq!(revoked_htlc_txn.len(), 2);
4934         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4935         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4936         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4937         check_spends!(revoked_htlc_txn[1], chan_1.3);
4938
4939         // B will generate justice tx from A's revoked commitment/HTLC tx
4940         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
4941         check_closed_broadcast!(nodes[1], false);
4942         check_added_monitors!(nodes[1], 1);
4943
4944         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4945         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4946         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4947         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4948         // transactions next...
4949         assert_eq!(node_txn[0].input.len(), 3);
4950         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4951
4952         assert_eq!(node_txn[1].input.len(), 2);
4953         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4954         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4955                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4956         } else {
4957                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4958                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4959         }
4960
4961         assert_eq!(node_txn[2].input.len(), 1);
4962         check_spends!(node_txn[2], chan_1.3);
4963
4964         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4965         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
4966         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4967
4968         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4969         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4970         assert_eq!(spend_txn.len(), 1);
4971         assert_eq!(spend_txn[0].input.len(), 1);
4972         check_spends!(spend_txn[0], node_txn[1]);
4973 }
4974
4975 #[test]
4976 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4977         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4978         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4979         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4980         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4981         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4982
4983         // Create some initial channels
4984         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4985
4986         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4987         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4988         assert_eq!(revoked_local_txn[0].input.len(), 1);
4989         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4990
4991         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4992         assert_eq!(revoked_local_txn[0].output.len(), 2);
4993
4994         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4995
4996         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4997         // B will generate HTLC-Success from revoked commitment tx
4998         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4999         check_closed_broadcast!(nodes[1], false);
5000         check_added_monitors!(nodes[1], 1);
5001         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5002
5003         assert_eq!(revoked_htlc_txn.len(), 2);
5004         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5005         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5006         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5007
5008         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5009         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5010         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5011
5012         // A will generate justice tx from B's revoked commitment/HTLC tx
5013         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5014         check_closed_broadcast!(nodes[0], false);
5015         check_added_monitors!(nodes[0], 1);
5016
5017         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5018         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5019
5020         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5021         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5022         // transactions next...
5023         assert_eq!(node_txn[0].input.len(), 2);
5024         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5025         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5026                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5027         } else {
5028                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5029                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5030         }
5031
5032         assert_eq!(node_txn[1].input.len(), 1);
5033         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5034
5035         check_spends!(node_txn[2], chan_1.3);
5036
5037         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5038         connect_block(&nodes[0], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5039         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5040
5041         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5042         // didn't try to generate any new transactions.
5043
5044         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5045         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5046         assert_eq!(spend_txn.len(), 3);
5047         assert_eq!(spend_txn[0].input.len(), 1);
5048         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5049         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5050         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5051         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5052 }
5053
5054 #[test]
5055 fn test_onchain_to_onchain_claim() {
5056         // Test that in case of channel closure, we detect the state of output and claim HTLC
5057         // on downstream peer's remote commitment tx.
5058         // First, have C claim an HTLC against its own latest commitment transaction.
5059         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5060         // channel.
5061         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5062         // gets broadcast.
5063
5064         let chanmon_cfgs = create_chanmon_cfgs(3);
5065         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5066         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5067         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5068
5069         // Create some initial channels
5070         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5071         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5072
5073         // Rebalance the network a bit by relaying one payment through all the channels ...
5074         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5075         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5076
5077         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5078         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5079         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5080         check_spends!(commitment_tx[0], chan_2.3);
5081         nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5082         check_added_monitors!(nodes[2], 1);
5083         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5084         assert!(updates.update_add_htlcs.is_empty());
5085         assert!(updates.update_fail_htlcs.is_empty());
5086         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5087         assert!(updates.update_fail_malformed_htlcs.is_empty());
5088
5089         connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5090         check_closed_broadcast!(nodes[2], false);
5091         check_added_monitors!(nodes[2], 1);
5092
5093         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5094         assert_eq!(c_txn.len(), 3);
5095         assert_eq!(c_txn[0], c_txn[2]);
5096         assert_eq!(commitment_tx[0], c_txn[1]);
5097         check_spends!(c_txn[1], chan_2.3);
5098         check_spends!(c_txn[2], c_txn[1]);
5099         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5100         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5101         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5102         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5103
5104         // 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
5105         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5106         {
5107                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5108                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5109                 assert_eq!(b_txn.len(), 3);
5110                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5111                 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5112                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5113                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5114                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5115                 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5116                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5117                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5118                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5119                 b_txn.clear();
5120         }
5121         check_added_monitors!(nodes[1], 1);
5122         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5123         check_added_monitors!(nodes[1], 1);
5124         match msg_events[0] {
5125                 MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
5126                 _ => panic!("Unexpected event"),
5127         }
5128         match msg_events[1] {
5129                 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, .. } } => {
5130                         assert!(update_add_htlcs.is_empty());
5131                         assert!(update_fail_htlcs.is_empty());
5132                         assert_eq!(update_fulfill_htlcs.len(), 1);
5133                         assert!(update_fail_malformed_htlcs.is_empty());
5134                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5135                 },
5136                 _ => panic!("Unexpected event"),
5137         };
5138         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5139         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5140         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5141         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5142         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5143         assert_eq!(b_txn.len(), 3);
5144         check_spends!(b_txn[1], chan_1.3);
5145         check_spends!(b_txn[2], b_txn[1]);
5146         check_spends!(b_txn[0], commitment_tx[0]);
5147         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5148         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5149         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5150
5151         check_closed_broadcast!(nodes[1], false);
5152         check_added_monitors!(nodes[1], 1);
5153 }
5154
5155 #[test]
5156 fn test_duplicate_payment_hash_one_failure_one_success() {
5157         // Topology : A --> B --> C
5158         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5159         let chanmon_cfgs = create_chanmon_cfgs(3);
5160         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5161         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5162         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5163
5164         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5165         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5166
5167         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5168         *nodes[0].network_payment_count.borrow_mut() -= 1;
5169         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5170
5171         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5172         assert_eq!(commitment_txn[0].input.len(), 1);
5173         check_spends!(commitment_txn[0], chan_2.3);
5174
5175         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5176         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5177         check_closed_broadcast!(nodes[1], false);
5178         check_added_monitors!(nodes[1], 1);
5179
5180         let htlc_timeout_tx;
5181         { // Extract one of the two HTLC-Timeout transaction
5182                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5183                 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5184                 assert_eq!(node_txn.len(), 5);
5185                 check_spends!(node_txn[0], commitment_txn[0]);
5186                 assert_eq!(node_txn[0].input.len(), 1);
5187                 check_spends!(node_txn[1], commitment_txn[0]);
5188                 assert_eq!(node_txn[1].input.len(), 1);
5189                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5190                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5191                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5192                 check_spends!(node_txn[2], chan_2.3);
5193                 check_spends!(node_txn[3], node_txn[2]);
5194                 check_spends!(node_txn[4], node_txn[2]);
5195                 htlc_timeout_tx = node_txn[1].clone();
5196         }
5197
5198         nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5199         connect_block(&nodes[2], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5200         check_added_monitors!(nodes[2], 3);
5201         let events = nodes[2].node.get_and_clear_pending_msg_events();
5202         match events[0] {
5203                 MessageSendEvent::UpdateHTLCs { .. } => {},
5204                 _ => panic!("Unexpected event"),
5205         }
5206         match events[1] {
5207                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5208                 _ => panic!("Unexepected event"),
5209         }
5210         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5211         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)
5212         check_spends!(htlc_success_txn[2], chan_2.3);
5213         check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5214         check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5215         assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5216         assert_eq!(htlc_success_txn[0].input.len(), 1);
5217         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5218         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5219         assert_eq!(htlc_success_txn[1].input.len(), 1);
5220         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5221         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5222         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5223         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5224
5225         connect_block(&nodes[1], &Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5226         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
5227         expect_pending_htlcs_forwardable!(nodes[1]);
5228         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5229         assert!(htlc_updates.update_add_htlcs.is_empty());
5230         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5231         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5232         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5233         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5234         check_added_monitors!(nodes[1], 1);
5235
5236         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5237         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5238         {
5239                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5240                 let events = nodes[0].node.get_and_clear_pending_msg_events();
5241                 assert_eq!(events.len(), 1);
5242                 match events[0] {
5243                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
5244                         },
5245                         _ => { panic!("Unexpected event"); }
5246                 }
5247         }
5248         expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5249
5250         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5251         connect_block(&nodes[1], &Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5252         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5253         assert!(updates.update_add_htlcs.is_empty());
5254         assert!(updates.update_fail_htlcs.is_empty());
5255         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5256         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5257         assert!(updates.update_fail_malformed_htlcs.is_empty());
5258         check_added_monitors!(nodes[1], 1);
5259
5260         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5261         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5262
5263         let events = nodes[0].node.get_and_clear_pending_events();
5264         match events[0] {
5265                 Event::PaymentSent { ref payment_preimage } => {
5266                         assert_eq!(*payment_preimage, our_payment_preimage);
5267                 }
5268                 _ => panic!("Unexpected event"),
5269         }
5270 }
5271
5272 #[test]
5273 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5274         let chanmon_cfgs = create_chanmon_cfgs(2);
5275         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5276         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5277         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5278
5279         // Create some initial channels
5280         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5281
5282         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5283         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5284         assert_eq!(local_txn.len(), 1);
5285         assert_eq!(local_txn[0].input.len(), 1);
5286         check_spends!(local_txn[0], chan_1.3);
5287
5288         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5289         nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5290         check_added_monitors!(nodes[1], 1);
5291         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5292         connect_block(&nodes[1], &Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5293         check_added_monitors!(nodes[1], 1);
5294         let events = nodes[1].node.get_and_clear_pending_msg_events();
5295         match events[0] {
5296                 MessageSendEvent::UpdateHTLCs { .. } => {},
5297                 _ => panic!("Unexpected event"),
5298         }
5299         match events[1] {
5300                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5301                 _ => panic!("Unexepected event"),
5302         }
5303         let node_txn = {
5304                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5305                 assert_eq!(node_txn.len(), 3);
5306                 assert_eq!(node_txn[0], node_txn[2]);
5307                 assert_eq!(node_txn[1], local_txn[0]);
5308                 assert_eq!(node_txn[0].input.len(), 1);
5309                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5310                 check_spends!(node_txn[0], local_txn[0]);
5311                 vec![node_txn[0].clone()]
5312         };
5313
5314         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5315         connect_block(&nodes[1], &Block { header: header_201, txdata: node_txn.clone() }, 201);
5316         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5317
5318         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5319         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5320         assert_eq!(spend_txn.len(), 1);
5321         check_spends!(spend_txn[0], node_txn[0]);
5322 }
5323
5324 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5325         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5326         // unrevoked commitment transaction.
5327         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5328         // a remote RAA before they could be failed backwards (and combinations thereof).
5329         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5330         // use the same payment hashes.
5331         // Thus, we use a six-node network:
5332         //
5333         // A \         / E
5334         //    - C - D -
5335         // B /         \ F
5336         // And test where C fails back to A/B when D announces its latest commitment transaction
5337         let chanmon_cfgs = create_chanmon_cfgs(6);
5338         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5339         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5340         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5341         let logger = test_utils::TestLogger::new();
5342
5343         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5344         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5345         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5346         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5347         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5348
5349         // Rebalance and check output sanity...
5350         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5351         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5352         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5353
5354         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5355         // 0th HTLC:
5356         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
5357         // 1st HTLC:
5358         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
5359         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5360         let our_node_id = &nodes[1].node.get_our_node_id();
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         // 2nd HTLC:
5363         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
5364         // 3rd HTLC:
5365         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
5366         // 4th HTLC:
5367         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5368         // 5th HTLC:
5369         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5370         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5371         // 6th HTLC:
5372         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5373         // 7th HTLC:
5374         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5375
5376         // 8th HTLC:
5377         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5378         // 9th HTLC:
5379         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5380         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
5381
5382         // 10th HTLC:
5383         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
5384         // 11th HTLC:
5385         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();
5386         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5387
5388         // Double-check that six of the new HTLC were added
5389         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5390         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5391         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5392         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5393
5394         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5395         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5396         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5397         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5398         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5399         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5400         check_added_monitors!(nodes[4], 0);
5401         expect_pending_htlcs_forwardable!(nodes[4]);
5402         check_added_monitors!(nodes[4], 1);
5403
5404         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5405         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5406         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5407         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5408         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5409         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5410
5411         // Fail 3rd below-dust and 7th above-dust HTLCs
5412         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5413         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5414         check_added_monitors!(nodes[5], 0);
5415         expect_pending_htlcs_forwardable!(nodes[5]);
5416         check_added_monitors!(nodes[5], 1);
5417
5418         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5419         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5420         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5421         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5422
5423         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5424
5425         expect_pending_htlcs_forwardable!(nodes[3]);
5426         check_added_monitors!(nodes[3], 1);
5427         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5428         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5429         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5430         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5431         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5432         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5433         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5434         if deliver_last_raa {
5435                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5436         } else {
5437                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5438         }
5439
5440         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5441         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5442         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5443         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5444         //
5445         // We now broadcast the latest commitment transaction, which *should* result in failures for
5446         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5447         // the non-broadcast above-dust HTLCs.
5448         //
5449         // Alternatively, we may broadcast the previous commitment transaction, which should only
5450         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5451         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5452
5453         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5454         if announce_latest {
5455                 connect_block(&nodes[2], &Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5456         } else {
5457                 connect_block(&nodes[2], &Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5458         }
5459         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1, 1, true,  header.block_hash());
5460         check_closed_broadcast!(nodes[2], false);
5461         expect_pending_htlcs_forwardable!(nodes[2]);
5462         check_added_monitors!(nodes[2], 3);
5463
5464         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5465         assert_eq!(cs_msgs.len(), 2);
5466         let mut a_done = false;
5467         for msg in cs_msgs {
5468                 match msg {
5469                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5470                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5471                                 // should be failed-backwards here.
5472                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5473                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5474                                         for htlc in &updates.update_fail_htlcs {
5475                                                 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 });
5476                                         }
5477                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5478                                         assert!(!a_done);
5479                                         a_done = true;
5480                                         &nodes[0]
5481                                 } else {
5482                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5483                                         for htlc in &updates.update_fail_htlcs {
5484                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5485                                         }
5486                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5487                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5488                                         &nodes[1]
5489                                 };
5490                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5491                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5492                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5493                                 if announce_latest {
5494                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5495                                         if *node_id == nodes[0].node.get_our_node_id() {
5496                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5497                                         }
5498                                 }
5499                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5500                         },
5501                         _ => panic!("Unexpected event"),
5502                 }
5503         }
5504
5505         let as_events = nodes[0].node.get_and_clear_pending_events();
5506         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5507         let mut as_failds = HashSet::new();
5508         for event in as_events.iter() {
5509                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5510                         assert!(as_failds.insert(*payment_hash));
5511                         if *payment_hash != payment_hash_2 {
5512                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5513                         } else {
5514                                 assert!(!rejected_by_dest);
5515                         }
5516                 } else { panic!("Unexpected event"); }
5517         }
5518         assert!(as_failds.contains(&payment_hash_1));
5519         assert!(as_failds.contains(&payment_hash_2));
5520         if announce_latest {
5521                 assert!(as_failds.contains(&payment_hash_3));
5522                 assert!(as_failds.contains(&payment_hash_5));
5523         }
5524         assert!(as_failds.contains(&payment_hash_6));
5525
5526         let bs_events = nodes[1].node.get_and_clear_pending_events();
5527         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5528         let mut bs_failds = HashSet::new();
5529         for event in bs_events.iter() {
5530                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5531                         assert!(bs_failds.insert(*payment_hash));
5532                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5533                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5534                         } else {
5535                                 assert!(!rejected_by_dest);
5536                         }
5537                 } else { panic!("Unexpected event"); }
5538         }
5539         assert!(bs_failds.contains(&payment_hash_1));
5540         assert!(bs_failds.contains(&payment_hash_2));
5541         if announce_latest {
5542                 assert!(bs_failds.contains(&payment_hash_4));
5543         }
5544         assert!(bs_failds.contains(&payment_hash_5));
5545
5546         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5547         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5548         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5549         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5550         // PaymentFailureNetworkUpdates.
5551         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5552         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5553         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5554         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5555         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5556                 match event {
5557                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5558                         _ => panic!("Unexpected event"),
5559                 }
5560         }
5561 }
5562
5563 #[test]
5564 fn test_fail_backwards_latest_remote_announce_a() {
5565         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5566 }
5567
5568 #[test]
5569 fn test_fail_backwards_latest_remote_announce_b() {
5570         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5571 }
5572
5573 #[test]
5574 fn test_fail_backwards_previous_remote_announce() {
5575         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5576         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5577         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5578 }
5579
5580 #[test]
5581 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5582         let chanmon_cfgs = create_chanmon_cfgs(2);
5583         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5584         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5585         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5586
5587         // Create some initial channels
5588         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5589
5590         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5591         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5592         assert_eq!(local_txn[0].input.len(), 1);
5593         check_spends!(local_txn[0], chan_1.3);
5594
5595         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5596         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5597         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5598         check_closed_broadcast!(nodes[0], false);
5599         check_added_monitors!(nodes[0], 1);
5600
5601         let htlc_timeout = {
5602                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5603                 assert_eq!(node_txn[0].input.len(), 1);
5604                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5605                 check_spends!(node_txn[0], local_txn[0]);
5606                 node_txn[0].clone()
5607         };
5608
5609         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5610         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5611         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5612         expect_payment_failed!(nodes[0], our_payment_hash, true);
5613
5614         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5615         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5616         assert_eq!(spend_txn.len(), 3);
5617         check_spends!(spend_txn[0], local_txn[0]);
5618         check_spends!(spend_txn[1], htlc_timeout);
5619         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5620 }
5621
5622 #[test]
5623 fn test_key_derivation_params() {
5624         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5625         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5626         // let us re-derive the channel key set to then derive a delayed_payment_key.
5627
5628         let chanmon_cfgs = create_chanmon_cfgs(3);
5629
5630         // We manually create the node configuration to backup the seed.
5631         let seed = [42; 32];
5632         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5633         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);
5634         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 };
5635         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5636         node_cfgs.remove(0);
5637         node_cfgs.insert(0, node);
5638
5639         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5640         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5641
5642         // Create some initial channels
5643         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5644         // for node 0
5645         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5646         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5647         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5648
5649         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5650         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5651         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5652         assert_eq!(local_txn_1[0].input.len(), 1);
5653         check_spends!(local_txn_1[0], chan_1.3);
5654
5655         // We check funding pubkey are unique
5656         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]));
5657         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]));
5658         if from_0_funding_key_0 == from_1_funding_key_0
5659             || from_0_funding_key_0 == from_1_funding_key_1
5660             || from_0_funding_key_1 == from_1_funding_key_0
5661             || from_0_funding_key_1 == from_1_funding_key_1 {
5662                 panic!("Funding pubkeys aren't unique");
5663         }
5664
5665         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5666         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5667         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn_1[0].clone()] }, 200);
5668         check_closed_broadcast!(nodes[0], false);
5669         check_added_monitors!(nodes[0], 1);
5670
5671         let htlc_timeout = {
5672                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5673                 assert_eq!(node_txn[0].input.len(), 1);
5674                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5675                 check_spends!(node_txn[0], local_txn_1[0]);
5676                 node_txn[0].clone()
5677         };
5678
5679         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5680         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5681         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5682         expect_payment_failed!(nodes[0], our_payment_hash, true);
5683
5684         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5685         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5686         let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5687         assert_eq!(spend_txn.len(), 3);
5688         check_spends!(spend_txn[0], local_txn_1[0]);
5689         check_spends!(spend_txn[1], htlc_timeout);
5690         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5691 }
5692
5693 #[test]
5694 fn test_static_output_closing_tx() {
5695         let chanmon_cfgs = create_chanmon_cfgs(2);
5696         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5697         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5698         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5699
5700         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5701
5702         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5703         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5704
5705         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5706         connect_block(&nodes[0], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5707         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5708
5709         let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5710         assert_eq!(spend_txn.len(), 1);
5711         check_spends!(spend_txn[0], closing_tx);
5712
5713         connect_block(&nodes[1], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5714         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5715
5716         let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5717         assert_eq!(spend_txn.len(), 1);
5718         check_spends!(spend_txn[0], closing_tx);
5719 }
5720
5721 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5722         let chanmon_cfgs = create_chanmon_cfgs(2);
5723         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5724         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5725         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5726         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5727
5728         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5729
5730         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5731         // present in B's local commitment transaction, but none of A's commitment transactions.
5732         assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5733         check_added_monitors!(nodes[1], 1);
5734
5735         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5736         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5737         let events = nodes[0].node.get_and_clear_pending_events();
5738         assert_eq!(events.len(), 1);
5739         match events[0] {
5740                 Event::PaymentSent { payment_preimage } => {
5741                         assert_eq!(payment_preimage, our_payment_preimage);
5742                 },
5743                 _ => panic!("Unexpected event"),
5744         }
5745
5746         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5747         check_added_monitors!(nodes[0], 1);
5748         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5749         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5750         check_added_monitors!(nodes[1], 1);
5751
5752         let mut block = Block {
5753                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5754                 txdata: vec![],
5755         };
5756         for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5757                 connect_block(&nodes[1], &block, i);
5758                 block.header.prev_blockhash = block.block_hash();
5759         }
5760         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5761         check_closed_broadcast!(nodes[1], false);
5762         check_added_monitors!(nodes[1], 1);
5763 }
5764
5765 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5766         let chanmon_cfgs = create_chanmon_cfgs(2);
5767         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5768         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5769         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5770         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5771         let logger = test_utils::TestLogger::new();
5772
5773         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5774         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5775         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();
5776         nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5777         check_added_monitors!(nodes[0], 1);
5778
5779         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5780
5781         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5782         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5783         // to "time out" the HTLC.
5784
5785         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5786
5787         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5788                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()}, i);
5789                 header.prev_blockhash = header.block_hash();
5790         }
5791         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5792         check_closed_broadcast!(nodes[0], false);
5793         check_added_monitors!(nodes[0], 1);
5794 }
5795
5796 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5797         let chanmon_cfgs = create_chanmon_cfgs(3);
5798         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5799         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5800         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5801         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5802
5803         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5804         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5805         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5806         // actually revoked.
5807         let htlc_value = if use_dust { 50000 } else { 3000000 };
5808         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5809         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5810         expect_pending_htlcs_forwardable!(nodes[1]);
5811         check_added_monitors!(nodes[1], 1);
5812
5813         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5814         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5815         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5816         check_added_monitors!(nodes[0], 1);
5817         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5818         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5819         check_added_monitors!(nodes[1], 1);
5820         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5821         check_added_monitors!(nodes[1], 1);
5822         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5823
5824         if check_revoke_no_close {
5825                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5826                 check_added_monitors!(nodes[0], 1);
5827         }
5828
5829         let mut block = Block {
5830                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5831                 txdata: vec![],
5832         };
5833         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5834                 connect_block(&nodes[0], &block, i);
5835                 block.header.prev_blockhash = block.block_hash();
5836         }
5837         if !check_revoke_no_close {
5838                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5839                 check_closed_broadcast!(nodes[0], false);
5840                 check_added_monitors!(nodes[0], 1);
5841         } else {
5842                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5843         }
5844 }
5845
5846 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5847 // There are only a few cases to test here:
5848 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5849 //    broadcastable commitment transactions result in channel closure,
5850 //  * its included in an unrevoked-but-previous remote commitment transaction,
5851 //  * its included in the latest remote or local commitment transactions.
5852 // We test each of the three possible commitment transactions individually and use both dust and
5853 // non-dust HTLCs.
5854 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5855 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5856 // tested for at least one of the cases in other tests.
5857 #[test]
5858 fn htlc_claim_single_commitment_only_a() {
5859         do_htlc_claim_local_commitment_only(true);
5860         do_htlc_claim_local_commitment_only(false);
5861
5862         do_htlc_claim_current_remote_commitment_only(true);
5863         do_htlc_claim_current_remote_commitment_only(false);
5864 }
5865
5866 #[test]
5867 fn htlc_claim_single_commitment_only_b() {
5868         do_htlc_claim_previous_remote_commitment_only(true, false);
5869         do_htlc_claim_previous_remote_commitment_only(false, false);
5870         do_htlc_claim_previous_remote_commitment_only(true, true);
5871         do_htlc_claim_previous_remote_commitment_only(false, true);
5872 }
5873
5874 #[test]
5875 #[should_panic]
5876 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5877         let chanmon_cfgs = create_chanmon_cfgs(2);
5878         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5879         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5880         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5881         //Force duplicate channel ids
5882         for node in nodes.iter() {
5883                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5884         }
5885
5886         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5887         let channel_value_satoshis=10000;
5888         let push_msat=10001;
5889         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5890         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5891         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5892
5893         //Create a second channel with a channel_id collision
5894         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5895 }
5896
5897 #[test]
5898 fn bolt2_open_channel_sending_node_checks_part2() {
5899         let chanmon_cfgs = create_chanmon_cfgs(2);
5900         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5901         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5902         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5903
5904         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5905         let channel_value_satoshis=2^24;
5906         let push_msat=10001;
5907         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5908
5909         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5910         let channel_value_satoshis=10000;
5911         // Test when push_msat is equal to 1000 * funding_satoshis.
5912         let push_msat=1000*channel_value_satoshis+1;
5913         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5914
5915         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5916         let channel_value_satoshis=10000;
5917         let push_msat=10001;
5918         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
5919         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5920         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5921
5922         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5923         // 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
5924         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5925
5926         // 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.
5927         assert!(BREAKDOWN_TIMEOUT>0);
5928         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5929
5930         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5931         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5932         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5933
5934         // 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.
5935         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5936         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5937         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5938         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5939         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5940 }
5941
5942 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5943 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5944 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5945 // is no longer affordable once it's freed.
5946 #[test]
5947 fn test_fail_holding_cell_htlc_upon_free() {
5948         let chanmon_cfgs = create_chanmon_cfgs(2);
5949         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5950         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5951         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5952         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5953         let logger = test_utils::TestLogger::new();
5954
5955         // First nodes[0] generates an update_fee, setting the channel's
5956         // pending_update_fee.
5957         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
5958         check_added_monitors!(nodes[0], 1);
5959
5960         let events = nodes[0].node.get_and_clear_pending_msg_events();
5961         assert_eq!(events.len(), 1);
5962         let (update_msg, commitment_signed) = match events[0] {
5963                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5964                         (update_fee.as_ref(), commitment_signed)
5965                 },
5966                 _ => panic!("Unexpected event"),
5967         };
5968
5969         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5970
5971         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5972         let channel_reserve = chan_stat.channel_reserve_msat;
5973         let feerate = get_feerate!(nodes[0], chan.2);
5974
5975         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5976         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5977         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5978         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5979         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();
5980
5981         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5982         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5983         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5984         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5985
5986         // Flush the pending fee update.
5987         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5988         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5989         check_added_monitors!(nodes[1], 1);
5990         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5991         check_added_monitors!(nodes[0], 1);
5992
5993         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5994         // HTLC, but now that the fee has been raised the payment will now fail, causing
5995         // us to surface its failure to the user.
5996         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5997         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5998         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
5999         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);
6000         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6001
6002         // Check that the payment failed to be sent out.
6003         let events = nodes[0].node.get_and_clear_pending_events();
6004         assert_eq!(events.len(), 1);
6005         match &events[0] {
6006                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6007                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6008                         assert_eq!(*rejected_by_dest, false);
6009                         assert_eq!(*error_code, None);
6010                         assert_eq!(*error_data, None);
6011                 },
6012                 _ => panic!("Unexpected event"),
6013         }
6014 }
6015
6016 // Test that if multiple HTLCs are released from the holding cell and one is
6017 // valid but the other is no longer valid upon release, the valid HTLC can be
6018 // successfully completed while the other one fails as expected.
6019 #[test]
6020 fn test_free_and_fail_holding_cell_htlcs() {
6021         let chanmon_cfgs = create_chanmon_cfgs(2);
6022         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6023         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6024         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6025         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6026         let logger = test_utils::TestLogger::new();
6027
6028         // First nodes[0] generates an update_fee, setting the channel's
6029         // pending_update_fee.
6030         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6031         check_added_monitors!(nodes[0], 1);
6032
6033         let events = nodes[0].node.get_and_clear_pending_msg_events();
6034         assert_eq!(events.len(), 1);
6035         let (update_msg, commitment_signed) = match events[0] {
6036                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6037                         (update_fee.as_ref(), commitment_signed)
6038                 },
6039                 _ => panic!("Unexpected event"),
6040         };
6041
6042         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6043
6044         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6045         let channel_reserve = chan_stat.channel_reserve_msat;
6046         let feerate = get_feerate!(nodes[0], chan.2);
6047
6048         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6049         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6050         let amt_1 = 20000;
6051         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6052         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6053         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6054         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();
6055         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();
6056
6057         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6058         nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6059         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6060         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6061         nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6062         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6063         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6064
6065         // Flush the pending fee update.
6066         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6067         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6068         check_added_monitors!(nodes[1], 1);
6069         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6070         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6071         check_added_monitors!(nodes[0], 2);
6072
6073         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6074         // but now that the fee has been raised the second payment will now fail, causing us
6075         // to surface its failure to the user. The first payment should succeed.
6076         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6077         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6078         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6079         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);
6080         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6081
6082         // Check that the second payment failed to be sent out.
6083         let events = nodes[0].node.get_and_clear_pending_events();
6084         assert_eq!(events.len(), 1);
6085         match &events[0] {
6086                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6087                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6088                         assert_eq!(*rejected_by_dest, false);
6089                         assert_eq!(*error_code, None);
6090                         assert_eq!(*error_data, None);
6091                 },
6092                 _ => panic!("Unexpected event"),
6093         }
6094
6095         // Complete the first payment and the RAA from the fee update.
6096         let (payment_event, send_raa_event) = {
6097                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6098                 assert_eq!(msgs.len(), 2);
6099                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6100         };
6101         let raa = match send_raa_event {
6102                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6103                 _ => panic!("Unexpected event"),
6104         };
6105         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6106         check_added_monitors!(nodes[1], 1);
6107         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6108         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6109         let events = nodes[1].node.get_and_clear_pending_events();
6110         assert_eq!(events.len(), 1);
6111         match events[0] {
6112                 Event::PendingHTLCsForwardable { .. } => {},
6113                 _ => panic!("Unexpected event"),
6114         }
6115         nodes[1].node.process_pending_htlc_forwards();
6116         let events = nodes[1].node.get_and_clear_pending_events();
6117         assert_eq!(events.len(), 1);
6118         match events[0] {
6119                 Event::PaymentReceived { .. } => {},
6120                 _ => panic!("Unexpected event"),
6121         }
6122         nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6123         check_added_monitors!(nodes[1], 1);
6124         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6125         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6126         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6127         let events = nodes[0].node.get_and_clear_pending_events();
6128         assert_eq!(events.len(), 1);
6129         match events[0] {
6130                 Event::PaymentSent { ref payment_preimage } => {
6131                         assert_eq!(*payment_preimage, payment_preimage_1);
6132                 }
6133                 _ => panic!("Unexpected event"),
6134         }
6135 }
6136
6137 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6138 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6139 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6140 // once it's freed.
6141 #[test]
6142 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6143         let chanmon_cfgs = create_chanmon_cfgs(3);
6144         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6145         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6146         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6147         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6148         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6149         let logger = test_utils::TestLogger::new();
6150
6151         // First nodes[1] generates an update_fee, setting the channel's
6152         // pending_update_fee.
6153         nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6154         check_added_monitors!(nodes[1], 1);
6155
6156         let events = nodes[1].node.get_and_clear_pending_msg_events();
6157         assert_eq!(events.len(), 1);
6158         let (update_msg, commitment_signed) = match events[0] {
6159                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6160                         (update_fee.as_ref(), commitment_signed)
6161                 },
6162                 _ => panic!("Unexpected event"),
6163         };
6164
6165         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6166
6167         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6168         let channel_reserve = chan_stat.channel_reserve_msat;
6169         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6170
6171         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6172         let feemsat = 239;
6173         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6174         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6175         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6176         let payment_event = {
6177                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6178                 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();
6179                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6180                 check_added_monitors!(nodes[0], 1);
6181
6182                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6183                 assert_eq!(events.len(), 1);
6184
6185                 SendEvent::from_event(events.remove(0))
6186         };
6187         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6188         check_added_monitors!(nodes[1], 0);
6189         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6190         expect_pending_htlcs_forwardable!(nodes[1]);
6191
6192         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6193         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6194
6195         // Flush the pending fee update.
6196         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6197         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6198         check_added_monitors!(nodes[2], 1);
6199         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6200         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6201         check_added_monitors!(nodes[1], 2);
6202
6203         // A final RAA message is generated to finalize the fee update.
6204         let events = nodes[1].node.get_and_clear_pending_msg_events();
6205         assert_eq!(events.len(), 1);
6206
6207         let raa_msg = match &events[0] {
6208                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6209                         msg.clone()
6210                 },
6211                 _ => panic!("Unexpected event"),
6212         };
6213
6214         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6215         check_added_monitors!(nodes[2], 1);
6216         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6217
6218         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6219         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6220         assert_eq!(process_htlc_forwards_event.len(), 1);
6221         match &process_htlc_forwards_event[0] {
6222                 &Event::PendingHTLCsForwardable { .. } => {},
6223                 _ => panic!("Unexpected event"),
6224         }
6225
6226         // In response, we call ChannelManager's process_pending_htlc_forwards
6227         nodes[1].node.process_pending_htlc_forwards();
6228         check_added_monitors!(nodes[1], 1);
6229
6230         // This causes the HTLC to be failed backwards.
6231         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6232         assert_eq!(fail_event.len(), 1);
6233         let (fail_msg, commitment_signed) = match &fail_event[0] {
6234                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6235                         assert_eq!(updates.update_add_htlcs.len(), 0);
6236                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6237                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6238                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6239                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6240                 },
6241                 _ => panic!("Unexpected event"),
6242         };
6243
6244         // Pass the failure messages back to nodes[0].
6245         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6246         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6247
6248         // Complete the HTLC failure+removal process.
6249         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6250         check_added_monitors!(nodes[0], 1);
6251         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6252         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6253         check_added_monitors!(nodes[1], 2);
6254         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6255         assert_eq!(final_raa_event.len(), 1);
6256         let raa = match &final_raa_event[0] {
6257                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6258                 _ => panic!("Unexpected event"),
6259         };
6260         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6261         let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6262         assert_eq!(fail_msg_event.len(), 1);
6263         match &fail_msg_event[0] {
6264                 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6265                 _ => panic!("Unexpected event"),
6266         }
6267         let failure_event = nodes[0].node.get_and_clear_pending_events();
6268         assert_eq!(failure_event.len(), 1);
6269         match &failure_event[0] {
6270                 &Event::PaymentFailed { rejected_by_dest, .. } => {
6271                         assert!(!rejected_by_dest);
6272                 },
6273                 _ => panic!("Unexpected event"),
6274         }
6275         check_added_monitors!(nodes[0], 1);
6276 }
6277
6278 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6279 // 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.
6280 //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.
6281
6282 #[test]
6283 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6284         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
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
6291         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
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 = 100;
6296
6297         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6298                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
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 less than their minimum HTLC value".to_string(), 1);
6301 }
6302
6303 #[test]
6304 fn test_update_add_htlc_bolt2_sender_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         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6312
6313         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6314         let logger = test_utils::TestLogger::new();
6315         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();
6316         route.paths[0][0].fee_msat = 0;
6317         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6318                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6319
6320         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6321         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6322 }
6323
6324 #[test]
6325 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6326         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6327         let chanmon_cfgs = create_chanmon_cfgs(2);
6328         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6329         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6330         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6331         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6332
6333         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6334         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6335         let logger = test_utils::TestLogger::new();
6336         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();
6337         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6338         check_added_monitors!(nodes[0], 1);
6339         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6340         updates.update_add_htlcs[0].amount_msat = 0;
6341
6342         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6343         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6344         check_closed_broadcast!(nodes[1], true).unwrap();
6345         check_added_monitors!(nodes[1], 1);
6346 }
6347
6348 #[test]
6349 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6350         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6351         //It is enforced when constructing a route.
6352         let chanmon_cfgs = create_chanmon_cfgs(2);
6353         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6354         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6355         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6356         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6357         let logger = test_utils::TestLogger::new();
6358
6359         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6360
6361         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6362         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();
6363         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6364                 assert_eq!(err, &"Channel CLTV overflowed?"));
6365 }
6366
6367 #[test]
6368 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6369         //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.
6370         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6371         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6372         let chanmon_cfgs = create_chanmon_cfgs(2);
6373         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6374         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6375         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6376         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6377         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6378
6379         let logger = test_utils::TestLogger::new();
6380         for i in 0..max_accepted_htlcs {
6381                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6382                 let payment_event = {
6383                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6384                         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();
6385                         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6386                         check_added_monitors!(nodes[0], 1);
6387
6388                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6389                         assert_eq!(events.len(), 1);
6390                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6391                                 assert_eq!(htlcs[0].htlc_id, i);
6392                         } else {
6393                                 assert!(false);
6394                         }
6395                         SendEvent::from_event(events.remove(0))
6396                 };
6397                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6398                 check_added_monitors!(nodes[1], 0);
6399                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6400
6401                 expect_pending_htlcs_forwardable!(nodes[1]);
6402                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6403         }
6404         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6405         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6406         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();
6407         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6408                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6409
6410         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6411         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6412 }
6413
6414 #[test]
6415 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6416         //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.
6417         let chanmon_cfgs = create_chanmon_cfgs(2);
6418         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6419         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6420         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6421         let channel_value = 100000;
6422         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6423         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6424
6425         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6426
6427         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6428         // Manually create a route over our max in flight (which our router normally automatically
6429         // limits us to.
6430         let route = Route { paths: vec![vec![RouteHop {
6431            pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6432            short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6433            fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6434         }]] };
6435         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6436                 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)));
6437
6438         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6439         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);
6440
6441         send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6442 }
6443
6444 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6445 #[test]
6446 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6447         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6448         let chanmon_cfgs = create_chanmon_cfgs(2);
6449         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6450         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6451         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6452         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6453         let htlc_minimum_msat: u64;
6454         {
6455                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6456                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6457                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6458         }
6459
6460         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6461         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6462         let logger = test_utils::TestLogger::new();
6463         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], htlc_minimum_msat, TEST_FINAL_CLTV, &logger).unwrap();
6464         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6465         check_added_monitors!(nodes[0], 1);
6466         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6467         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6468         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6469         assert!(nodes[1].node.list_channels().is_empty());
6470         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6471         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()));
6472         check_added_monitors!(nodes[1], 1);
6473 }
6474
6475 #[test]
6476 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6477         //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
6478         let chanmon_cfgs = create_chanmon_cfgs(2);
6479         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6480         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6481         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6482         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6483         let logger = test_utils::TestLogger::new();
6484
6485         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6486         let channel_reserve = chan_stat.channel_reserve_msat;
6487         let feerate = get_feerate!(nodes[0], chan.2);
6488         // The 2* and +1 are for the fee spike reserve.
6489         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6490
6491         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6492         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6493         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6494         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();
6495         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6496         check_added_monitors!(nodes[0], 1);
6497         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6498
6499         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6500         // at this time channel-initiatee receivers are not required to enforce that senders
6501         // respect the fee_spike_reserve.
6502         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6503         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6504
6505         assert!(nodes[1].node.list_channels().is_empty());
6506         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6507         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6508         check_added_monitors!(nodes[1], 1);
6509 }
6510
6511 #[test]
6512 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6513         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6514         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6515         let chanmon_cfgs = create_chanmon_cfgs(2);
6516         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6517         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6518         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6519         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6520         let logger = test_utils::TestLogger::new();
6521
6522         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6523         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6524
6525         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6526         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();
6527
6528         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6529         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6530         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6531         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6532
6533         let mut msg = msgs::UpdateAddHTLC {
6534                 channel_id: chan.2,
6535                 htlc_id: 0,
6536                 amount_msat: 1000,
6537                 payment_hash: our_payment_hash,
6538                 cltv_expiry: htlc_cltv,
6539                 onion_routing_packet: onion_packet.clone(),
6540         };
6541
6542         for i in 0..super::channel::OUR_MAX_HTLCS {
6543                 msg.htlc_id = i as u64;
6544                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6545         }
6546         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6547         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6548
6549         assert!(nodes[1].node.list_channels().is_empty());
6550         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6551         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6552         check_added_monitors!(nodes[1], 1);
6553 }
6554
6555 #[test]
6556 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6557         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6558         let chanmon_cfgs = create_chanmon_cfgs(2);
6559         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6560         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6561         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6562         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6563         let logger = test_utils::TestLogger::new();
6564
6565         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6566         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6567         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();
6568         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6569         check_added_monitors!(nodes[0], 1);
6570         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6571         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6572         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6573
6574         assert!(nodes[1].node.list_channels().is_empty());
6575         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6576         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6577         check_added_monitors!(nodes[1], 1);
6578 }
6579
6580 #[test]
6581 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6582         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6583         let chanmon_cfgs = create_chanmon_cfgs(2);
6584         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6585         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6586         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6587         let logger = test_utils::TestLogger::new();
6588
6589         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6590         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6591         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6592         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();
6593         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6594         check_added_monitors!(nodes[0], 1);
6595         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6596         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6597         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6598
6599         assert!(nodes[1].node.list_channels().is_empty());
6600         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6601         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6602         check_added_monitors!(nodes[1], 1);
6603 }
6604
6605 #[test]
6606 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6607         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6608         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6609         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6610         let chanmon_cfgs = create_chanmon_cfgs(2);
6611         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6612         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6613         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6614         let logger = test_utils::TestLogger::new();
6615
6616         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6617         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6618         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6619         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();
6620         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6621         check_added_monitors!(nodes[0], 1);
6622         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6623         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6624
6625         //Disconnect and Reconnect
6626         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6627         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6628         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6629         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6630         assert_eq!(reestablish_1.len(), 1);
6631         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6632         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6633         assert_eq!(reestablish_2.len(), 1);
6634         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6635         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6636         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6637         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6638
6639         //Resend HTLC
6640         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6641         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6642         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6643         check_added_monitors!(nodes[1], 1);
6644         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6645
6646         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6647
6648         assert!(nodes[1].node.list_channels().is_empty());
6649         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6650         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6651         check_added_monitors!(nodes[1], 1);
6652 }
6653
6654 #[test]
6655 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6656         //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.
6657
6658         let chanmon_cfgs = create_chanmon_cfgs(2);
6659         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6660         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6661         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6662         let logger = test_utils::TestLogger::new();
6663         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6664         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6665         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6666         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();
6667         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6668
6669         check_added_monitors!(nodes[0], 1);
6670         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6671         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6672
6673         let update_msg = msgs::UpdateFulfillHTLC{
6674                 channel_id: chan.2,
6675                 htlc_id: 0,
6676                 payment_preimage: our_payment_preimage,
6677         };
6678
6679         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6680
6681         assert!(nodes[0].node.list_channels().is_empty());
6682         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6683         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()));
6684         check_added_monitors!(nodes[0], 1);
6685 }
6686
6687 #[test]
6688 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6689         //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.
6690
6691         let chanmon_cfgs = create_chanmon_cfgs(2);
6692         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6693         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6694         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6695         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6696         let logger = test_utils::TestLogger::new();
6697
6698         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6699         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6700         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();
6701         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6702         check_added_monitors!(nodes[0], 1);
6703         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6704         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6705
6706         let update_msg = msgs::UpdateFailHTLC{
6707                 channel_id: chan.2,
6708                 htlc_id: 0,
6709                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6710         };
6711
6712         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6713
6714         assert!(nodes[0].node.list_channels().is_empty());
6715         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6716         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()));
6717         check_added_monitors!(nodes[0], 1);
6718 }
6719
6720 #[test]
6721 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6722         //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.
6723
6724         let chanmon_cfgs = create_chanmon_cfgs(2);
6725         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6726         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6727         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6728         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6729         let logger = test_utils::TestLogger::new();
6730
6731         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6732         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6733         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();
6734         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6735         check_added_monitors!(nodes[0], 1);
6736         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6737         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6738         let update_msg = msgs::UpdateFailMalformedHTLC{
6739                 channel_id: chan.2,
6740                 htlc_id: 0,
6741                 sha256_of_onion: [1; 32],
6742                 failure_code: 0x8000,
6743         };
6744
6745         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6746
6747         assert!(nodes[0].node.list_channels().is_empty());
6748         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6749         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()));
6750         check_added_monitors!(nodes[0], 1);
6751 }
6752
6753 #[test]
6754 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6755         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6756
6757         let chanmon_cfgs = create_chanmon_cfgs(2);
6758         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6759         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6760         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6761         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6762
6763         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6764
6765         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6766         check_added_monitors!(nodes[1], 1);
6767
6768         let events = nodes[1].node.get_and_clear_pending_msg_events();
6769         assert_eq!(events.len(), 1);
6770         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6771                 match events[0] {
6772                         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, .. } } => {
6773                                 assert!(update_add_htlcs.is_empty());
6774                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6775                                 assert!(update_fail_htlcs.is_empty());
6776                                 assert!(update_fail_malformed_htlcs.is_empty());
6777                                 assert!(update_fee.is_none());
6778                                 update_fulfill_htlcs[0].clone()
6779                         },
6780                         _ => panic!("Unexpected event"),
6781                 }
6782         };
6783
6784         update_fulfill_msg.htlc_id = 1;
6785
6786         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6787
6788         assert!(nodes[0].node.list_channels().is_empty());
6789         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6790         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6791         check_added_monitors!(nodes[0], 1);
6792 }
6793
6794 #[test]
6795 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6796         //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.
6797
6798         let chanmon_cfgs = create_chanmon_cfgs(2);
6799         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6800         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6801         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6802         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6803
6804         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6805
6806         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6807         check_added_monitors!(nodes[1], 1);
6808
6809         let events = nodes[1].node.get_and_clear_pending_msg_events();
6810         assert_eq!(events.len(), 1);
6811         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6812                 match events[0] {
6813                         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, .. } } => {
6814                                 assert!(update_add_htlcs.is_empty());
6815                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6816                                 assert!(update_fail_htlcs.is_empty());
6817                                 assert!(update_fail_malformed_htlcs.is_empty());
6818                                 assert!(update_fee.is_none());
6819                                 update_fulfill_htlcs[0].clone()
6820                         },
6821                         _ => panic!("Unexpected event"),
6822                 }
6823         };
6824
6825         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6826
6827         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6828
6829         assert!(nodes[0].node.list_channels().is_empty());
6830         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6831         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6832         check_added_monitors!(nodes[0], 1);
6833 }
6834
6835 #[test]
6836 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6837         //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.
6838
6839         let chanmon_cfgs = create_chanmon_cfgs(2);
6840         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6841         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6842         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6843         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6844         let logger = test_utils::TestLogger::new();
6845
6846         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6847         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6848         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();
6849         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6850         check_added_monitors!(nodes[0], 1);
6851
6852         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6853         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6854
6855         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6856         check_added_monitors!(nodes[1], 0);
6857         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6858
6859         let events = nodes[1].node.get_and_clear_pending_msg_events();
6860
6861         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6862                 match events[0] {
6863                         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, .. } } => {
6864                                 assert!(update_add_htlcs.is_empty());
6865                                 assert!(update_fulfill_htlcs.is_empty());
6866                                 assert!(update_fail_htlcs.is_empty());
6867                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6868                                 assert!(update_fee.is_none());
6869                                 update_fail_malformed_htlcs[0].clone()
6870                         },
6871                         _ => panic!("Unexpected event"),
6872                 }
6873         };
6874         update_msg.failure_code &= !0x8000;
6875         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6876
6877         assert!(nodes[0].node.list_channels().is_empty());
6878         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6879         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6880         check_added_monitors!(nodes[0], 1);
6881 }
6882
6883 #[test]
6884 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6885         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6886         //    * 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.
6887
6888         let chanmon_cfgs = create_chanmon_cfgs(3);
6889         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6890         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6891         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6892         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6893         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6894         let logger = test_utils::TestLogger::new();
6895
6896         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6897
6898         //First hop
6899         let mut payment_event = {
6900                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6901                 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();
6902                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6903                 check_added_monitors!(nodes[0], 1);
6904                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6905                 assert_eq!(events.len(), 1);
6906                 SendEvent::from_event(events.remove(0))
6907         };
6908         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6909         check_added_monitors!(nodes[1], 0);
6910         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6911         expect_pending_htlcs_forwardable!(nodes[1]);
6912         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6913         assert_eq!(events_2.len(), 1);
6914         check_added_monitors!(nodes[1], 1);
6915         payment_event = SendEvent::from_event(events_2.remove(0));
6916         assert_eq!(payment_event.msgs.len(), 1);
6917
6918         //Second Hop
6919         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6920         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6921         check_added_monitors!(nodes[2], 0);
6922         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6923
6924         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6925         assert_eq!(events_3.len(), 1);
6926         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6927                 match events_3[0] {
6928                         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 } } => {
6929                                 assert!(update_add_htlcs.is_empty());
6930                                 assert!(update_fulfill_htlcs.is_empty());
6931                                 assert!(update_fail_htlcs.is_empty());
6932                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6933                                 assert!(update_fee.is_none());
6934                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6935                         },
6936                         _ => panic!("Unexpected event"),
6937                 }
6938         };
6939
6940         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6941
6942         check_added_monitors!(nodes[1], 0);
6943         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6944         expect_pending_htlcs_forwardable!(nodes[1]);
6945         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6946         assert_eq!(events_4.len(), 1);
6947
6948         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6949         match events_4[0] {
6950                 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, .. } } => {
6951                         assert!(update_add_htlcs.is_empty());
6952                         assert!(update_fulfill_htlcs.is_empty());
6953                         assert_eq!(update_fail_htlcs.len(), 1);
6954                         assert!(update_fail_malformed_htlcs.is_empty());
6955                         assert!(update_fee.is_none());
6956                 },
6957                 _ => panic!("Unexpected event"),
6958         };
6959
6960         check_added_monitors!(nodes[1], 1);
6961 }
6962
6963 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6964         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6965         // 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
6966         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6967
6968         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6969         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6970         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6971         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6972         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6973         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6974
6975         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6976
6977         // We route 2 dust-HTLCs between A and B
6978         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6979         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6980         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6981
6982         // Cache one local commitment tx as previous
6983         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6984
6985         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6986         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
6987         check_added_monitors!(nodes[1], 0);
6988         expect_pending_htlcs_forwardable!(nodes[1]);
6989         check_added_monitors!(nodes[1], 1);
6990
6991         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6992         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6993         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6994         check_added_monitors!(nodes[0], 1);
6995
6996         // Cache one local commitment tx as lastest
6997         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6998
6999         let events = nodes[0].node.get_and_clear_pending_msg_events();
7000         match events[0] {
7001                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7002                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7003                 },
7004                 _ => panic!("Unexpected event"),
7005         }
7006         match events[1] {
7007                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7008                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7009                 },
7010                 _ => panic!("Unexpected event"),
7011         }
7012
7013         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7014         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7015         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7016
7017         if announce_latest {
7018                 connect_block(&nodes[0], &Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
7019         } else {
7020                 connect_block(&nodes[0], &Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
7021         }
7022
7023         check_closed_broadcast!(nodes[0], false);
7024         check_added_monitors!(nodes[0], 1);
7025
7026         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7027         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true,  header.block_hash());
7028         let events = nodes[0].node.get_and_clear_pending_events();
7029         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7030         assert_eq!(events.len(), 2);
7031         let mut first_failed = false;
7032         for event in events {
7033                 match event {
7034                         Event::PaymentFailed { payment_hash, .. } => {
7035                                 if payment_hash == payment_hash_1 {
7036                                         assert!(!first_failed);
7037                                         first_failed = true;
7038                                 } else {
7039                                         assert_eq!(payment_hash, payment_hash_2);
7040                                 }
7041                         }
7042                         _ => panic!("Unexpected event"),
7043                 }
7044         }
7045 }
7046
7047 #[test]
7048 fn test_failure_delay_dust_htlc_local_commitment() {
7049         do_test_failure_delay_dust_htlc_local_commitment(true);
7050         do_test_failure_delay_dust_htlc_local_commitment(false);
7051 }
7052
7053 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7054         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7055         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7056         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7057         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7058         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7059         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7060
7061         let chanmon_cfgs = create_chanmon_cfgs(3);
7062         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7063         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7064         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7065         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7066
7067         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7068
7069         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7070         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7071
7072         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7073         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7074
7075         // We revoked bs_commitment_tx
7076         if revoked {
7077                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7078                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7079         }
7080
7081         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7082         let mut timeout_tx = Vec::new();
7083         if local {
7084                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7085                 connect_block(&nodes[0], &Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
7086                 check_closed_broadcast!(nodes[0], false);
7087                 check_added_monitors!(nodes[0], 1);
7088                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7089                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7090                 let parent_hash  = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7091                 expect_payment_failed!(nodes[0], dust_hash, true);
7092                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7093                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7094                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7095                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7096                 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7097                 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7098                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7099                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7100         } else {
7101                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7102                 connect_block(&nodes[0], &Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
7103                 check_closed_broadcast!(nodes[0], false);
7104                 check_added_monitors!(nodes[0], 1);
7105                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7106                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7107                 let parent_hash  = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7108                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7109                 if !revoked {
7110                         expect_payment_failed!(nodes[0], dust_hash, true);
7111                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7112                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7113                         connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7114                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7115                         let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7116                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7117                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7118                 } else {
7119                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7120                         // commitment tx
7121                         let events = nodes[0].node.get_and_clear_pending_events();
7122                         assert_eq!(events.len(), 2);
7123                         let first;
7124                         match events[0] {
7125                                 Event::PaymentFailed { payment_hash, .. } => {
7126                                         if payment_hash == dust_hash { first = true; }
7127                                         else { first = false; }
7128                                 },
7129                                 _ => panic!("Unexpected event"),
7130                         }
7131                         match events[1] {
7132                                 Event::PaymentFailed { payment_hash, .. } => {
7133                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7134                                         else { assert_eq!(payment_hash, dust_hash); }
7135                                 },
7136                                 _ => panic!("Unexpected event"),
7137                         }
7138                 }
7139         }
7140 }
7141
7142 #[test]
7143 fn test_sweep_outbound_htlc_failure_update() {
7144         do_test_sweep_outbound_htlc_failure_update(false, true);
7145         do_test_sweep_outbound_htlc_failure_update(false, false);
7146         do_test_sweep_outbound_htlc_failure_update(true, false);
7147 }
7148
7149 #[test]
7150 fn test_upfront_shutdown_script() {
7151         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7152         // enforce it at shutdown message
7153
7154         let mut config = UserConfig::default();
7155         config.channel_options.announced_channel = true;
7156         config.peer_channel_config_limits.force_announced_channel_preference = false;
7157         config.channel_options.commit_upfront_shutdown_pubkey = false;
7158         let user_cfgs = [None, Some(config), None];
7159         let chanmon_cfgs = create_chanmon_cfgs(3);
7160         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7161         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7162         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7163
7164         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7165         let flags = InitFeatures::known();
7166         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7167         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7168         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7169         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7170         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
7171         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7172     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()));
7173         check_added_monitors!(nodes[2], 1);
7174
7175         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7176         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7177         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7178         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7179         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7180         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7181         let events = nodes[2].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[0].node.get_our_node_id()) }
7185                 _ => panic!("Unexpected event"),
7186         }
7187
7188         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7189         let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7190         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7191         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7192         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7193         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7194         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
7195         let events = nodes[1].node.get_and_clear_pending_msg_events();
7196         assert_eq!(events.len(), 1);
7197         match events[0] {
7198                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7199                 _ => panic!("Unexpected event"),
7200         }
7201
7202         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7203         // channel smoothly, opt-out is from channel initiator here
7204         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7205         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7206         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7207         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7208         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7209         let events = nodes[0].node.get_and_clear_pending_msg_events();
7210         assert_eq!(events.len(), 1);
7211         match events[0] {
7212                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7213                 _ => panic!("Unexpected event"),
7214         }
7215
7216         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7217         //// channel smoothly
7218         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7219         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7220         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7221         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7222         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7223         let events = nodes[0].node.get_and_clear_pending_msg_events();
7224         assert_eq!(events.len(), 2);
7225         match events[0] {
7226                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7227                 _ => panic!("Unexpected event"),
7228         }
7229         match events[1] {
7230                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7231                 _ => panic!("Unexpected event"),
7232         }
7233 }
7234
7235 #[test]
7236 fn test_upfront_shutdown_script_unsupport_segwit() {
7237         // We test that channel is closed early
7238         // if a segwit program is passed as upfront shutdown script,
7239         // but the peer does not support segwit.
7240         let chanmon_cfgs = create_chanmon_cfgs(2);
7241         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7242         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7243         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7244
7245         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
7246
7247         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7248         open_channel.shutdown_scriptpubkey = Present(Builder::new().push_int(16)
7249                 .push_slice(&[0, 0])
7250                 .into_script());
7251
7252         let features = InitFeatures::known().clear_shutdown_anysegwit();
7253         nodes[0].node.handle_open_channel(&nodes[0].node.get_our_node_id(), features, &open_channel);
7254
7255         let events = nodes[0].node.get_and_clear_pending_msg_events();
7256         assert_eq!(events.len(), 1);
7257         match events[0] {
7258                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7259                         assert_eq!(node_id, nodes[0].node.get_our_node_id());
7260                         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));
7261                 },
7262                 _ => panic!("Unexpected event"),
7263         }
7264 }
7265
7266 #[test]
7267 fn test_shutdown_script_any_segwit_allowed() {
7268         let mut config = UserConfig::default();
7269         config.channel_options.announced_channel = true;
7270         config.peer_channel_config_limits.force_announced_channel_preference = false;
7271         config.channel_options.commit_upfront_shutdown_pubkey = false;
7272         let user_cfgs = [None, Some(config), None];
7273         let chanmon_cfgs = create_chanmon_cfgs(3);
7274         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7275         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7276         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7277
7278         //// We test if the remote peer accepts opt_shutdown_anysegwit, a witness program can be used on shutdown
7279         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7280         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7281         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7282         node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7283                 .push_slice(&[0, 0])
7284                 .into_script();
7285         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7286         let events = nodes[0].node.get_and_clear_pending_msg_events();
7287         assert_eq!(events.len(), 2);
7288         match events[0] {
7289                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7290                 _ => panic!("Unexpected event"),
7291         }
7292         match events[1] {
7293                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7294                 _ => panic!("Unexpected event"),
7295         }
7296 }
7297
7298 #[test]
7299 fn test_shutdown_script_any_segwit_not_allowed() {
7300         let mut config = UserConfig::default();
7301         config.channel_options.announced_channel = true;
7302         config.peer_channel_config_limits.force_announced_channel_preference = false;
7303         config.channel_options.commit_upfront_shutdown_pubkey = false;
7304         let user_cfgs = [None, Some(config), None];
7305         let chanmon_cfgs = create_chanmon_cfgs(3);
7306         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7307         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7308         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7309
7310         //// We test that if the remote peer does not accept opt_shutdown_anysegwit, the witness program cannot be used on shutdown
7311         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7312         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7313         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7314         // Make an any segwit version script
7315         node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7316                 .push_slice(&[0, 0])
7317                 .into_script();
7318         let flags_no = InitFeatures::known().clear_shutdown_anysegwit();
7319         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &flags_no, &node_0_shutdown);
7320         let events = nodes[0].node.get_and_clear_pending_msg_events();
7321         assert_eq!(events.len(), 2);
7322         match events[1] {
7323                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7324                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7325                         assert_eq!(msg.data, "Got a nonstandard scriptpubkey (60020000) from remote peer".to_owned())
7326                 },
7327                 _ => panic!("Unexpected event"),
7328         }
7329         check_added_monitors!(nodes[0], 1);
7330 }
7331
7332 #[test]
7333 fn test_shutdown_script_segwit_but_not_anysegwit() {
7334         let mut config = UserConfig::default();
7335         config.channel_options.announced_channel = true;
7336         config.peer_channel_config_limits.force_announced_channel_preference = false;
7337         config.channel_options.commit_upfront_shutdown_pubkey = false;
7338         let user_cfgs = [None, Some(config), None];
7339         let chanmon_cfgs = create_chanmon_cfgs(3);
7340         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7341         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7342         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7343
7344         //// We test that if shutdown any segwit is supported and we send a witness script with 0 version, this is not accepted
7345         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7346         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7347         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7348         // Make a segwit script that is not a valid as any segwit
7349         node_0_shutdown.scriptpubkey = Builder::new().push_int(0)
7350                 .push_slice(&[0, 0])
7351                 .into_script();
7352         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7353         let events = nodes[0].node.get_and_clear_pending_msg_events();
7354         assert_eq!(events.len(), 2);
7355         match events[1] {
7356                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7357                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7358                         assert_eq!(msg.data, "Got a nonstandard scriptpubkey (00020000) from remote peer".to_owned())
7359                 },
7360                 _ => panic!("Unexpected event"),
7361         }
7362         check_added_monitors!(nodes[0], 1);
7363 }
7364
7365 #[test]
7366 fn test_user_configurable_csv_delay() {
7367         // We test our channel constructors yield errors when we pass them absurd csv delay
7368
7369         let mut low_our_to_self_config = UserConfig::default();
7370         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7371         let mut high_their_to_self_config = UserConfig::default();
7372         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7373         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7374         let chanmon_cfgs = create_chanmon_cfgs(2);
7375         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7376         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7377         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7378
7379         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7380         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) {
7381                 match error {
7382                         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())); },
7383                         _ => panic!("Unexpected event"),
7384                 }
7385         } else { assert!(false) }
7386
7387         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7388         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7389         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7390         open_channel.to_self_delay = 200;
7391         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) {
7392                 match error {
7393                         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()));  },
7394                         _ => panic!("Unexpected event"),
7395                 }
7396         } else { assert!(false); }
7397
7398         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7399         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7400         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()));
7401         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7402         accept_channel.to_self_delay = 200;
7403         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7404         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7405                 match action {
7406                         &ErrorAction::SendErrorMessage { ref msg } => {
7407                                 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()));
7408                         },
7409                         _ => { assert!(false); }
7410                 }
7411         } else { assert!(false); }
7412
7413         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7414         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7415         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7416         open_channel.to_self_delay = 200;
7417         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) {
7418                 match error {
7419                         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())); },
7420                         _ => panic!("Unexpected event"),
7421                 }
7422         } else { assert!(false); }
7423 }
7424
7425 #[test]
7426 fn test_data_loss_protect() {
7427         // We want to be sure that :
7428         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7429         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7430         // * we close channel in case of detecting other being fallen behind
7431         // * we are able to claim our own outputs thanks to to_remote being static
7432         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7433         let persister;
7434         let logger;
7435         let fee_estimator;
7436         let tx_broadcaster;
7437         let chain_source;
7438         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7439         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7440         // during signing due to revoked tx
7441         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7442         let keys_manager = &chanmon_cfgs[0].keys_manager;
7443         let monitor;
7444         let node_state_0;
7445         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7446         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7447         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7448
7449         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7450
7451         // Cache node A state before any channel update
7452         let previous_node_state = nodes[0].node.encode();
7453         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7454         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7455
7456         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7457         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7458
7459         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7460         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7461
7462         // Restore node A from previous state
7463         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7464         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7465         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7466         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7467         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7468         persister = test_utils::TestPersister::new();
7469         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7470         node_state_0 = {
7471                 let mut channel_monitors = HashMap::new();
7472                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7473                 <(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 {
7474                         keys_manager: keys_manager,
7475                         fee_estimator: &fee_estimator,
7476                         chain_monitor: &monitor,
7477                         logger: &logger,
7478                         tx_broadcaster: &tx_broadcaster,
7479                         default_config: UserConfig::default(),
7480                         channel_monitors,
7481                 }).unwrap().1
7482         };
7483         nodes[0].node = &node_state_0;
7484         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7485         nodes[0].chain_monitor = &monitor;
7486         nodes[0].chain_source = &chain_source;
7487
7488         check_added_monitors!(nodes[0], 1);
7489
7490         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7491         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7492
7493         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7494
7495         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7496         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7497         check_added_monitors!(nodes[0], 1);
7498
7499         {
7500                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7501                 assert_eq!(node_txn.len(), 0);
7502         }
7503
7504         let mut reestablish_1 = Vec::with_capacity(1);
7505         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7506                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7507                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7508                         reestablish_1.push(msg.clone());
7509                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7510                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7511                         match action {
7512                                 &ErrorAction::SendErrorMessage { ref msg } => {
7513                                         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");
7514                                 },
7515                                 _ => panic!("Unexpected event!"),
7516                         }
7517                 } else {
7518                         panic!("Unexpected event")
7519                 }
7520         }
7521
7522         // Check we close channel detecting A is fallen-behind
7523         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7524         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7525         check_added_monitors!(nodes[1], 1);
7526
7527
7528         // Check A is able to claim to_remote output
7529         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7530         assert_eq!(node_txn.len(), 1);
7531         check_spends!(node_txn[0], chan.3);
7532         assert_eq!(node_txn[0].output.len(), 2);
7533         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7534         connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7535         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
7536         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 1000000);
7537         assert_eq!(spend_txn.len(), 1);
7538         check_spends!(spend_txn[0], node_txn[0]);
7539 }
7540
7541 #[test]
7542 fn test_check_htlc_underpaying() {
7543         // Send payment through A -> B but A is maliciously
7544         // sending a probe payment (i.e less than expected value0
7545         // to B, B should refuse payment.
7546
7547         let chanmon_cfgs = create_chanmon_cfgs(2);
7548         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7549         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7550         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7551
7552         // Create some initial channels
7553         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7554
7555         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7556
7557         // Node 3 is expecting payment of 100_000 but receive 10_000,
7558         // fail htlc like we didn't know the preimage.
7559         nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7560         nodes[1].node.process_pending_htlc_forwards();
7561
7562         let events = nodes[1].node.get_and_clear_pending_msg_events();
7563         assert_eq!(events.len(), 1);
7564         let (update_fail_htlc, commitment_signed) = match events[0] {
7565                 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 } } => {
7566                         assert!(update_add_htlcs.is_empty());
7567                         assert!(update_fulfill_htlcs.is_empty());
7568                         assert_eq!(update_fail_htlcs.len(), 1);
7569                         assert!(update_fail_malformed_htlcs.is_empty());
7570                         assert!(update_fee.is_none());
7571                         (update_fail_htlcs[0].clone(), commitment_signed)
7572                 },
7573                 _ => panic!("Unexpected event"),
7574         };
7575         check_added_monitors!(nodes[1], 1);
7576
7577         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7578         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7579
7580         // 10_000 msat as u64, followed by a height of 99 as u32
7581         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7582         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7583         expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7584         nodes[1].node.get_and_clear_pending_events();
7585 }
7586
7587 #[test]
7588 fn test_announce_disable_channels() {
7589         // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7590         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7591
7592         let chanmon_cfgs = create_chanmon_cfgs(2);
7593         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7594         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7595         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7596
7597         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7598         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7599         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7600
7601         // Disconnect peers
7602         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7603         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7604
7605         nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7606         nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7607         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7608         assert_eq!(msg_events.len(), 3);
7609         for e in msg_events {
7610                 match e {
7611                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7612                                 let short_id = msg.contents.short_channel_id;
7613                                 // Check generated channel_update match list in PendingChannelUpdate
7614                                 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7615                                         panic!("Generated ChannelUpdate for wrong chan!");
7616                                 }
7617                         },
7618                         _ => panic!("Unexpected event"),
7619                 }
7620         }
7621         // Reconnect peers
7622         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7623         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7624         assert_eq!(reestablish_1.len(), 3);
7625         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7626         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7627         assert_eq!(reestablish_2.len(), 3);
7628
7629         // Reestablish chan_1
7630         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7631         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7632         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7633         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7634         // Reestablish chan_2
7635         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7636         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7637         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7638         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7639         // Reestablish chan_3
7640         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7641         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7642         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7643         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7644
7645         nodes[0].node.timer_chan_freshness_every_min();
7646         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7647 }
7648
7649 #[test]
7650 fn test_bump_penalty_txn_on_revoked_commitment() {
7651         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7652         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7653
7654         let chanmon_cfgs = create_chanmon_cfgs(2);
7655         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7656         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7657         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7658
7659         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7660         let logger = test_utils::TestLogger::new();
7661
7662
7663         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7664         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7665         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();
7666         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7667
7668         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7669         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7670         assert_eq!(revoked_txn[0].output.len(), 4);
7671         assert_eq!(revoked_txn[0].input.len(), 1);
7672         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7673         let revoked_txid = revoked_txn[0].txid();
7674
7675         let mut penalty_sum = 0;
7676         for outp in revoked_txn[0].output.iter() {
7677                 if outp.script_pubkey.is_v0_p2wsh() {
7678                         penalty_sum += outp.value;
7679                 }
7680         }
7681
7682         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7683         let header_114 = connect_blocks(&nodes[1], 114, 0, false, Default::default());
7684
7685         // Actually revoke tx by claiming a HTLC
7686         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7687         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7688         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7689         check_added_monitors!(nodes[1], 1);
7690
7691         // One or more justice tx should have been broadcast, check it
7692         let penalty_1;
7693         let feerate_1;
7694         {
7695                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7696                 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7697                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7698                 assert_eq!(node_txn[0].output.len(), 1);
7699                 check_spends!(node_txn[0], revoked_txn[0]);
7700                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7701                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7702                 penalty_1 = node_txn[0].txid();
7703                 node_txn.clear();
7704         };
7705
7706         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7707         let header = connect_blocks(&nodes[1], 3, 115,  true, header.block_hash());
7708         let mut penalty_2 = penalty_1;
7709         let mut feerate_2 = 0;
7710         {
7711                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7712                 assert_eq!(node_txn.len(), 1);
7713                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7714                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7715                         assert_eq!(node_txn[0].output.len(), 1);
7716                         check_spends!(node_txn[0], revoked_txn[0]);
7717                         penalty_2 = node_txn[0].txid();
7718                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7719                         assert_ne!(penalty_2, penalty_1);
7720                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7721                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7722                         // Verify 25% bump heuristic
7723                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7724                         node_txn.clear();
7725                 }
7726         }
7727         assert_ne!(feerate_2, 0);
7728
7729         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7730         connect_blocks(&nodes[1], 3, 118, true, header);
7731         let penalty_3;
7732         let mut feerate_3 = 0;
7733         {
7734                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7735                 assert_eq!(node_txn.len(), 1);
7736                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7737                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7738                         assert_eq!(node_txn[0].output.len(), 1);
7739                         check_spends!(node_txn[0], revoked_txn[0]);
7740                         penalty_3 = node_txn[0].txid();
7741                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7742                         assert_ne!(penalty_3, penalty_2);
7743                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7744                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7745                         // Verify 25% bump heuristic
7746                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7747                         node_txn.clear();
7748                 }
7749         }
7750         assert_ne!(feerate_3, 0);
7751
7752         nodes[1].node.get_and_clear_pending_events();
7753         nodes[1].node.get_and_clear_pending_msg_events();
7754 }
7755
7756 #[test]
7757 fn test_bump_penalty_txn_on_revoked_htlcs() {
7758         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7759         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7760
7761         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7762         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7763         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7764         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7765         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7766
7767         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7768         // Lock HTLC in both directions
7769         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7770         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7771
7772         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7773         assert_eq!(revoked_local_txn[0].input.len(), 1);
7774         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7775
7776         // Revoke local commitment tx
7777         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7778
7779         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7780         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7781         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7782         check_closed_broadcast!(nodes[1], false);
7783         check_added_monitors!(nodes[1], 1);
7784
7785         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7786         assert_eq!(revoked_htlc_txn.len(), 4);
7787         if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7788                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7789                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7790                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7791                 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7792                 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7793                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7794         } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7795                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7796                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7797                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7798                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7799                 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7800                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7801         }
7802
7803         // Broadcast set of revoked txn on A
7804         let header_128 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7805         connect_block(&nodes[0], &Block { header: header_128, txdata: vec![revoked_local_txn[0].clone()] }, 128);
7806         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7807         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7808         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
7809         let first;
7810         let feerate_1;
7811         let penalty_txn;
7812         {
7813                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7814                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7815                 // Verify claim tx are spending revoked HTLC txn
7816
7817                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7818                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7819                 // which are included in the same block (they are broadcasted because we scan the
7820                 // transactions linearly and generate claims as we go, they likely should be removed in the
7821                 // future).
7822                 assert_eq!(node_txn[0].input.len(), 1);
7823                 check_spends!(node_txn[0], revoked_local_txn[0]);
7824                 assert_eq!(node_txn[1].input.len(), 1);
7825                 check_spends!(node_txn[1], revoked_local_txn[0]);
7826                 assert_eq!(node_txn[2].input.len(), 1);
7827                 check_spends!(node_txn[2], revoked_local_txn[0]);
7828
7829                 // Each of the three justice transactions claim a separate (single) output of the three
7830                 // available, which we check here:
7831                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7832                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7833                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7834
7835                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7836                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7837
7838                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7839                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7840                 // a remote commitment tx has already been confirmed).
7841                 check_spends!(node_txn[3], chan.3);
7842
7843                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7844                 // output, checked above).
7845                 assert_eq!(node_txn[4].input.len(), 2);
7846                 assert_eq!(node_txn[4].output.len(), 1);
7847                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7848
7849                 first = node_txn[4].txid();
7850                 // Store both feerates for later comparison
7851                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7852                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7853                 penalty_txn = vec![node_txn[2].clone()];
7854                 node_txn.clear();
7855         }
7856
7857         // Connect one more block to see if bumped penalty are issued for HTLC txn
7858         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7859         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
7860         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7861         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() }, 131);
7862         {
7863                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7864                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7865
7866                 check_spends!(node_txn[0], revoked_local_txn[0]);
7867                 check_spends!(node_txn[1], revoked_local_txn[0]);
7868                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7869                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7870                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7871                 } else {
7872                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7873                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7874                 }
7875
7876                 node_txn.clear();
7877         };
7878
7879         // Few more blocks to confirm penalty txn
7880         let header_135 = connect_blocks(&nodes[0], 4, 131, true, header_131.block_hash());
7881         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7882         let header_144 = connect_blocks(&nodes[0], 9, 135, true, header_135);
7883         let node_txn = {
7884                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7885                 assert_eq!(node_txn.len(), 1);
7886
7887                 assert_eq!(node_txn[0].input.len(), 2);
7888                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7889                 // Verify bumped tx is different and 25% bump heuristic
7890                 assert_ne!(first, node_txn[0].txid());
7891                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7892                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7893                 assert!(feerate_2 * 100 > feerate_1 * 125);
7894                 let txn = vec![node_txn[0].clone()];
7895                 node_txn.clear();
7896                 txn
7897         };
7898         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7899         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7900         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn }, 145);
7901         connect_blocks(&nodes[0], 20, 145, true, header_145.block_hash());
7902         {
7903                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7904                 // We verify than no new transaction has been broadcast because previously
7905                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7906                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7907                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7908                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7909                 // up bumped justice generation.
7910                 assert_eq!(node_txn.len(), 0);
7911                 node_txn.clear();
7912         }
7913         check_closed_broadcast!(nodes[0], false);
7914         check_added_monitors!(nodes[0], 1);
7915 }
7916
7917 #[test]
7918 fn test_bump_penalty_txn_on_remote_commitment() {
7919         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7920         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7921
7922         // Create 2 HTLCs
7923         // Provide preimage for one
7924         // Check aggregation
7925
7926         let chanmon_cfgs = create_chanmon_cfgs(2);
7927         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7928         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7929         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7930
7931         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7932         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7933         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7934
7935         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7936         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7937         assert_eq!(remote_txn[0].output.len(), 4);
7938         assert_eq!(remote_txn[0].input.len(), 1);
7939         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7940
7941         // Claim a HTLC without revocation (provide B monitor with preimage)
7942         nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7943         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7944         connect_block(&nodes[1], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7945         check_added_monitors!(nodes[1], 2);
7946
7947         // One or more claim tx should have been broadcast, check it
7948         let timeout;
7949         let preimage;
7950         let feerate_timeout;
7951         let feerate_preimage;
7952         {
7953                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7954                 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7955                 assert_eq!(node_txn[0].input.len(), 1);
7956                 assert_eq!(node_txn[1].input.len(), 1);
7957                 check_spends!(node_txn[0], remote_txn[0]);
7958                 check_spends!(node_txn[1], remote_txn[0]);
7959                 check_spends!(node_txn[2], chan.3);
7960                 check_spends!(node_txn[3], node_txn[2]);
7961                 check_spends!(node_txn[4], node_txn[2]);
7962                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7963                         timeout = node_txn[0].txid();
7964                         let index = node_txn[0].input[0].previous_output.vout;
7965                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7966                         feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7967
7968                         preimage = node_txn[1].txid();
7969                         let index = node_txn[1].input[0].previous_output.vout;
7970                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7971                         feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7972                 } else {
7973                         timeout = node_txn[1].txid();
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                         feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7977
7978                         preimage = node_txn[0].txid();
7979                         let index = node_txn[0].input[0].previous_output.vout;
7980                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7981                         feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7982                 }
7983                 node_txn.clear();
7984         };
7985         assert_ne!(feerate_timeout, 0);
7986         assert_ne!(feerate_preimage, 0);
7987
7988         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7989         connect_blocks(&nodes[1], 15, 1,  true, header.block_hash());
7990         {
7991                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7992                 assert_eq!(node_txn.len(), 2);
7993                 assert_eq!(node_txn[0].input.len(), 1);
7994                 assert_eq!(node_txn[1].input.len(), 1);
7995                 check_spends!(node_txn[0], remote_txn[0]);
7996                 check_spends!(node_txn[1], remote_txn[0]);
7997                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7998                         let index = node_txn[0].input[0].previous_output.vout;
7999                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8000                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8001                         assert!(new_feerate * 100 > feerate_timeout * 125);
8002                         assert_ne!(timeout, node_txn[0].txid());
8003
8004                         let index = node_txn[1].input[0].previous_output.vout;
8005                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8006                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
8007                         assert!(new_feerate * 100 > feerate_preimage * 125);
8008                         assert_ne!(preimage, node_txn[1].txid());
8009                 } else {
8010                         let index = node_txn[1].input[0].previous_output.vout;
8011                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8012                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
8013                         assert!(new_feerate * 100 > feerate_timeout * 125);
8014                         assert_ne!(timeout, node_txn[1].txid());
8015
8016                         let index = node_txn[0].input[0].previous_output.vout;
8017                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8018                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8019                         assert!(new_feerate * 100 > feerate_preimage * 125);
8020                         assert_ne!(preimage, node_txn[0].txid());
8021                 }
8022                 node_txn.clear();
8023         }
8024
8025         nodes[1].node.get_and_clear_pending_events();
8026         nodes[1].node.get_and_clear_pending_msg_events();
8027 }
8028
8029 #[test]
8030 fn test_counterparty_raa_skip_no_crash() {
8031         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8032         // commitment transaction, we would have happily carried on and provided them the next
8033         // commitment transaction based on one RAA forward. This would probably eventually have led to
8034         // channel closure, but it would not have resulted in funds loss. Still, our
8035         // EnforcingSigner would have paniced as it doesn't like jumps into the future. Here, we
8036         // check simply that the channel is closed in response to such an RAA, but don't check whether
8037         // we decide to punish our counterparty for revoking their funds (as we don't currently
8038         // implement that).
8039         let chanmon_cfgs = create_chanmon_cfgs(2);
8040         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8041         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8042         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8043         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8044
8045         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8046         let keys = &guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8047         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8048         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8049         // Must revoke without gaps
8050         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8051         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8052                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8053
8054         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8055                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8056         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8057         check_added_monitors!(nodes[1], 1);
8058 }
8059
8060 #[test]
8061 fn test_bump_txn_sanitize_tracking_maps() {
8062         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8063         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8064
8065         let chanmon_cfgs = create_chanmon_cfgs(2);
8066         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8067         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8068         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8069
8070         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8071         // Lock HTLC in both directions
8072         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8073         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8074
8075         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8076         assert_eq!(revoked_local_txn[0].input.len(), 1);
8077         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8078
8079         // Revoke local commitment tx
8080         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8081
8082         // Broadcast set of revoked txn on A
8083         let header_128 = connect_blocks(&nodes[0], 128, 0,  false, Default::default());
8084         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8085
8086         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8087         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
8088         check_closed_broadcast!(nodes[0], false);
8089         check_added_monitors!(nodes[0], 1);
8090         let penalty_txn = {
8091                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8092                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8093                 check_spends!(node_txn[0], revoked_local_txn[0]);
8094                 check_spends!(node_txn[1], revoked_local_txn[0]);
8095                 check_spends!(node_txn[2], revoked_local_txn[0]);
8096                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8097                 node_txn.clear();
8098                 penalty_txn
8099         };
8100         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8101         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
8102         connect_blocks(&nodes[0], 5, 130,  false, header_130.block_hash());
8103         {
8104                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8105                 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8106                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8107                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8108                 }
8109         }
8110 }
8111
8112 #[test]
8113 fn test_override_channel_config() {
8114         let chanmon_cfgs = create_chanmon_cfgs(2);
8115         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8116         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8117         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8118
8119         // Node0 initiates a channel to node1 using the override config.
8120         let mut override_config = UserConfig::default();
8121         override_config.own_channel_config.our_to_self_delay = 200;
8122
8123         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8124
8125         // Assert the channel created by node0 is using the override config.
8126         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8127         assert_eq!(res.channel_flags, 0);
8128         assert_eq!(res.to_self_delay, 200);
8129 }
8130
8131 #[test]
8132 fn test_override_0msat_htlc_minimum() {
8133         let mut zero_config = UserConfig::default();
8134         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8135         let chanmon_cfgs = create_chanmon_cfgs(2);
8136         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8137         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8138         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8139
8140         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8141         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8142         assert_eq!(res.htlc_minimum_msat, 1);
8143
8144         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8145         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8146         assert_eq!(res.htlc_minimum_msat, 1);
8147 }
8148
8149 #[test]
8150 fn test_simple_payment_secret() {
8151         // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8152         // features, however.
8153         let chanmon_cfgs = create_chanmon_cfgs(3);
8154         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8155         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8156         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8157
8158         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8159         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8160         let logger = test_utils::TestLogger::new();
8161
8162         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8163         let payment_secret = PaymentSecret([0xdb; 32]);
8164         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8165         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();
8166         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8167         // Claiming with all the correct values but the wrong secret should result in nothing...
8168         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8169         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8170         // ...but with the right secret we should be able to claim all the way back
8171         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8172 }
8173
8174 #[test]
8175 fn test_simple_mpp() {
8176         // Simple test of sending a multi-path payment.
8177         let chanmon_cfgs = create_chanmon_cfgs(4);
8178         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8179         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8180         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8181
8182         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8183         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8184         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8185         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8186         let logger = test_utils::TestLogger::new();
8187
8188         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8189         let payment_secret = PaymentSecret([0xdb; 32]);
8190         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8191         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();
8192         let path = route.paths[0].clone();
8193         route.paths.push(path);
8194         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8195         route.paths[0][0].short_channel_id = chan_1_id;
8196         route.paths[0][1].short_channel_id = chan_3_id;
8197         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8198         route.paths[1][0].short_channel_id = chan_2_id;
8199         route.paths[1][1].short_channel_id = chan_4_id;
8200         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8201         // Claiming with all the correct values but the wrong secret should result in nothing...
8202         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8203         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8204         // ...but with the right secret we should be able to claim all the way back
8205         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8206 }
8207
8208 #[test]
8209 fn test_update_err_monitor_lockdown() {
8210         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8211         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8212         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8213         //
8214         // This scenario may happen in a watchtower setup, where watchtower process a block height
8215         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8216         // commitment at same time.
8217
8218         let chanmon_cfgs = create_chanmon_cfgs(2);
8219         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8220         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8221         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8222
8223         // Create some initial channel
8224         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8225         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8226
8227         // Rebalance the network to generate htlc in the two directions
8228         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8229
8230         // Route a HTLC from node 0 to node 1 (but don't settle)
8231         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8232
8233         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8234         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8235         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8236         let persister = test_utils::TestPersister::new();
8237         let watchtower = {
8238                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8239                 let monitor = monitors.get(&outpoint).unwrap();
8240                 let mut w = test_utils::TestVecWriter(Vec::new());
8241                 monitor.write(&mut w).unwrap();
8242                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8243                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8244                 assert!(new_monitor == *monitor);
8245                 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);
8246                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8247                 watchtower
8248         };
8249         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8250         watchtower.chain_monitor.block_connected(&header, &[], 200);
8251
8252         // Try to update ChannelMonitor
8253         assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8254         check_added_monitors!(nodes[1], 1);
8255         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8256         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8257         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8258         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8259                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8260                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8261                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8262                 } else { assert!(false); }
8263         } else { assert!(false); };
8264         // Our local monitor is in-sync and hasn't processed yet timeout
8265         check_added_monitors!(nodes[0], 1);
8266         let events = nodes[0].node.get_and_clear_pending_events();
8267         assert_eq!(events.len(), 1);
8268 }
8269
8270 #[test]
8271 fn test_concurrent_monitor_claim() {
8272         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8273         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8274         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8275         // state N+1 confirms. Alice claims output from state N+1.
8276
8277         let chanmon_cfgs = create_chanmon_cfgs(2);
8278         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8279         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8280         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8281
8282         // Create some initial channel
8283         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8284         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8285
8286         // Rebalance the network to generate htlc in the two directions
8287         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8288
8289         // Route a HTLC from node 0 to node 1 (but don't settle)
8290         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8291
8292         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8293         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8294         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8295         let persister = test_utils::TestPersister::new();
8296         let watchtower_alice = {
8297                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8298                 let monitor = monitors.get(&outpoint).unwrap();
8299                 let mut w = test_utils::TestVecWriter(Vec::new());
8300                 monitor.write(&mut w).unwrap();
8301                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8302                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8303                 assert!(new_monitor == *monitor);
8304                 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);
8305                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8306                 watchtower
8307         };
8308         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8309         watchtower_alice.chain_monitor.block_connected(&header, &vec![], 135);
8310
8311         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8312         {
8313                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8314                 assert_eq!(txn.len(), 2);
8315                 txn.clear();
8316         }
8317
8318         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8319         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8320         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8321         let persister = test_utils::TestPersister::new();
8322         let watchtower_bob = {
8323                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8324                 let monitor = monitors.get(&outpoint).unwrap();
8325                 let mut w = test_utils::TestVecWriter(Vec::new());
8326                 monitor.write(&mut w).unwrap();
8327                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8328                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8329                 assert!(new_monitor == *monitor);
8330                 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);
8331                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8332                 watchtower
8333         };
8334         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8335         watchtower_bob.chain_monitor.block_connected(&header, &vec![], 134);
8336
8337         // Route another payment to generate another update with still previous HTLC pending
8338         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8339         {
8340                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8341                 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();
8342                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8343         }
8344         check_added_monitors!(nodes[1], 1);
8345
8346         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8347         assert_eq!(updates.update_add_htlcs.len(), 1);
8348         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8349         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8350                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8351                         // Watchtower Alice should already have seen the block and reject the update
8352                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8353                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8354                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8355                 } else { assert!(false); }
8356         } else { assert!(false); };
8357         // Our local monitor is in-sync and hasn't processed yet timeout
8358         check_added_monitors!(nodes[0], 1);
8359
8360         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8361         watchtower_bob.chain_monitor.block_connected(&header, &vec![], 135);
8362
8363         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8364         let bob_state_y;
8365         {
8366                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8367                 assert_eq!(txn.len(), 2);
8368                 bob_state_y = txn[0].clone();
8369                 txn.clear();
8370         };
8371
8372         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8373         watchtower_alice.chain_monitor.block_connected(&header, &vec![(0, &bob_state_y)], 136);
8374         {
8375                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8376                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8377                 // the onchain detection of the HTLC output
8378                 assert_eq!(htlc_txn.len(), 2);
8379                 check_spends!(htlc_txn[0], bob_state_y);
8380                 check_spends!(htlc_txn[1], bob_state_y);
8381         }
8382 }
8383
8384 #[test]
8385 fn test_pre_lockin_no_chan_closed_update() {
8386         // Test that if a peer closes a channel in response to a funding_created message we don't
8387         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8388         // message).
8389         //
8390         // Doing so would imply a channel monitor update before the initial channel monitor
8391         // registration, violating our API guarantees.
8392         //
8393         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8394         // then opening a second channel with the same funding output as the first (which is not
8395         // rejected because the first channel does not exist in the ChannelManager) and closing it
8396         // before receiving funding_signed.
8397         let chanmon_cfgs = create_chanmon_cfgs(2);
8398         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8399         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8400         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8401
8402         // Create an initial channel
8403         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8404         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8405         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8406         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8407         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8408
8409         // Move the first channel through the funding flow...
8410         let (temporary_channel_id, _tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8411
8412         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8413         check_added_monitors!(nodes[0], 0);
8414
8415         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8416         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8417         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8418         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8419 }
8420
8421 #[test]
8422 fn test_htlc_no_detection() {
8423         // This test is a mutation to underscore the detection logic bug we had
8424         // before #653. HTLC value routed is above the remaining balance, thus
8425         // inverting HTLC and `to_remote` output. HTLC will come second and
8426         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8427         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8428         // outputs order detection for correct spending children filtring.
8429
8430         let chanmon_cfgs = create_chanmon_cfgs(2);
8431         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8432         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8433         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8434
8435         // Create some initial channels
8436         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8437
8438         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000, 1_000_000);
8439         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8440         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8441         assert_eq!(local_txn[0].input.len(), 1);
8442         assert_eq!(local_txn[0].output.len(), 3);
8443         check_spends!(local_txn[0], chan_1.3);
8444
8445         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8446         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8447         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8448         // We deliberately connect the local tx twice as this should provoke a failure calling
8449         // this test before #653 fix.
8450         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8451         check_closed_broadcast!(nodes[0], false);
8452         check_added_monitors!(nodes[0], 1);
8453
8454         let htlc_timeout = {
8455                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8456                 assert_eq!(node_txn[0].input.len(), 1);
8457                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8458                 check_spends!(node_txn[0], local_txn[0]);
8459                 node_txn[0].clone()
8460         };
8461
8462         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8463         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
8464         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
8465         expect_payment_failed!(nodes[0], our_payment_hash, true);
8466 }
8467
8468 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8469         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8470         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8471         // Carol, Alice would be the upstream node, and Carol the downstream.)
8472         //
8473         // Steps of the test:
8474         // 1) Alice sends a HTLC to Carol through Bob.
8475         // 2) Carol doesn't settle the HTLC.
8476         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8477         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8478         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8479         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8480         // 5) Carol release the preimage to Bob off-chain.
8481         // 6) Bob claims the offered output on the broadcasted commitment.
8482         let chanmon_cfgs = create_chanmon_cfgs(3);
8483         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8484         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8485         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8486
8487         // Create some initial channels
8488         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8489         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8490
8491         // Steps (1) and (2):
8492         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8493         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8494
8495         // Check that Alice's commitment transaction now contains an output for this HTLC.
8496         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8497         check_spends!(alice_txn[0], chan_ab.3);
8498         assert_eq!(alice_txn[0].output.len(), 2);
8499         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8500         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8501         assert_eq!(alice_txn.len(), 2);
8502
8503         // Steps (3) and (4):
8504         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8505         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8506         let mut force_closing_node = 0; // Alice force-closes
8507         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8508         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8509         check_closed_broadcast!(nodes[force_closing_node], false);
8510         check_added_monitors!(nodes[force_closing_node], 1);
8511         if go_onchain_before_fulfill {
8512                 let txn_to_broadcast = match broadcast_alice {
8513                         true => alice_txn.clone(),
8514                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8515                 };
8516                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8517                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]}, 1);
8518                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8519                 if broadcast_alice {
8520                         check_closed_broadcast!(nodes[1], false);
8521                         check_added_monitors!(nodes[1], 1);
8522                 }
8523                 assert_eq!(bob_txn.len(), 1);
8524                 check_spends!(bob_txn[0], chan_ab.3);
8525         }
8526
8527         // Step (5):
8528         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8529         // process of removing the HTLC from their commitment transactions.
8530         assert!(nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000));
8531         check_added_monitors!(nodes[2], 1);
8532         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8533         assert!(carol_updates.update_add_htlcs.is_empty());
8534         assert!(carol_updates.update_fail_htlcs.is_empty());
8535         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8536         assert!(carol_updates.update_fee.is_none());
8537         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8538
8539         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8540         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8541         if !go_onchain_before_fulfill && broadcast_alice {
8542                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8543                 assert_eq!(events.len(), 1);
8544                 match events[0] {
8545                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8546                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8547                         },
8548                         _ => panic!("Unexpected event"),
8549                 };
8550         }
8551         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8552         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8553         // Carol<->Bob's updated commitment transaction info.
8554         check_added_monitors!(nodes[1], 2);
8555
8556         let events = nodes[1].node.get_and_clear_pending_msg_events();
8557         assert_eq!(events.len(), 2);
8558         let bob_revocation = match events[0] {
8559                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8560                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8561                         (*msg).clone()
8562                 },
8563                 _ => panic!("Unexpected event"),
8564         };
8565         let bob_updates = match events[1] {
8566                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8567                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8568                         (*updates).clone()
8569                 },
8570                 _ => panic!("Unexpected event"),
8571         };
8572
8573         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8574         check_added_monitors!(nodes[2], 1);
8575         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8576         check_added_monitors!(nodes[2], 1);
8577
8578         let events = nodes[2].node.get_and_clear_pending_msg_events();
8579         assert_eq!(events.len(), 1);
8580         let carol_revocation = match events[0] {
8581                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8582                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8583                         (*msg).clone()
8584                 },
8585                 _ => panic!("Unexpected event"),
8586         };
8587         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8588         check_added_monitors!(nodes[1], 1);
8589
8590         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8591         // here's where we put said channel's commitment tx on-chain.
8592         let mut txn_to_broadcast = alice_txn.clone();
8593         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8594         if !go_onchain_before_fulfill {
8595                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8596                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]}, 1);
8597                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8598                 if broadcast_alice {
8599                         check_closed_broadcast!(nodes[1], false);
8600                         check_added_monitors!(nodes[1], 1);
8601                 }
8602                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8603                 if broadcast_alice {
8604                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8605                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8606                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8607                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8608                         // broadcasted.
8609                         assert_eq!(bob_txn.len(), 3);
8610                         check_spends!(bob_txn[1], chan_ab.3);
8611                 } else {
8612                         assert_eq!(bob_txn.len(), 2);
8613                         check_spends!(bob_txn[0], chan_ab.3);
8614                 }
8615         }
8616
8617         // Step (6):
8618         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8619         // broadcasted commitment transaction.
8620         {
8621                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8622                 if go_onchain_before_fulfill {
8623                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8624                         assert_eq!(bob_txn.len(), 2);
8625                 }
8626                 let script_weight = match broadcast_alice {
8627                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8628                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8629                 };
8630                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8631                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8632                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8633                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8634                 if broadcast_alice && !go_onchain_before_fulfill {
8635                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8636                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8637                 } else {
8638                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8639                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8640                 }
8641         }
8642 }
8643
8644 #[test]
8645 fn test_onchain_htlc_settlement_after_close() {
8646         do_test_onchain_htlc_settlement_after_close(true, true);
8647         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8648         do_test_onchain_htlc_settlement_after_close(true, false);
8649         do_test_onchain_htlc_settlement_after_close(false, false);
8650 }
8651
8652 #[test]
8653 fn test_duplicate_chan_id() {
8654         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8655         // already open we reject it and keep the old channel.
8656         //
8657         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8658         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8659         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8660         // updating logic for the existing channel.
8661         let chanmon_cfgs = create_chanmon_cfgs(2);
8662         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8663         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8664         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8665
8666         // Create an initial channel
8667         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8668         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8669         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8670         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()));
8671
8672         // Try to create a second channel with the same temporary_channel_id as the first and check
8673         // that it is rejected.
8674         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8675         {
8676                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8677                 assert_eq!(events.len(), 1);
8678                 match events[0] {
8679                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8680                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8681                                 // first (valid) and second (invalid) channels are closed, given they both have
8682                                 // the same non-temporary channel_id. However, currently we do not, so we just
8683                                 // move forward with it.
8684                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8685                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8686                         },
8687                         _ => panic!("Unexpected event"),
8688                 }
8689         }
8690
8691         // Move the first channel through the funding flow...
8692         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8693
8694         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8695         check_added_monitors!(nodes[0], 0);
8696
8697         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8698         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8699         {
8700                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8701                 assert_eq!(added_monitors.len(), 1);
8702                 assert_eq!(added_monitors[0].0, funding_output);
8703                 added_monitors.clear();
8704         }
8705         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8706
8707         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8708         let channel_id = funding_outpoint.to_channel_id();
8709
8710         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8711         // temporary one).
8712
8713         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8714         // Technically this is allowed by the spec, but we don't support it and there's little reason
8715         // to. Still, it shouldn't cause any other issues.
8716         open_chan_msg.temporary_channel_id = channel_id;
8717         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8718         {
8719                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8720                 assert_eq!(events.len(), 1);
8721                 match events[0] {
8722                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8723                                 // Technically, at this point, nodes[1] would be justified in thinking both
8724                                 // channels are closed, but currently we do not, so we just move forward with it.
8725                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8726                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8727                         },
8728                         _ => panic!("Unexpected event"),
8729                 }
8730         }
8731
8732         // Now try to create a second channel which has a duplicate funding output.
8733         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8734         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8735         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8736         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()));
8737         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8738
8739         let funding_created = {
8740                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8741                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8742                 let logger = test_utils::TestLogger::new();
8743                 as_chan.get_outbound_funding_created(funding_outpoint, &&logger).unwrap()
8744         };
8745         check_added_monitors!(nodes[0], 0);
8746         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8747         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8748         // still needs to be cleared here.
8749         check_added_monitors!(nodes[1], 1);
8750
8751         // ...still, nodes[1] will reject the duplicate channel.
8752         {
8753                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8754                 assert_eq!(events.len(), 1);
8755                 match events[0] {
8756                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8757                                 // Technically, at this point, nodes[1] would be justified in thinking both
8758                                 // channels are closed, but currently we do not, so we just move forward with it.
8759                                 assert_eq!(msg.channel_id, channel_id);
8760                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8761                         },
8762                         _ => panic!("Unexpected event"),
8763                 }
8764         }
8765
8766         // finally, finish creating the original channel and send a payment over it to make sure
8767         // everything is functional.
8768         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8769         {
8770                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8771                 assert_eq!(added_monitors.len(), 1);
8772                 assert_eq!(added_monitors[0].0, funding_output);
8773                 added_monitors.clear();
8774         }
8775
8776         let events_4 = nodes[0].node.get_and_clear_pending_events();
8777         assert_eq!(events_4.len(), 1);
8778         match events_4[0] {
8779                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
8780                         assert_eq!(user_channel_id, 42);
8781                         assert_eq!(*funding_txo, funding_output);
8782                 },
8783                 _ => panic!("Unexpected event"),
8784         };
8785
8786         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8787         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8788         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8789         send_payment(&nodes[0], &[&nodes[1]], 8000000, 8_000_000);
8790 }
8791
8792 #[test]
8793 fn test_error_chans_closed() {
8794         // Test that we properly handle error messages, closing appropriate channels.
8795         //
8796         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8797         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8798         // we can test various edge cases around it to ensure we don't regress.
8799         let chanmon_cfgs = create_chanmon_cfgs(3);
8800         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8801         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8802         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8803
8804         // Create some initial channels
8805         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8806         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8807         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8808
8809         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8810         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8811         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8812
8813         // Closing a channel from a different peer has no effect
8814         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8815         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8816
8817         // Closing one channel doesn't impact others
8818         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8819         check_added_monitors!(nodes[0], 1);
8820         check_closed_broadcast!(nodes[0], false);
8821         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8822         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);
8823         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);
8824
8825         // A null channel ID should close all channels
8826         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8827         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8828         check_added_monitors!(nodes[0], 2);
8829         let events = nodes[0].node.get_and_clear_pending_msg_events();
8830         assert_eq!(events.len(), 2);
8831         match events[0] {
8832                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8833                         assert_eq!(msg.contents.flags & 2, 2);
8834                 },
8835                 _ => panic!("Unexpected event"),
8836         }
8837         match events[1] {
8838                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8839                         assert_eq!(msg.contents.flags & 2, 2);
8840                 },
8841                 _ => panic!("Unexpected event"),
8842         }
8843         // Note that at this point users of a standard PeerHandler will end up calling
8844         // peer_disconnected with no_connection_possible set to false, duplicating the
8845         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8846         // users with their own peer handling logic. We duplicate the call here, however.
8847         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8848         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8849
8850         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8851         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8852         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8853 }