Switch from slice to slice-of-refs for spend_spendable_outputs
[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::{ChannelKeys, 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::EnforcingChannelKeys;
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 use std::mem;
55
56 use ln::functional_test_utils::*;
57 use ln::chan_utils::CommitmentTransaction;
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::<EnforcingChannelKeys>::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, &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, &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, &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(), &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(), &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(), &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(), &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, &[], 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, &[], 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, &[], 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(), &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(), &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(), &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(), &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(), &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(), &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(), &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(), &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(), &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, &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, &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, &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, &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, &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, &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 EnforcingChannelKeys 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_keys = local_chan.get_keys();
1619                 let pubkeys = chan_keys.pubkeys();
1620                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1621                  chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1622                  chan_keys.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_keys = remote_chan.get_keys();
1628                 let pubkeys = chan_keys.pubkeys();
1629                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1630                  chan_keys.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_keys = local_chan.get_keys();
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_keys.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 amount would result in a channel reserve violation. In this test
1705         // we check that we would be prevented from sending an HTLC in this situation.
1706         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1707         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1708         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1709         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1710         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1711         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1712         let logger = test_utils::TestLogger::new();
1713
1714         macro_rules! get_route_and_payment_hash {
1715                 ($recv_value: expr) => {{
1716                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1717                         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1718                         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.first().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1719                         (route, payment_hash, payment_preimage)
1720                 }}
1721         }
1722
1723         let (route, our_payment_hash, _) = get_route_and_payment_hash!(1000);
1724         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1725                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1726         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1727         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
1728 }
1729
1730 #[test]
1731 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1732         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1733         // Set the fee rate for the channel very high, to the point where the funder
1734         // receiving 1 update_add_htlc would result in them closing the channel due
1735         // to channel reserve violation. This close could also happen if the fee went
1736         // up a more realistic amount, but many HTLCs were outstanding at the time of
1737         // the update_add_htlc.
1738         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1739         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1740         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1741         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1742         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1743         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1744         let logger = test_utils::TestLogger::new();
1745
1746         macro_rules! get_route_and_payment_hash {
1747                 ($recv_value: expr) => {{
1748                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1749                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1750                         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.first().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1751                         (route, payment_hash, payment_preimage)
1752                 }}
1753         }
1754
1755         let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1756         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1757         let secp_ctx = Secp256k1::new();
1758         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1759         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1760         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1761         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1762         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1763         let msg = msgs::UpdateAddHTLC {
1764                 channel_id: chan.2,
1765                 htlc_id: 1,
1766                 amount_msat: htlc_msat + 1,
1767                 payment_hash: payment_hash,
1768                 cltv_expiry: htlc_cltv,
1769                 onion_routing_packet: onion_packet,
1770         };
1771
1772         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1773         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1774         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1775         assert_eq!(nodes[0].node.list_channels().len(), 0);
1776         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1777         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1778         check_added_monitors!(nodes[0], 1);
1779 }
1780
1781 #[test]
1782 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1783         let chanmon_cfgs = create_chanmon_cfgs(3);
1784         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1785         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1786         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1787         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1788         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1789         let logger = test_utils::TestLogger::new();
1790
1791         macro_rules! get_route_and_payment_hash {
1792                 ($recv_value: expr) => {{
1793                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1794                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1795                         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, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1796                         (route, payment_hash, payment_preimage)
1797                 }}
1798         }
1799
1800         let feemsat = 239;
1801         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1802         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1803         let feerate = get_feerate!(nodes[0], chan.2);
1804
1805         // Add a 2* and +1 for the fee spike reserve.
1806         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1807         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;
1808         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1809
1810         // Add a pending HTLC.
1811         let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1812         let payment_event_1 = {
1813                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1814                 check_added_monitors!(nodes[0], 1);
1815
1816                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1817                 assert_eq!(events.len(), 1);
1818                 SendEvent::from_event(events.remove(0))
1819         };
1820         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1821
1822         // Attempt to trigger a channel reserve violation --> payment failure.
1823         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1824         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;
1825         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1826         let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1827
1828         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1829         let secp_ctx = Secp256k1::new();
1830         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1831         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1832         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1833         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1834         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1835         let msg = msgs::UpdateAddHTLC {
1836                 channel_id: chan.2,
1837                 htlc_id: 1,
1838                 amount_msat: htlc_msat + 1,
1839                 payment_hash: our_payment_hash_1,
1840                 cltv_expiry: htlc_cltv,
1841                 onion_routing_packet: onion_packet,
1842         };
1843
1844         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1845         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1846         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1847         assert_eq!(nodes[1].node.list_channels().len(), 1);
1848         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1849         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1850         check_added_monitors!(nodes[1], 1);
1851 }
1852
1853 #[test]
1854 fn test_inbound_outbound_capacity_is_not_zero() {
1855         let chanmon_cfgs = create_chanmon_cfgs(2);
1856         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1857         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1858         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1859         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1860         let channels0 = node_chanmgrs[0].list_channels();
1861         let channels1 = node_chanmgrs[1].list_channels();
1862         assert_eq!(channels0.len(), 1);
1863         assert_eq!(channels1.len(), 1);
1864
1865         assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1866         assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1867
1868         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1869         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1870 }
1871
1872 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1873         (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1874 }
1875
1876 #[test]
1877 fn test_channel_reserve_holding_cell_htlcs() {
1878         let chanmon_cfgs = create_chanmon_cfgs(3);
1879         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1880         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1881         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1882         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1883         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1884         let logger = test_utils::TestLogger::new();
1885
1886         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1887         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1888
1889         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1890         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1891
1892         macro_rules! get_route_and_payment_hash {
1893                 ($recv_value: expr) => {{
1894                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1895                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1896                         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, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1897                         (route, payment_hash, payment_preimage)
1898                 }}
1899         }
1900
1901         macro_rules! expect_forward {
1902                 ($node: expr) => {{
1903                         let mut events = $node.node.get_and_clear_pending_msg_events();
1904                         assert_eq!(events.len(), 1);
1905                         check_added_monitors!($node, 1);
1906                         let payment_event = SendEvent::from_event(events.remove(0));
1907                         payment_event
1908                 }}
1909         }
1910
1911         let feemsat = 239; // somehow we know?
1912         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1913         let feerate = get_feerate!(nodes[0], chan_1.2);
1914
1915         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1916
1917         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1918         {
1919                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1920                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1921                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1922                         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)));
1923                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1924                 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);
1925         }
1926
1927         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1928         // nodes[0]'s wealth
1929         loop {
1930                 let amt_msat = recv_value_0 + total_fee_msat;
1931                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1932                 // Also, ensure that each payment has enough to be over the dust limit to
1933                 // ensure it'll be included in each commit tx fee calculation.
1934                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1935                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1936                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1937                         break;
1938                 }
1939                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1940
1941                 let (stat01_, stat11_, stat12_, stat22_) = (
1942                         get_channel_value_stat!(nodes[0], chan_1.2),
1943                         get_channel_value_stat!(nodes[1], chan_1.2),
1944                         get_channel_value_stat!(nodes[1], chan_2.2),
1945                         get_channel_value_stat!(nodes[2], chan_2.2),
1946                 );
1947
1948                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1949                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1950                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1951                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1952                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1953         }
1954
1955         // adding pending output.
1956         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1957         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1958         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1959         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1960         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1961         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1962         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1963         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1964         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1965         // policy.
1966         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
1967         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1968         let amt_msat_1 = recv_value_1 + total_fee_msat;
1969
1970         let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
1971         let payment_event_1 = {
1972                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1973                 check_added_monitors!(nodes[0], 1);
1974
1975                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1976                 assert_eq!(events.len(), 1);
1977                 SendEvent::from_event(events.remove(0))
1978         };
1979         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1980
1981         // channel reserve test with htlc pending output > 0
1982         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1983         {
1984                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1985                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1986                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1987                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1988         }
1989
1990         // split the rest to test holding cell
1991         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1992         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1993         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1994         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1995         {
1996                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1997                 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);
1998         }
1999
2000         // now see if they go through on both sides
2001         let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2002         // but this will stuck in the holding cell
2003         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2004         check_added_monitors!(nodes[0], 0);
2005         let events = nodes[0].node.get_and_clear_pending_events();
2006         assert_eq!(events.len(), 0);
2007
2008         // test with outbound holding cell amount > 0
2009         {
2010                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2011                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2012                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2013                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2014                 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);
2015         }
2016
2017         let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2018         // this will also stuck in the holding cell
2019         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2020         check_added_monitors!(nodes[0], 0);
2021         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2022         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2023
2024         // flush the pending htlc
2025         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2026         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2027         check_added_monitors!(nodes[1], 1);
2028
2029         // the pending htlc should be promoted to committed
2030         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2031         check_added_monitors!(nodes[0], 1);
2032         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2033
2034         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2035         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2036         // No commitment_signed so get_event_msg's assert(len == 1) passes
2037         check_added_monitors!(nodes[0], 1);
2038
2039         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2040         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2041         check_added_monitors!(nodes[1], 1);
2042
2043         expect_pending_htlcs_forwardable!(nodes[1]);
2044
2045         let ref payment_event_11 = expect_forward!(nodes[1]);
2046         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2047         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2048
2049         expect_pending_htlcs_forwardable!(nodes[2]);
2050         expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2051
2052         // flush the htlcs in the holding cell
2053         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2054         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2055         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2056         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2057         expect_pending_htlcs_forwardable!(nodes[1]);
2058
2059         let ref payment_event_3 = expect_forward!(nodes[1]);
2060         assert_eq!(payment_event_3.msgs.len(), 2);
2061         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2062         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2063
2064         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2065         expect_pending_htlcs_forwardable!(nodes[2]);
2066
2067         let events = nodes[2].node.get_and_clear_pending_events();
2068         assert_eq!(events.len(), 2);
2069         match events[0] {
2070                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2071                         assert_eq!(our_payment_hash_21, *payment_hash);
2072                         assert_eq!(*payment_secret, None);
2073                         assert_eq!(recv_value_21, amt);
2074                 },
2075                 _ => panic!("Unexpected event"),
2076         }
2077         match events[1] {
2078                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2079                         assert_eq!(our_payment_hash_22, *payment_hash);
2080                         assert_eq!(None, *payment_secret);
2081                         assert_eq!(recv_value_22, amt);
2082                 },
2083                 _ => panic!("Unexpected event"),
2084         }
2085
2086         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2087         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2088         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2089
2090         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2091         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2092         {
2093                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_3 + 1);
2094                 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
2095                 match err {
2096                         PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
2097                                 match &fails[0] {
2098                                         &APIError::ChannelUnavailable{ref err} =>
2099                                                 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
2100                                         _ => panic!("Unexpected error variant"),
2101                                 }
2102                         },
2103                         _ => panic!("Unexpected error variant"),
2104                 }
2105                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2106                 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(), 3);
2107         }
2108
2109         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2110
2111         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2112         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);
2113         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2114         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2115         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2116
2117         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2118         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2119 }
2120
2121 #[test]
2122 fn channel_reserve_in_flight_removes() {
2123         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2124         // can send to its counterparty, but due to update ordering, the other side may not yet have
2125         // considered those HTLCs fully removed.
2126         // This tests that we don't count HTLCs which will not be included in the next remote
2127         // commitment transaction towards the reserve value (as it implies no commitment transaction
2128         // will be generated which violates the remote reserve value).
2129         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2130         // To test this we:
2131         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2132         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2133         //    you only consider the value of the first HTLC, it may not),
2134         //  * start routing a third HTLC from A to B,
2135         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2136         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2137         //  * deliver the first fulfill from B
2138         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2139         //    claim,
2140         //  * deliver A's response CS and RAA.
2141         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2142         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2143         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2144         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2145         let chanmon_cfgs = create_chanmon_cfgs(2);
2146         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2147         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2148         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2149         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2150         let logger = test_utils::TestLogger::new();
2151
2152         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2153         // Route the first two HTLCs.
2154         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2155         let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2156
2157         // Start routing the third HTLC (this is just used to get everyone in the right state).
2158         let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2159         let send_1 = {
2160                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2161                 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, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
2162                 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2163                 check_added_monitors!(nodes[0], 1);
2164                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2165                 assert_eq!(events.len(), 1);
2166                 SendEvent::from_event(events.remove(0))
2167         };
2168
2169         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2170         // initial fulfill/CS.
2171         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2172         check_added_monitors!(nodes[1], 1);
2173         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2174
2175         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2176         // remove the second HTLC when we send the HTLC back from B to A.
2177         assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2178         check_added_monitors!(nodes[1], 1);
2179         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2180
2181         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2182         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2183         check_added_monitors!(nodes[0], 1);
2184         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2185         expect_payment_sent!(nodes[0], payment_preimage_1);
2186
2187         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2188         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2189         check_added_monitors!(nodes[1], 1);
2190         // B is already AwaitingRAA, so cant generate a CS here
2191         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2192
2193         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2194         check_added_monitors!(nodes[1], 1);
2195         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2196
2197         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2198         check_added_monitors!(nodes[0], 1);
2199         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2200
2201         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2202         check_added_monitors!(nodes[1], 1);
2203         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2204
2205         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2206         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2207         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2208         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2209         // on-chain as necessary).
2210         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2211         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2212         check_added_monitors!(nodes[0], 1);
2213         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2214         expect_payment_sent!(nodes[0], payment_preimage_2);
2215
2216         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2217         check_added_monitors!(nodes[1], 1);
2218         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2219
2220         expect_pending_htlcs_forwardable!(nodes[1]);
2221         expect_payment_received!(nodes[1], payment_hash_3, 100000);
2222
2223         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2224         // resolve the second HTLC from A's point of view.
2225         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2226         check_added_monitors!(nodes[0], 1);
2227         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2228
2229         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2230         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2231         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2232         let send_2 = {
2233                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2234                 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, &[], 10000, TEST_FINAL_CLTV, &logger).unwrap();
2235                 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2236                 check_added_monitors!(nodes[1], 1);
2237                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2238                 assert_eq!(events.len(), 1);
2239                 SendEvent::from_event(events.remove(0))
2240         };
2241
2242         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2243         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2244         check_added_monitors!(nodes[0], 1);
2245         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2246
2247         // Now just resolve all the outstanding messages/HTLCs for completeness...
2248
2249         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2250         check_added_monitors!(nodes[1], 1);
2251         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2252
2253         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2254         check_added_monitors!(nodes[1], 1);
2255
2256         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2257         check_added_monitors!(nodes[0], 1);
2258         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2259
2260         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2261         check_added_monitors!(nodes[1], 1);
2262         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2263
2264         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2265         check_added_monitors!(nodes[0], 1);
2266
2267         expect_pending_htlcs_forwardable!(nodes[0]);
2268         expect_payment_received!(nodes[0], payment_hash_4, 10000);
2269
2270         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2271         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2272 }
2273
2274 #[test]
2275 fn channel_monitor_network_test() {
2276         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2277         // tests that ChannelMonitor is able to recover from various states.
2278         let chanmon_cfgs = create_chanmon_cfgs(5);
2279         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2280         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2281         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2282
2283         // Create some initial channels
2284         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2285         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2286         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2287         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2288
2289         // Rebalance the network a bit by relaying one payment through all the channels...
2290         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2291         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2292         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2293         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2294
2295         // Simple case with no pending HTLCs:
2296         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2297         check_added_monitors!(nodes[1], 1);
2298         {
2299                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2300                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2301                 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2302                 check_added_monitors!(nodes[0], 1);
2303                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2304         }
2305         get_announce_close_broadcast_events(&nodes, 0, 1);
2306         assert_eq!(nodes[0].node.list_channels().len(), 0);
2307         assert_eq!(nodes[1].node.list_channels().len(), 1);
2308
2309         // One pending HTLC is discarded by the force-close:
2310         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2311
2312         // Simple case of one pending HTLC to HTLC-Timeout
2313         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2314         check_added_monitors!(nodes[1], 1);
2315         {
2316                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2317                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2318                 connect_block(&nodes[2], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2319                 check_added_monitors!(nodes[2], 1);
2320                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2321         }
2322         get_announce_close_broadcast_events(&nodes, 1, 2);
2323         assert_eq!(nodes[1].node.list_channels().len(), 0);
2324         assert_eq!(nodes[2].node.list_channels().len(), 1);
2325
2326         macro_rules! claim_funds {
2327                 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2328                         {
2329                                 assert!($node.node.claim_funds($preimage, &None, $amount));
2330                                 check_added_monitors!($node, 1);
2331
2332                                 let events = $node.node.get_and_clear_pending_msg_events();
2333                                 assert_eq!(events.len(), 1);
2334                                 match events[0] {
2335                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2336                                                 assert!(update_add_htlcs.is_empty());
2337                                                 assert!(update_fail_htlcs.is_empty());
2338                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2339                                         },
2340                                         _ => panic!("Unexpected event"),
2341                                 };
2342                         }
2343                 }
2344         }
2345
2346         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2347         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2348         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2349         check_added_monitors!(nodes[2], 1);
2350         let node2_commitment_txid;
2351         {
2352                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2353                 node2_commitment_txid = node_txn[0].txid();
2354
2355                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2356                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2357
2358                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2359                 connect_block(&nodes[3], &Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2360                 check_added_monitors!(nodes[3], 1);
2361
2362                 check_preimage_claim(&nodes[3], &node_txn);
2363         }
2364         get_announce_close_broadcast_events(&nodes, 2, 3);
2365         assert_eq!(nodes[2].node.list_channels().len(), 0);
2366         assert_eq!(nodes[3].node.list_channels().len(), 1);
2367
2368         { // Cheat and reset nodes[4]'s height to 1
2369                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2370                 connect_block(&nodes[4], &Block { header, txdata: vec![] }, 1);
2371         }
2372
2373         assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2374         assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2375         // One pending HTLC to time out:
2376         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2377         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2378         // buffer space).
2379
2380         let (close_chan_update_1, close_chan_update_2) = {
2381                 let mut block = Block {
2382                         header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2383                         txdata: vec![],
2384                 };
2385                 connect_block(&nodes[3], &block, 2);
2386                 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2387                         block = Block {
2388                                 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2389                                 txdata: vec![],
2390                         };
2391                         connect_block(&nodes[3], &block, i);
2392                 }
2393                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2394                 assert_eq!(events.len(), 1);
2395                 let close_chan_update_1 = match events[0] {
2396                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2397                                 msg.clone()
2398                         },
2399                         _ => panic!("Unexpected event"),
2400                 };
2401                 check_added_monitors!(nodes[3], 1);
2402
2403                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2404                 {
2405                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2406                         node_txn.retain(|tx| {
2407                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2408                                         false
2409                                 } else { true }
2410                         });
2411                 }
2412
2413                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2414
2415                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2416                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2417
2418                 block = Block {
2419                         header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2420                         txdata: vec![],
2421                 };
2422
2423                 connect_block(&nodes[4], &block, 2);
2424                 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2425                         block = Block {
2426                                 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2427                                 txdata: vec![],
2428                         };
2429                         connect_block(&nodes[4], &block, i);
2430                 }
2431                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2432                 assert_eq!(events.len(), 1);
2433                 let close_chan_update_2 = match events[0] {
2434                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2435                                 msg.clone()
2436                         },
2437                         _ => panic!("Unexpected event"),
2438                 };
2439                 check_added_monitors!(nodes[4], 1);
2440                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2441
2442                 block = Block {
2443                         header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2444                         txdata: vec![node_txn[0].clone()],
2445                 };
2446                 connect_block(&nodes[4], &block, TEST_FINAL_CLTV - 5);
2447
2448                 check_preimage_claim(&nodes[4], &node_txn);
2449                 (close_chan_update_1, close_chan_update_2)
2450         };
2451         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2452         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2453         assert_eq!(nodes[3].node.list_channels().len(), 0);
2454         assert_eq!(nodes[4].node.list_channels().len(), 0);
2455 }
2456
2457 #[test]
2458 fn test_justice_tx() {
2459         // Test justice txn built on revoked HTLC-Success tx, against both sides
2460         let mut alice_config = UserConfig::default();
2461         alice_config.channel_options.announced_channel = true;
2462         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2463         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2464         let mut bob_config = UserConfig::default();
2465         bob_config.channel_options.announced_channel = true;
2466         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2467         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2468         let user_cfgs = [Some(alice_config), Some(bob_config)];
2469         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2470         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2471         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2472         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2473         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2474         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2475         // Create some new channels:
2476         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2477
2478         // A pending HTLC which will be revoked:
2479         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2480         // Get the will-be-revoked local txn from nodes[0]
2481         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2482         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2483         assert_eq!(revoked_local_txn[0].input.len(), 1);
2484         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2485         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2486         assert_eq!(revoked_local_txn[1].input.len(), 1);
2487         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2488         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2489         // Revoke the old state
2490         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2491
2492         {
2493                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2494                 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2495                 {
2496                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2497                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2498                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2499
2500                         check_spends!(node_txn[0], revoked_local_txn[0]);
2501                         node_txn.swap_remove(0);
2502                         node_txn.truncate(1);
2503                 }
2504                 check_added_monitors!(nodes[1], 1);
2505                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2506
2507                 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2508                 // Verify broadcast of revoked HTLC-timeout
2509                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2510                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2511                 check_added_monitors!(nodes[0], 1);
2512                 // Broadcast revoked HTLC-timeout on node 1
2513                 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2514                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2515         }
2516         get_announce_close_broadcast_events(&nodes, 0, 1);
2517
2518         assert_eq!(nodes[0].node.list_channels().len(), 0);
2519         assert_eq!(nodes[1].node.list_channels().len(), 0);
2520
2521         // We test justice_tx build by A on B's revoked HTLC-Success tx
2522         // Create some new channels:
2523         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2524         {
2525                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2526                 node_txn.clear();
2527         }
2528
2529         // A pending HTLC which will be revoked:
2530         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2531         // Get the will-be-revoked local txn from B
2532         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2533         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2534         assert_eq!(revoked_local_txn[0].input.len(), 1);
2535         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2536         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2537         // Revoke the old state
2538         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2539         {
2540                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2541                 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2542                 {
2543                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2544                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2545                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2546
2547                         check_spends!(node_txn[0], revoked_local_txn[0]);
2548                         node_txn.swap_remove(0);
2549                 }
2550                 check_added_monitors!(nodes[0], 1);
2551                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2552
2553                 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2554                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2555                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2556                 check_added_monitors!(nodes[1], 1);
2557                 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2558                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2559         }
2560         get_announce_close_broadcast_events(&nodes, 0, 1);
2561         assert_eq!(nodes[0].node.list_channels().len(), 0);
2562         assert_eq!(nodes[1].node.list_channels().len(), 0);
2563 }
2564
2565 #[test]
2566 fn revoked_output_claim() {
2567         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2568         // transaction is broadcast by its counterparty
2569         let chanmon_cfgs = create_chanmon_cfgs(2);
2570         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2571         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2572         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2573         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2574         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2575         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2576         assert_eq!(revoked_local_txn.len(), 1);
2577         // Only output is the full channel value back to nodes[0]:
2578         assert_eq!(revoked_local_txn[0].output.len(), 1);
2579         // Send a payment through, updating everyone's latest commitment txn
2580         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2581
2582         // Inform nodes[1] that nodes[0] broadcast a stale tx
2583         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2584         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2585         check_added_monitors!(nodes[1], 1);
2586         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2587         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2588
2589         check_spends!(node_txn[0], revoked_local_txn[0]);
2590         check_spends!(node_txn[1], chan_1.3);
2591
2592         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2593         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2594         get_announce_close_broadcast_events(&nodes, 0, 1);
2595         check_added_monitors!(nodes[0], 1)
2596 }
2597
2598 #[test]
2599 fn claim_htlc_outputs_shared_tx() {
2600         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2601         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2602         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2603         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2604         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2605         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2606
2607         // Create some new channel:
2608         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2609
2610         // Rebalance the network to generate htlc in the two directions
2611         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2612         // 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
2613         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2614         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2615
2616         // Get the will-be-revoked local txn from node[0]
2617         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2618         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2619         assert_eq!(revoked_local_txn[0].input.len(), 1);
2620         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2621         assert_eq!(revoked_local_txn[1].input.len(), 1);
2622         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2623         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2624         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2625
2626         //Revoke the old state
2627         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2628
2629         {
2630                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2631                 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2632                 check_added_monitors!(nodes[0], 1);
2633                 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2634                 check_added_monitors!(nodes[1], 1);
2635                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
2636                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2637
2638                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2639                 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2640
2641                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2642                 check_spends!(node_txn[0], revoked_local_txn[0]);
2643
2644                 let mut witness_lens = BTreeSet::new();
2645                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2646                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2647                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2648                 assert_eq!(witness_lens.len(), 3);
2649                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2650                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2651                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2652
2653                 // Next nodes[1] broadcasts its current local tx state:
2654                 assert_eq!(node_txn[1].input.len(), 1);
2655                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2656
2657                 assert_eq!(node_txn[2].input.len(), 1);
2658                 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2659                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2660                 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2661                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2662                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2663         }
2664         get_announce_close_broadcast_events(&nodes, 0, 1);
2665         assert_eq!(nodes[0].node.list_channels().len(), 0);
2666         assert_eq!(nodes[1].node.list_channels().len(), 0);
2667 }
2668
2669 #[test]
2670 fn claim_htlc_outputs_single_tx() {
2671         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2672         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2673         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2674         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2675         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2676         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2677
2678         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2679
2680         // Rebalance the network to generate htlc in the two directions
2681         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2682         // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
2683         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2684         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2685         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2686
2687         // Get the will-be-revoked local txn from node[0]
2688         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2689
2690         //Revoke the old state
2691         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2692
2693         {
2694                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2695                 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2696                 check_added_monitors!(nodes[0], 1);
2697                 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2698                 check_added_monitors!(nodes[1], 1);
2699                 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2700
2701                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
2702                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2703
2704                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2705                 assert_eq!(node_txn.len(), 9);
2706                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2707                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2708                 // 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)
2709                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2710
2711                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2712                 assert_eq!(node_txn[2].input.len(), 1);
2713                 check_spends!(node_txn[2], chan_1.3);
2714                 assert_eq!(node_txn[3].input.len(), 1);
2715                 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2716                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2717                 check_spends!(node_txn[3], node_txn[2]);
2718
2719                 // Justice transactions are indices 1-2-4
2720                 assert_eq!(node_txn[0].input.len(), 1);
2721                 assert_eq!(node_txn[1].input.len(), 1);
2722                 assert_eq!(node_txn[4].input.len(), 1);
2723
2724                 check_spends!(node_txn[0], revoked_local_txn[0]);
2725                 check_spends!(node_txn[1], revoked_local_txn[0]);
2726                 check_spends!(node_txn[4], revoked_local_txn[0]);
2727
2728                 let mut witness_lens = BTreeSet::new();
2729                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2730                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2731                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2732                 assert_eq!(witness_lens.len(), 3);
2733                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2734                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2735                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2736         }
2737         get_announce_close_broadcast_events(&nodes, 0, 1);
2738         assert_eq!(nodes[0].node.list_channels().len(), 0);
2739         assert_eq!(nodes[1].node.list_channels().len(), 0);
2740 }
2741
2742 #[test]
2743 fn test_htlc_on_chain_success() {
2744         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2745         // the preimage backward accordingly. So here we test that ChannelManager is
2746         // broadcasting the right event to other nodes in payment path.
2747         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2748         // A --------------------> B ----------------------> C (preimage)
2749         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2750         // commitment transaction was broadcast.
2751         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2752         // towards B.
2753         // B should be able to claim via preimage if A then broadcasts its local tx.
2754         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2755         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2756         // PaymentSent event).
2757
2758         let chanmon_cfgs = create_chanmon_cfgs(3);
2759         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2760         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2761         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2762
2763         // Create some initial channels
2764         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2765         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2766
2767         // Rebalance the network a bit by relaying one payment through all the channels...
2768         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2769         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2770
2771         let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2772         let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2773         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2774
2775         // Broadcast legit commitment tx from C on B's chain
2776         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2777         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2778         assert_eq!(commitment_tx.len(), 1);
2779         check_spends!(commitment_tx[0], chan_2.3);
2780         nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2781         nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2782         check_added_monitors!(nodes[2], 2);
2783         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2784         assert!(updates.update_add_htlcs.is_empty());
2785         assert!(updates.update_fail_htlcs.is_empty());
2786         assert!(updates.update_fail_malformed_htlcs.is_empty());
2787         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2788
2789         connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2790         check_closed_broadcast!(nodes[2], false);
2791         check_added_monitors!(nodes[2], 1);
2792         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)
2793         assert_eq!(node_txn.len(), 5);
2794         assert_eq!(node_txn[0], node_txn[3]);
2795         assert_eq!(node_txn[1], node_txn[4]);
2796         assert_eq!(node_txn[2], commitment_tx[0]);
2797         check_spends!(node_txn[0], commitment_tx[0]);
2798         check_spends!(node_txn[1], commitment_tx[0]);
2799         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2800         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2801         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2802         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2803         assert_eq!(node_txn[0].lock_time, 0);
2804         assert_eq!(node_txn[1].lock_time, 0);
2805
2806         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2807         connect_block(&nodes[1], &Block { header, txdata: node_txn}, 1);
2808         {
2809                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2810                 assert_eq!(added_monitors.len(), 1);
2811                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2812                 added_monitors.clear();
2813         }
2814         let events = nodes[1].node.get_and_clear_pending_msg_events();
2815         {
2816                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2817                 assert_eq!(added_monitors.len(), 2);
2818                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2819                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2820                 added_monitors.clear();
2821         }
2822         assert_eq!(events.len(), 2);
2823         match events[0] {
2824                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2825                 _ => panic!("Unexpected event"),
2826         }
2827         match events[1] {
2828                 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, .. } } => {
2829                         assert!(update_add_htlcs.is_empty());
2830                         assert!(update_fail_htlcs.is_empty());
2831                         assert_eq!(update_fulfill_htlcs.len(), 1);
2832                         assert!(update_fail_malformed_htlcs.is_empty());
2833                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2834                 },
2835                 _ => panic!("Unexpected event"),
2836         };
2837         macro_rules! check_tx_local_broadcast {
2838                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2839                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2840                         assert_eq!(node_txn.len(), 5);
2841                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2842                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2843                         check_spends!(node_txn[0], $commitment_tx);
2844                         check_spends!(node_txn[1], $commitment_tx);
2845                         assert_ne!(node_txn[0].lock_time, 0);
2846                         assert_ne!(node_txn[1].lock_time, 0);
2847                         if $htlc_offered {
2848                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2849                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2850                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2851                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2852                         } else {
2853                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2854                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2855                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2856                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2857                         }
2858                         check_spends!(node_txn[2], $chan_tx);
2859                         check_spends!(node_txn[3], node_txn[2]);
2860                         check_spends!(node_txn[4], node_txn[2]);
2861                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2862                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2863                         assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2864                         assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2865                         assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2866                         assert_ne!(node_txn[3].lock_time, 0);
2867                         assert_ne!(node_txn[4].lock_time, 0);
2868                         node_txn.clear();
2869                 } }
2870         }
2871         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2872         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2873         // timeout-claim of the output that nodes[2] just claimed via success.
2874         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2875
2876         // Broadcast legit commitment tx from A on B's chain
2877         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2878         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2879         check_spends!(commitment_tx[0], chan_1.3);
2880         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2881         check_closed_broadcast!(nodes[1], false);
2882         check_added_monitors!(nodes[1], 1);
2883         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2884         assert_eq!(node_txn.len(), 4);
2885         check_spends!(node_txn[0], commitment_tx[0]);
2886         assert_eq!(node_txn[0].input.len(), 2);
2887         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2888         assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2889         assert_eq!(node_txn[0].lock_time, 0);
2890         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2891         check_spends!(node_txn[1], chan_1.3);
2892         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2893         check_spends!(node_txn[2], node_txn[1]);
2894         check_spends!(node_txn[3], node_txn[1]);
2895         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2896         // we already checked the same situation with A.
2897
2898         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2899         connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2900         check_closed_broadcast!(nodes[0], false);
2901         check_added_monitors!(nodes[0], 1);
2902         let events = nodes[0].node.get_and_clear_pending_events();
2903         assert_eq!(events.len(), 2);
2904         let mut first_claimed = false;
2905         for event in events {
2906                 match event {
2907                         Event::PaymentSent { payment_preimage } => {
2908                                 if payment_preimage == our_payment_preimage {
2909                                         assert!(!first_claimed);
2910                                         first_claimed = true;
2911                                 } else {
2912                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2913                                 }
2914                         },
2915                         _ => panic!("Unexpected event"),
2916                 }
2917         }
2918         check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2919 }
2920
2921 #[test]
2922 fn test_htlc_on_chain_timeout() {
2923         // Test that in case of a unilateral close onchain, we detect the state of output and
2924         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2925         // broadcasting the right event to other nodes in payment path.
2926         // A ------------------> B ----------------------> C (timeout)
2927         //    B's commitment tx                 C's commitment tx
2928         //            \                                  \
2929         //         B's HTLC timeout tx               B's timeout tx
2930
2931         let chanmon_cfgs = create_chanmon_cfgs(3);
2932         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2933         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2934         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2935
2936         // Create some intial channels
2937         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2938         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2939
2940         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2941         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2942         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2943
2944         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2945         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2946
2947         // Broadcast legit commitment tx from C on B's chain
2948         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2949         check_spends!(commitment_tx[0], chan_2.3);
2950         nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2951         check_added_monitors!(nodes[2], 0);
2952         expect_pending_htlcs_forwardable!(nodes[2]);
2953         check_added_monitors!(nodes[2], 1);
2954
2955         let events = nodes[2].node.get_and_clear_pending_msg_events();
2956         assert_eq!(events.len(), 1);
2957         match events[0] {
2958                 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, .. } } => {
2959                         assert!(update_add_htlcs.is_empty());
2960                         assert!(!update_fail_htlcs.is_empty());
2961                         assert!(update_fulfill_htlcs.is_empty());
2962                         assert!(update_fail_malformed_htlcs.is_empty());
2963                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2964                 },
2965                 _ => panic!("Unexpected event"),
2966         };
2967         connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2968         check_closed_broadcast!(nodes[2], false);
2969         check_added_monitors!(nodes[2], 1);
2970         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2971         assert_eq!(node_txn.len(), 1);
2972         check_spends!(node_txn[0], chan_2.3);
2973         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2974
2975         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2976         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2977         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2978         let timeout_tx;
2979         {
2980                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2981                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2982                 assert_eq!(node_txn[1], node_txn[3]);
2983                 assert_eq!(node_txn[2], node_txn[4]);
2984
2985                 check_spends!(node_txn[0], commitment_tx[0]);
2986                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2987
2988                 check_spends!(node_txn[1], chan_2.3);
2989                 check_spends!(node_txn[2], node_txn[1]);
2990                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2991                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2992
2993                 timeout_tx = node_txn[0].clone();
2994                 node_txn.clear();
2995         }
2996
2997         connect_block(&nodes[1], &Block { header, txdata: vec![timeout_tx]}, 1);
2998         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
2999         check_added_monitors!(nodes[1], 1);
3000         check_closed_broadcast!(nodes[1], false);
3001
3002         expect_pending_htlcs_forwardable!(nodes[1]);
3003         check_added_monitors!(nodes[1], 1);
3004         let events = nodes[1].node.get_and_clear_pending_msg_events();
3005         assert_eq!(events.len(), 1);
3006         match events[0] {
3007                 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, .. } } => {
3008                         assert!(update_add_htlcs.is_empty());
3009                         assert!(!update_fail_htlcs.is_empty());
3010                         assert!(update_fulfill_htlcs.is_empty());
3011                         assert!(update_fail_malformed_htlcs.is_empty());
3012                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3013                 },
3014                 _ => panic!("Unexpected event"),
3015         };
3016         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
3017         assert_eq!(node_txn.len(), 0);
3018
3019         // Broadcast legit commitment tx from B on A's chain
3020         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3021         check_spends!(commitment_tx[0], chan_1.3);
3022
3023         connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3024         check_closed_broadcast!(nodes[0], false);
3025         check_added_monitors!(nodes[0], 1);
3026         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3027         assert_eq!(node_txn.len(), 3);
3028         check_spends!(node_txn[0], commitment_tx[0]);
3029         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3030         check_spends!(node_txn[1], chan_1.3);
3031         check_spends!(node_txn[2], node_txn[1]);
3032         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3033         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3034 }
3035
3036 #[test]
3037 fn test_simple_commitment_revoked_fail_backward() {
3038         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3039         // and fail backward accordingly.
3040
3041         let chanmon_cfgs = create_chanmon_cfgs(3);
3042         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3043         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3044         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3045
3046         // Create some initial channels
3047         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3048         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3049
3050         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3051         // Get the will-be-revoked local txn from nodes[2]
3052         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3053         // Revoke the old state
3054         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3055
3056         let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3057
3058         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3059         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3060         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3061         check_added_monitors!(nodes[1], 1);
3062         check_closed_broadcast!(nodes[1], false);
3063
3064         expect_pending_htlcs_forwardable!(nodes[1]);
3065         check_added_monitors!(nodes[1], 1);
3066         let events = nodes[1].node.get_and_clear_pending_msg_events();
3067         assert_eq!(events.len(), 1);
3068         match events[0] {
3069                 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, .. } } => {
3070                         assert!(update_add_htlcs.is_empty());
3071                         assert_eq!(update_fail_htlcs.len(), 1);
3072                         assert!(update_fulfill_htlcs.is_empty());
3073                         assert!(update_fail_malformed_htlcs.is_empty());
3074                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3075
3076                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3077                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3078
3079                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3080                         assert_eq!(events.len(), 1);
3081                         match events[0] {
3082                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3083                                 _ => panic!("Unexpected event"),
3084                         }
3085                         expect_payment_failed!(nodes[0], payment_hash, false);
3086                 },
3087                 _ => panic!("Unexpected event"),
3088         }
3089 }
3090
3091 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3092         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3093         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3094         // commitment transaction anymore.
3095         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3096         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3097         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3098         // technically disallowed and we should probably handle it reasonably.
3099         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3100         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3101         // transactions:
3102         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3103         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3104         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3105         //   and once they revoke the previous commitment transaction (allowing us to send a new
3106         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3107         let chanmon_cfgs = create_chanmon_cfgs(3);
3108         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3109         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3110         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3111
3112         // Create some initial channels
3113         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3114         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3115
3116         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3117         // Get the will-be-revoked local txn from nodes[2]
3118         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3119         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3120         // Revoke the old state
3121         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3122
3123         let value = if use_dust {
3124                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3125                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3126                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3127         } else { 3000000 };
3128
3129         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3130         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3131         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3132
3133         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3134         expect_pending_htlcs_forwardable!(nodes[2]);
3135         check_added_monitors!(nodes[2], 1);
3136         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3137         assert!(updates.update_add_htlcs.is_empty());
3138         assert!(updates.update_fulfill_htlcs.is_empty());
3139         assert!(updates.update_fail_malformed_htlcs.is_empty());
3140         assert_eq!(updates.update_fail_htlcs.len(), 1);
3141         assert!(updates.update_fee.is_none());
3142         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3143         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3144         // Drop the last RAA from 3 -> 2
3145
3146         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3147         expect_pending_htlcs_forwardable!(nodes[2]);
3148         check_added_monitors!(nodes[2], 1);
3149         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3150         assert!(updates.update_add_htlcs.is_empty());
3151         assert!(updates.update_fulfill_htlcs.is_empty());
3152         assert!(updates.update_fail_malformed_htlcs.is_empty());
3153         assert_eq!(updates.update_fail_htlcs.len(), 1);
3154         assert!(updates.update_fee.is_none());
3155         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3156         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3157         check_added_monitors!(nodes[1], 1);
3158         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3159         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3160         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3161         check_added_monitors!(nodes[2], 1);
3162
3163         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3164         expect_pending_htlcs_forwardable!(nodes[2]);
3165         check_added_monitors!(nodes[2], 1);
3166         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3167         assert!(updates.update_add_htlcs.is_empty());
3168         assert!(updates.update_fulfill_htlcs.is_empty());
3169         assert!(updates.update_fail_malformed_htlcs.is_empty());
3170         assert_eq!(updates.update_fail_htlcs.len(), 1);
3171         assert!(updates.update_fee.is_none());
3172         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3173         // At this point first_payment_hash has dropped out of the latest two commitment
3174         // transactions that nodes[1] is tracking...
3175         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3176         check_added_monitors!(nodes[1], 1);
3177         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3178         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3179         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3180         check_added_monitors!(nodes[2], 1);
3181
3182         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3183         // on nodes[2]'s RAA.
3184         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3185         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3186         let logger = test_utils::TestLogger::new();
3187         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, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3188         nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3189         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3190         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3191         check_added_monitors!(nodes[1], 0);
3192
3193         if deliver_bs_raa {
3194                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3195                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3196                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3197                 check_added_monitors!(nodes[1], 1);
3198                 let events = nodes[1].node.get_and_clear_pending_events();
3199                 assert_eq!(events.len(), 1);
3200                 match events[0] {
3201                         Event::PendingHTLCsForwardable { .. } => { },
3202                         _ => panic!("Unexpected event"),
3203                 };
3204                 // Deliberately don't process the pending fail-back so they all fail back at once after
3205                 // block connection just like the !deliver_bs_raa case
3206         }
3207
3208         let mut failed_htlcs = HashSet::new();
3209         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3210
3211         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3212         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3213         check_added_monitors!(nodes[1], 1);
3214         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3215
3216         let events = nodes[1].node.get_and_clear_pending_events();
3217         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3218         match events[0] {
3219                 Event::PaymentFailed { ref payment_hash, .. } => {
3220                         assert_eq!(*payment_hash, fourth_payment_hash);
3221                 },
3222                 _ => panic!("Unexpected event"),
3223         }
3224         if !deliver_bs_raa {
3225                 match events[1] {
3226                         Event::PendingHTLCsForwardable { .. } => { },
3227                         _ => panic!("Unexpected event"),
3228                 };
3229         }
3230         nodes[1].node.process_pending_htlc_forwards();
3231         check_added_monitors!(nodes[1], 1);
3232
3233         let events = nodes[1].node.get_and_clear_pending_msg_events();
3234         assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3235         match events[if deliver_bs_raa { 1 } else { 0 }] {
3236                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3237                 _ => panic!("Unexpected event"),
3238         }
3239         if deliver_bs_raa {
3240                 match events[0] {
3241                         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, .. } } => {
3242                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3243                                 assert_eq!(update_add_htlcs.len(), 1);
3244                                 assert!(update_fulfill_htlcs.is_empty());
3245                                 assert!(update_fail_htlcs.is_empty());
3246                                 assert!(update_fail_malformed_htlcs.is_empty());
3247                         },
3248                         _ => panic!("Unexpected event"),
3249                 }
3250         }
3251         match events[if deliver_bs_raa { 2 } else { 1 }] {
3252                 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, .. } } => {
3253                         assert!(update_add_htlcs.is_empty());
3254                         assert_eq!(update_fail_htlcs.len(), 3);
3255                         assert!(update_fulfill_htlcs.is_empty());
3256                         assert!(update_fail_malformed_htlcs.is_empty());
3257                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3258
3259                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3260                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3261                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3262
3263                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3264
3265                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3266                         // If we delivered B's RAA we got an unknown preimage error, not something
3267                         // that we should update our routing table for.
3268                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3269                         for event in events {
3270                                 match event {
3271                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3272                                         _ => panic!("Unexpected event"),
3273                                 }
3274                         }
3275                         let events = nodes[0].node.get_and_clear_pending_events();
3276                         assert_eq!(events.len(), 3);
3277                         match events[0] {
3278                                 Event::PaymentFailed { ref payment_hash, .. } => {
3279                                         assert!(failed_htlcs.insert(payment_hash.0));
3280                                 },
3281                                 _ => panic!("Unexpected event"),
3282                         }
3283                         match events[1] {
3284                                 Event::PaymentFailed { ref payment_hash, .. } => {
3285                                         assert!(failed_htlcs.insert(payment_hash.0));
3286                                 },
3287                                 _ => panic!("Unexpected event"),
3288                         }
3289                         match events[2] {
3290                                 Event::PaymentFailed { ref payment_hash, .. } => {
3291                                         assert!(failed_htlcs.insert(payment_hash.0));
3292                                 },
3293                                 _ => panic!("Unexpected event"),
3294                         }
3295                 },
3296                 _ => panic!("Unexpected event"),
3297         }
3298
3299         assert!(failed_htlcs.contains(&first_payment_hash.0));
3300         assert!(failed_htlcs.contains(&second_payment_hash.0));
3301         assert!(failed_htlcs.contains(&third_payment_hash.0));
3302 }
3303
3304 #[test]
3305 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3306         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3307         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3308         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3309         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3310 }
3311
3312 #[test]
3313 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3314         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3315         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3316         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3317         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3318 }
3319
3320 #[test]
3321 fn fail_backward_pending_htlc_upon_channel_failure() {
3322         let chanmon_cfgs = create_chanmon_cfgs(2);
3323         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3324         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3325         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3326         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3327         let logger = test_utils::TestLogger::new();
3328
3329         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3330         {
3331                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3332                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3333                 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, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3334                 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3335                 check_added_monitors!(nodes[0], 1);
3336
3337                 let payment_event = {
3338                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3339                         assert_eq!(events.len(), 1);
3340                         SendEvent::from_event(events.remove(0))
3341                 };
3342                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3343                 assert_eq!(payment_event.msgs.len(), 1);
3344         }
3345
3346         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3347         let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3348         {
3349                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3350                 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, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3351                 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3352                 check_added_monitors!(nodes[0], 0);
3353
3354                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3355         }
3356
3357         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3358         {
3359                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3360
3361                 let secp_ctx = Secp256k1::new();
3362                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3363                 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3364                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3365                 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, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3366                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3367                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3368                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3369
3370                 // Send a 0-msat update_add_htlc to fail the channel.
3371                 let update_add_htlc = msgs::UpdateAddHTLC {
3372                         channel_id: chan.2,
3373                         htlc_id: 0,
3374                         amount_msat: 0,
3375                         payment_hash,
3376                         cltv_expiry,
3377                         onion_routing_packet,
3378                 };
3379                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3380         }
3381
3382         // Check that Alice fails backward the pending HTLC from the second payment.
3383         expect_payment_failed!(nodes[0], failed_payment_hash, true);
3384         check_closed_broadcast!(nodes[0], true);
3385         check_added_monitors!(nodes[0], 1);
3386 }
3387
3388 #[test]
3389 fn test_htlc_ignore_latest_remote_commitment() {
3390         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3391         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3392         let chanmon_cfgs = create_chanmon_cfgs(2);
3393         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3394         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3395         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3396         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3397
3398         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3399         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3400         check_closed_broadcast!(nodes[0], false);
3401         check_added_monitors!(nodes[0], 1);
3402
3403         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3404         assert_eq!(node_txn.len(), 2);
3405
3406         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3407         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3408         check_closed_broadcast!(nodes[1], false);
3409         check_added_monitors!(nodes[1], 1);
3410
3411         // Duplicate the connect_block call since this may happen due to other listeners
3412         // registering new transactions
3413         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3414 }
3415
3416 #[test]
3417 fn test_force_close_fail_back() {
3418         // Check which HTLCs are failed-backwards on channel force-closure
3419         let chanmon_cfgs = create_chanmon_cfgs(3);
3420         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3421         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3422         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3423         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3424         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3425         let logger = test_utils::TestLogger::new();
3426
3427         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3428
3429         let mut payment_event = {
3430                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3431                 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, &Vec::new(), 1000000, 42, &logger).unwrap();
3432                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3433                 check_added_monitors!(nodes[0], 1);
3434
3435                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3436                 assert_eq!(events.len(), 1);
3437                 SendEvent::from_event(events.remove(0))
3438         };
3439
3440         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3441         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3442
3443         expect_pending_htlcs_forwardable!(nodes[1]);
3444
3445         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3446         assert_eq!(events_2.len(), 1);
3447         payment_event = SendEvent::from_event(events_2.remove(0));
3448         assert_eq!(payment_event.msgs.len(), 1);
3449
3450         check_added_monitors!(nodes[1], 1);
3451         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3452         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3453         check_added_monitors!(nodes[2], 1);
3454         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3455
3456         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3457         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3458         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3459
3460         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3461         check_closed_broadcast!(nodes[2], false);
3462         check_added_monitors!(nodes[2], 1);
3463         let tx = {
3464                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3465                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3466                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3467                 // back to nodes[1] upon timeout otherwise.
3468                 assert_eq!(node_txn.len(), 1);
3469                 node_txn.remove(0)
3470         };
3471
3472         let block = Block {
3473                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3474                 txdata: vec![tx.clone()],
3475         };
3476         connect_block(&nodes[1], &block, 1);
3477
3478         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3479         check_closed_broadcast!(nodes[1], false);
3480         check_added_monitors!(nodes[1], 1);
3481
3482         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3483         {
3484                 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.lock().unwrap();
3485                 monitors.get_mut(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3486                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3487         }
3488         connect_block(&nodes[2], &block, 1);
3489         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3490         assert_eq!(node_txn.len(), 1);
3491         assert_eq!(node_txn[0].input.len(), 1);
3492         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3493         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3494         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3495
3496         check_spends!(node_txn[0], tx);
3497 }
3498
3499 #[test]
3500 fn test_unconf_chan() {
3501         // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3502         let chanmon_cfgs = create_chanmon_cfgs(2);
3503         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3504         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3505         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3506         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3507
3508         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3509         assert_eq!(channel_state.by_id.len(), 1);
3510         assert_eq!(channel_state.short_to_id.len(), 1);
3511         mem::drop(channel_state);
3512
3513         let mut headers = Vec::new();
3514         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3515         headers.push(header.clone());
3516         for _i in 2..100 {
3517                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3518                 headers.push(header.clone());
3519         }
3520         while !headers.is_empty() {
3521                 nodes[0].node.block_disconnected(&headers.pop().unwrap());
3522         }
3523         check_closed_broadcast!(nodes[0], false);
3524         check_added_monitors!(nodes[0], 1);
3525         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3526         assert_eq!(channel_state.by_id.len(), 0);
3527         assert_eq!(channel_state.short_to_id.len(), 0);
3528 }
3529
3530 #[test]
3531 fn test_simple_peer_disconnect() {
3532         // Test that we can reconnect when there are no lost messages
3533         let chanmon_cfgs = create_chanmon_cfgs(3);
3534         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3535         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3536         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3537         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3538         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3539
3540         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3541         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3542         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3543
3544         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3545         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3546         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3547         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3548
3549         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3550         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3551         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3552
3553         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3554         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3555         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3556         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3557
3558         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3559         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3560
3561         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3562         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3563
3564         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3565         {
3566                 let events = nodes[0].node.get_and_clear_pending_events();
3567                 assert_eq!(events.len(), 2);
3568                 match events[0] {
3569                         Event::PaymentSent { payment_preimage } => {
3570                                 assert_eq!(payment_preimage, payment_preimage_3);
3571                         },
3572                         _ => panic!("Unexpected event"),
3573                 }
3574                 match events[1] {
3575                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3576                                 assert_eq!(payment_hash, payment_hash_5);
3577                                 assert!(rejected_by_dest);
3578                         },
3579                         _ => panic!("Unexpected event"),
3580                 }
3581         }
3582
3583         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3584         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3585 }
3586
3587 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3588         // Test that we can reconnect when in-flight HTLC updates get dropped
3589         let chanmon_cfgs = create_chanmon_cfgs(2);
3590         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3591         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3592         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3593         if messages_delivered == 0 {
3594                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3595                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3596         } else {
3597                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3598         }
3599
3600         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3601
3602         let logger = test_utils::TestLogger::new();
3603         let payment_event = {
3604                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3605                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3606                         &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3607                         &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3608                 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3609                 check_added_monitors!(nodes[0], 1);
3610
3611                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3612                 assert_eq!(events.len(), 1);
3613                 SendEvent::from_event(events.remove(0))
3614         };
3615         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3616
3617         if messages_delivered < 2 {
3618                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3619         } else {
3620                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3621                 if messages_delivered >= 3 {
3622                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3623                         check_added_monitors!(nodes[1], 1);
3624                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3625
3626                         if messages_delivered >= 4 {
3627                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3628                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3629                                 check_added_monitors!(nodes[0], 1);
3630
3631                                 if messages_delivered >= 5 {
3632                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3633                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3634                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3635                                         check_added_monitors!(nodes[0], 1);
3636
3637                                         if messages_delivered >= 6 {
3638                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3639                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3640                                                 check_added_monitors!(nodes[1], 1);
3641                                         }
3642                                 }
3643                         }
3644                 }
3645         }
3646
3647         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3648         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3649         if messages_delivered < 3 {
3650                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3651                 // received on either side, both sides will need to resend them.
3652                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3653         } else if messages_delivered == 3 {
3654                 // nodes[0] still wants its RAA + commitment_signed
3655                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3656         } else if messages_delivered == 4 {
3657                 // nodes[0] still wants its commitment_signed
3658                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3659         } else if messages_delivered == 5 {
3660                 // nodes[1] still wants its final RAA
3661                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3662         } else if messages_delivered == 6 {
3663                 // Everything was delivered...
3664                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3665         }
3666
3667         let events_1 = nodes[1].node.get_and_clear_pending_events();
3668         assert_eq!(events_1.len(), 1);
3669         match events_1[0] {
3670                 Event::PendingHTLCsForwardable { .. } => { },
3671                 _ => panic!("Unexpected event"),
3672         };
3673
3674         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3675         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3676         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3677
3678         nodes[1].node.process_pending_htlc_forwards();
3679
3680         let events_2 = nodes[1].node.get_and_clear_pending_events();
3681         assert_eq!(events_2.len(), 1);
3682         match events_2[0] {
3683                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3684                         assert_eq!(payment_hash_1, *payment_hash);
3685                         assert_eq!(*payment_secret, None);
3686                         assert_eq!(amt, 1000000);
3687                 },
3688                 _ => panic!("Unexpected event"),
3689         }
3690
3691         nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3692         check_added_monitors!(nodes[1], 1);
3693
3694         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3695         assert_eq!(events_3.len(), 1);
3696         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3697                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3698                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3699                         assert!(updates.update_add_htlcs.is_empty());
3700                         assert!(updates.update_fail_htlcs.is_empty());
3701                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3702                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3703                         assert!(updates.update_fee.is_none());
3704                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3705                 },
3706                 _ => panic!("Unexpected event"),
3707         };
3708
3709         if messages_delivered >= 1 {
3710                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3711
3712                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3713                 assert_eq!(events_4.len(), 1);
3714                 match events_4[0] {
3715                         Event::PaymentSent { ref payment_preimage } => {
3716                                 assert_eq!(payment_preimage_1, *payment_preimage);
3717                         },
3718                         _ => panic!("Unexpected event"),
3719                 }
3720
3721                 if messages_delivered >= 2 {
3722                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3723                         check_added_monitors!(nodes[0], 1);
3724                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3725
3726                         if messages_delivered >= 3 {
3727                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3728                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3729                                 check_added_monitors!(nodes[1], 1);
3730
3731                                 if messages_delivered >= 4 {
3732                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3733                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3734                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3735                                         check_added_monitors!(nodes[1], 1);
3736
3737                                         if messages_delivered >= 5 {
3738                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3739                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3740                                                 check_added_monitors!(nodes[0], 1);
3741                                         }
3742                                 }
3743                         }
3744                 }
3745         }
3746
3747         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3748         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3749         if messages_delivered < 2 {
3750                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3751                 //TODO: Deduplicate PaymentSent events, then enable this if:
3752                 //if messages_delivered < 1 {
3753                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3754                         assert_eq!(events_4.len(), 1);
3755                         match events_4[0] {
3756                                 Event::PaymentSent { ref payment_preimage } => {
3757                                         assert_eq!(payment_preimage_1, *payment_preimage);
3758                                 },
3759                                 _ => panic!("Unexpected event"),
3760                         }
3761                 //}
3762         } else if messages_delivered == 2 {
3763                 // nodes[0] still wants its RAA + commitment_signed
3764                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3765         } else if messages_delivered == 3 {
3766                 // nodes[0] still wants its commitment_signed
3767                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3768         } else if messages_delivered == 4 {
3769                 // nodes[1] still wants its final RAA
3770                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3771         } else if messages_delivered == 5 {
3772                 // Everything was delivered...
3773                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3774         }
3775
3776         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3777         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3778         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3779
3780         // Channel should still work fine...
3781         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3782         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3783                 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3784                 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3785         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3786         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3787 }
3788
3789 #[test]
3790 fn test_drop_messages_peer_disconnect_a() {
3791         do_test_drop_messages_peer_disconnect(0);
3792         do_test_drop_messages_peer_disconnect(1);
3793         do_test_drop_messages_peer_disconnect(2);
3794         do_test_drop_messages_peer_disconnect(3);
3795 }
3796
3797 #[test]
3798 fn test_drop_messages_peer_disconnect_b() {
3799         do_test_drop_messages_peer_disconnect(4);
3800         do_test_drop_messages_peer_disconnect(5);
3801         do_test_drop_messages_peer_disconnect(6);
3802 }
3803
3804 #[test]
3805 fn test_funding_peer_disconnect() {
3806         // Test that we can lock in our funding tx while disconnected
3807         let chanmon_cfgs = create_chanmon_cfgs(2);
3808         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3809         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3810         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3811         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3812
3813         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3814         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3815
3816         confirm_transaction(&nodes[0], &tx);
3817         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3818         assert_eq!(events_1.len(), 1);
3819         match events_1[0] {
3820                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3821                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3822                 },
3823                 _ => panic!("Unexpected event"),
3824         }
3825
3826         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3827
3828         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3829         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3830
3831         confirm_transaction(&nodes[1], &tx);
3832         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3833         assert_eq!(events_2.len(), 2);
3834         let funding_locked = match events_2[0] {
3835                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3836                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3837                         msg.clone()
3838                 },
3839                 _ => panic!("Unexpected event"),
3840         };
3841         let bs_announcement_sigs = match events_2[1] {
3842                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3843                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3844                         msg.clone()
3845                 },
3846                 _ => panic!("Unexpected event"),
3847         };
3848
3849         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3850
3851         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3852         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3853         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3854         assert_eq!(events_3.len(), 2);
3855         let as_announcement_sigs = match events_3[0] {
3856                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3857                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3858                         msg.clone()
3859                 },
3860                 _ => panic!("Unexpected event"),
3861         };
3862         let (as_announcement, as_update) = match events_3[1] {
3863                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3864                         (msg.clone(), update_msg.clone())
3865                 },
3866                 _ => panic!("Unexpected event"),
3867         };
3868
3869         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3870         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3871         assert_eq!(events_4.len(), 1);
3872         let (_, bs_update) = match events_4[0] {
3873                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3874                         (msg.clone(), update_msg.clone())
3875                 },
3876                 _ => panic!("Unexpected event"),
3877         };
3878
3879         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3880         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3881         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3882
3883         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3884         let logger = test_utils::TestLogger::new();
3885         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, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3886         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3887         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3888 }
3889
3890 #[test]
3891 fn test_drop_messages_peer_disconnect_dual_htlc() {
3892         // Test that we can handle reconnecting when both sides of a channel have pending
3893         // commitment_updates when we disconnect.
3894         let chanmon_cfgs = create_chanmon_cfgs(2);
3895         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3896         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3897         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3898         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3899         let logger = test_utils::TestLogger::new();
3900
3901         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3902
3903         // Now try to send a second payment which will fail to send
3904         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3905         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3906         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, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3907         nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3908         check_added_monitors!(nodes[0], 1);
3909
3910         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3911         assert_eq!(events_1.len(), 1);
3912         match events_1[0] {
3913                 MessageSendEvent::UpdateHTLCs { .. } => {},
3914                 _ => panic!("Unexpected event"),
3915         }
3916
3917         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3918         check_added_monitors!(nodes[1], 1);
3919
3920         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3921         assert_eq!(events_2.len(), 1);
3922         match events_2[0] {
3923                 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 } } => {
3924                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3925                         assert!(update_add_htlcs.is_empty());
3926                         assert_eq!(update_fulfill_htlcs.len(), 1);
3927                         assert!(update_fail_htlcs.is_empty());
3928                         assert!(update_fail_malformed_htlcs.is_empty());
3929                         assert!(update_fee.is_none());
3930
3931                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3932                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3933                         assert_eq!(events_3.len(), 1);
3934                         match events_3[0] {
3935                                 Event::PaymentSent { ref payment_preimage } => {
3936                                         assert_eq!(*payment_preimage, payment_preimage_1);
3937                                 },
3938                                 _ => panic!("Unexpected event"),
3939                         }
3940
3941                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3942                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3943                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3944                         check_added_monitors!(nodes[0], 1);
3945                 },
3946                 _ => panic!("Unexpected event"),
3947         }
3948
3949         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3950         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3951
3952         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3953         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3954         assert_eq!(reestablish_1.len(), 1);
3955         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3956         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3957         assert_eq!(reestablish_2.len(), 1);
3958
3959         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3960         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3961         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3962         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3963
3964         assert!(as_resp.0.is_none());
3965         assert!(bs_resp.0.is_none());
3966
3967         assert!(bs_resp.1.is_none());
3968         assert!(bs_resp.2.is_none());
3969
3970         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3971
3972         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3973         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3974         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3975         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3976         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3977         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3978         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3979         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3980         // No commitment_signed so get_event_msg's assert(len == 1) passes
3981         check_added_monitors!(nodes[1], 1);
3982
3983         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3984         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3985         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3986         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3987         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3988         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3989         assert!(bs_second_commitment_signed.update_fee.is_none());
3990         check_added_monitors!(nodes[1], 1);
3991
3992         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3993         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3994         assert!(as_commitment_signed.update_add_htlcs.is_empty());
3995         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3996         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3997         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3998         assert!(as_commitment_signed.update_fee.is_none());
3999         check_added_monitors!(nodes[0], 1);
4000
4001         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4002         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4003         // No commitment_signed so get_event_msg's assert(len == 1) passes
4004         check_added_monitors!(nodes[0], 1);
4005
4006         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4007         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4008         // No commitment_signed so get_event_msg's assert(len == 1) passes
4009         check_added_monitors!(nodes[1], 1);
4010
4011         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4012         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4013         check_added_monitors!(nodes[1], 1);
4014
4015         expect_pending_htlcs_forwardable!(nodes[1]);
4016
4017         let events_5 = nodes[1].node.get_and_clear_pending_events();
4018         assert_eq!(events_5.len(), 1);
4019         match events_5[0] {
4020                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4021                         assert_eq!(payment_hash_2, *payment_hash);
4022                         assert_eq!(*payment_secret, None);
4023                 },
4024                 _ => panic!("Unexpected event"),
4025         }
4026
4027         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4028         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4029         check_added_monitors!(nodes[0], 1);
4030
4031         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4032 }
4033
4034 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4035         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4036         // to avoid our counterparty failing the channel.
4037         let chanmon_cfgs = create_chanmon_cfgs(2);
4038         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4039         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4040         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4041
4042         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4043         let logger = test_utils::TestLogger::new();
4044
4045         let our_payment_hash = if send_partial_mpp {
4046                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4047                 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, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4048                 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4049                 let payment_secret = PaymentSecret([0xdb; 32]);
4050                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4051                 // indicates there are more HTLCs coming.
4052                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
4053                 check_added_monitors!(nodes[0], 1);
4054                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4055                 assert_eq!(events.len(), 1);
4056                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4057                 // hop should *not* yet generate any PaymentReceived event(s).
4058                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4059                 our_payment_hash
4060         } else {
4061                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4062         };
4063
4064         let mut block = Block {
4065                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4066                 txdata: vec![],
4067         };
4068         connect_block(&nodes[0], &block, 101);
4069         connect_block(&nodes[1], &block, 101);
4070         for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4071                 block.header.prev_blockhash = block.block_hash();
4072                 connect_block(&nodes[0], &block, i);
4073                 connect_block(&nodes[1], &block, i);
4074         }
4075
4076         expect_pending_htlcs_forwardable!(nodes[1]);
4077
4078         check_added_monitors!(nodes[1], 1);
4079         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4080         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4081         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4082         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4083         assert!(htlc_timeout_updates.update_fee.is_none());
4084
4085         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4086         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4087         // 100_000 msat as u64, followed by a height of 123 as u32
4088         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4089         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
4090         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4091 }
4092
4093 #[test]
4094 fn test_htlc_timeout() {
4095         do_test_htlc_timeout(true);
4096         do_test_htlc_timeout(false);
4097 }
4098
4099 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4100         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4101         let chanmon_cfgs = create_chanmon_cfgs(3);
4102         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4103         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4104         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4105         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4106         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4107         let logger = test_utils::TestLogger::new();
4108
4109         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4110         let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4111         {
4112                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4113                 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, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4114                 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4115         }
4116         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4117         check_added_monitors!(nodes[1], 1);
4118
4119         // Now attempt to route a second payment, which should be placed in the holding cell
4120         let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4121         if forwarded_htlc {
4122                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4123                 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, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4124                 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4125                 check_added_monitors!(nodes[0], 1);
4126                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4127                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4128                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4129                 expect_pending_htlcs_forwardable!(nodes[1]);
4130                 check_added_monitors!(nodes[1], 0);
4131         } else {
4132                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4133                 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, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4134                 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4135                 check_added_monitors!(nodes[1], 0);
4136         }
4137
4138         let mut block = Block {
4139                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4140                 txdata: vec![],
4141         };
4142         connect_block(&nodes[1], &block, 101);
4143         for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4144                 block.header.prev_blockhash = block.block_hash();
4145                 connect_block(&nodes[1], &block, i);
4146         }
4147
4148         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4149         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4150
4151         block.header.prev_blockhash = block.block_hash();
4152         connect_block(&nodes[1], &block, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4153
4154         if forwarded_htlc {
4155                 expect_pending_htlcs_forwardable!(nodes[1]);
4156                 check_added_monitors!(nodes[1], 1);
4157                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4158                 assert_eq!(fail_commit.len(), 1);
4159                 match fail_commit[0] {
4160                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4161                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4162                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4163                         },
4164                         _ => unreachable!(),
4165                 }
4166                 expect_payment_failed!(nodes[0], second_payment_hash, false);
4167                 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4168                         match update {
4169                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4170                                 _ => panic!("Unexpected event"),
4171                         }
4172                 } else {
4173                         panic!("Unexpected event");
4174                 }
4175         } else {
4176                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4177         }
4178 }
4179
4180 #[test]
4181 fn test_holding_cell_htlc_add_timeouts() {
4182         do_test_holding_cell_htlc_add_timeouts(false);
4183         do_test_holding_cell_htlc_add_timeouts(true);
4184 }
4185
4186 #[test]
4187 fn test_invalid_channel_announcement() {
4188         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4189         let secp_ctx = Secp256k1::new();
4190         let chanmon_cfgs = create_chanmon_cfgs(2);
4191         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4192         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4193         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4194
4195         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4196
4197         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4198         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4199         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4200         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4201
4202         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 } );
4203
4204         let as_bitcoin_key = as_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4205         let bs_bitcoin_key = bs_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4206
4207         let as_network_key = nodes[0].node.get_our_node_id();
4208         let bs_network_key = nodes[1].node.get_our_node_id();
4209
4210         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4211
4212         let mut chan_announcement;
4213
4214         macro_rules! dummy_unsigned_msg {
4215                 () => {
4216                         msgs::UnsignedChannelAnnouncement {
4217                                 features: ChannelFeatures::known(),
4218                                 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4219                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4220                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4221                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4222                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4223                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4224                                 excess_data: Vec::new(),
4225                         };
4226                 }
4227         }
4228
4229         macro_rules! sign_msg {
4230                 ($unsigned_msg: expr) => {
4231                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4232                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_keys().inner.funding_key);
4233                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_keys().inner.funding_key);
4234                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4235                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4236                         chan_announcement = msgs::ChannelAnnouncement {
4237                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4238                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4239                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4240                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4241                                 contents: $unsigned_msg
4242                         }
4243                 }
4244         }
4245
4246         let unsigned_msg = dummy_unsigned_msg!();
4247         sign_msg!(unsigned_msg);
4248         assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4249         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 } );
4250
4251         // Configured with Network::Testnet
4252         let mut unsigned_msg = dummy_unsigned_msg!();
4253         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4254         sign_msg!(unsigned_msg);
4255         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4256
4257         let mut unsigned_msg = dummy_unsigned_msg!();
4258         unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4259         sign_msg!(unsigned_msg);
4260         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4261 }
4262
4263 #[test]
4264 fn test_no_txn_manager_serialize_deserialize() {
4265         let chanmon_cfgs = create_chanmon_cfgs(2);
4266         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4267         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4268         let logger: test_utils::TestLogger;
4269         let fee_estimator: test_utils::TestFeeEstimator;
4270         let persister: test_utils::TestPersister;
4271         let new_chain_monitor: test_utils::TestChainMonitor;
4272         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4273         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4274
4275         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4276
4277         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4278
4279         let nodes_0_serialized = nodes[0].node.encode();
4280         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4281         nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4282
4283         logger = test_utils::TestLogger::new();
4284         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4285         persister = test_utils::TestPersister::new();
4286         let keys_manager = &chanmon_cfgs[0].keys_manager;
4287         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4288         nodes[0].chain_monitor = &new_chain_monitor;
4289         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4290         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(
4291                 &mut chan_0_monitor_read, keys_manager).unwrap();
4292         assert!(chan_0_monitor_read.is_empty());
4293
4294         let mut nodes_0_read = &nodes_0_serialized[..];
4295         let config = UserConfig::default();
4296         let (_, nodes_0_deserialized_tmp) = {
4297                 let mut channel_monitors = HashMap::new();
4298                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4299                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4300                         default_config: config,
4301                         keys_manager,
4302                         fee_estimator: &fee_estimator,
4303                         chain_monitor: nodes[0].chain_monitor,
4304                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4305                         logger: &logger,
4306                         channel_monitors,
4307                 }).unwrap()
4308         };
4309         nodes_0_deserialized = nodes_0_deserialized_tmp;
4310         assert!(nodes_0_read.is_empty());
4311
4312         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4313         nodes[0].node = &nodes_0_deserialized;
4314         assert_eq!(nodes[0].node.list_channels().len(), 1);
4315         check_added_monitors!(nodes[0], 1);
4316
4317         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4318         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4319         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4320         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4321
4322         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4323         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4324         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4325         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4326
4327         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4328         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4329         for node in nodes.iter() {
4330                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4331                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4332                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4333         }
4334
4335         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4336 }
4337
4338 #[test]
4339 fn test_manager_serialize_deserialize_events() {
4340         // This test makes sure the events field in ChannelManager survives de/serialization
4341         let chanmon_cfgs = create_chanmon_cfgs(2);
4342         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4343         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4344         let fee_estimator: test_utils::TestFeeEstimator;
4345         let persister: test_utils::TestPersister;
4346         let logger: test_utils::TestLogger;
4347         let new_chain_monitor: test_utils::TestChainMonitor;
4348         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4349         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4350
4351         // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4352         let channel_value = 100000;
4353         let push_msat = 10001;
4354         let a_flags = InitFeatures::known();
4355         let b_flags = InitFeatures::known();
4356         let node_a = nodes.remove(0);
4357         let node_b = nodes.remove(0);
4358         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4359         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()));
4360         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()));
4361
4362         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4363
4364         node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4365         check_added_monitors!(node_a, 0);
4366
4367         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()));
4368         {
4369                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4370                 assert_eq!(added_monitors.len(), 1);
4371                 assert_eq!(added_monitors[0].0, funding_output);
4372                 added_monitors.clear();
4373         }
4374
4375         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()));
4376         {
4377                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4378                 assert_eq!(added_monitors.len(), 1);
4379                 assert_eq!(added_monitors[0].0, funding_output);
4380                 added_monitors.clear();
4381         }
4382         // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4383
4384         nodes.push(node_a);
4385         nodes.push(node_b);
4386
4387         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4388         let nodes_0_serialized = nodes[0].node.encode();
4389         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4390         nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4391
4392         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4393         logger = test_utils::TestLogger::new();
4394         persister = test_utils::TestPersister::new();
4395         let keys_manager = &chanmon_cfgs[0].keys_manager;
4396         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4397         nodes[0].chain_monitor = &new_chain_monitor;
4398         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4399         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(
4400                 &mut chan_0_monitor_read, keys_manager).unwrap();
4401         assert!(chan_0_monitor_read.is_empty());
4402
4403         let mut nodes_0_read = &nodes_0_serialized[..];
4404         let config = UserConfig::default();
4405         let (_, nodes_0_deserialized_tmp) = {
4406                 let mut channel_monitors = HashMap::new();
4407                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4408                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4409                         default_config: config,
4410                         keys_manager,
4411                         fee_estimator: &fee_estimator,
4412                         chain_monitor: nodes[0].chain_monitor,
4413                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4414                         logger: &logger,
4415                         channel_monitors,
4416                 }).unwrap()
4417         };
4418         nodes_0_deserialized = nodes_0_deserialized_tmp;
4419         assert!(nodes_0_read.is_empty());
4420
4421         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4422
4423         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4424         nodes[0].node = &nodes_0_deserialized;
4425
4426         // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4427         let events_4 = nodes[0].node.get_and_clear_pending_events();
4428         assert_eq!(events_4.len(), 1);
4429         match events_4[0] {
4430                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4431                         assert_eq!(user_channel_id, 42);
4432                         assert_eq!(*funding_txo, funding_output);
4433                 },
4434                 _ => panic!("Unexpected event"),
4435         };
4436
4437         // Make sure the channel is functioning as though the de/serialization never happened
4438         assert_eq!(nodes[0].node.list_channels().len(), 1);
4439         check_added_monitors!(nodes[0], 1);
4440
4441         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4442         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4443         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4444         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4445
4446         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4447         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4448         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4449         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4450
4451         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4452         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4453         for node in nodes.iter() {
4454                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4455                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4456                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4457         }
4458
4459         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4460 }
4461
4462 #[test]
4463 fn test_simple_manager_serialize_deserialize() {
4464         let chanmon_cfgs = create_chanmon_cfgs(2);
4465         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4466         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4467         let logger: test_utils::TestLogger;
4468         let fee_estimator: test_utils::TestFeeEstimator;
4469         let persister: test_utils::TestPersister;
4470         let new_chain_monitor: test_utils::TestChainMonitor;
4471         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4472         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4473         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4474
4475         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4476         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4477
4478         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4479
4480         let nodes_0_serialized = nodes[0].node.encode();
4481         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4482         nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4483
4484         logger = test_utils::TestLogger::new();
4485         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4486         persister = test_utils::TestPersister::new();
4487         let keys_manager = &chanmon_cfgs[0].keys_manager;
4488         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4489         nodes[0].chain_monitor = &new_chain_monitor;
4490         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4491         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(
4492                 &mut chan_0_monitor_read, keys_manager).unwrap();
4493         assert!(chan_0_monitor_read.is_empty());
4494
4495         let mut nodes_0_read = &nodes_0_serialized[..];
4496         let (_, nodes_0_deserialized_tmp) = {
4497                 let mut channel_monitors = HashMap::new();
4498                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4499                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4500                         default_config: UserConfig::default(),
4501                         keys_manager,
4502                         fee_estimator: &fee_estimator,
4503                         chain_monitor: nodes[0].chain_monitor,
4504                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4505                         logger: &logger,
4506                         channel_monitors,
4507                 }).unwrap()
4508         };
4509         nodes_0_deserialized = nodes_0_deserialized_tmp;
4510         assert!(nodes_0_read.is_empty());
4511
4512         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4513         nodes[0].node = &nodes_0_deserialized;
4514         check_added_monitors!(nodes[0], 1);
4515
4516         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4517
4518         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4519         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4520 }
4521
4522 #[test]
4523 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4524         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4525         let chanmon_cfgs = create_chanmon_cfgs(4);
4526         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4527         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4528         let logger: test_utils::TestLogger;
4529         let fee_estimator: test_utils::TestFeeEstimator;
4530         let persister: test_utils::TestPersister;
4531         let new_chain_monitor: test_utils::TestChainMonitor;
4532         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4533         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4534         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4535         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4536         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4537
4538         let mut node_0_stale_monitors_serialized = Vec::new();
4539         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
4540                 let mut writer = test_utils::TestVecWriter(Vec::new());
4541                 monitor.1.write(&mut writer).unwrap();
4542                 node_0_stale_monitors_serialized.push(writer.0);
4543         }
4544
4545         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4546
4547         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4548         let nodes_0_serialized = nodes[0].node.encode();
4549
4550         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4551         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4552         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4553         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4554
4555         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4556         // nodes[3])
4557         let mut node_0_monitors_serialized = Vec::new();
4558         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
4559                 let mut writer = test_utils::TestVecWriter(Vec::new());
4560                 monitor.1.write(&mut writer).unwrap();
4561                 node_0_monitors_serialized.push(writer.0);
4562         }
4563
4564         logger = test_utils::TestLogger::new();
4565         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4566         persister = test_utils::TestPersister::new();
4567         let keys_manager = &chanmon_cfgs[0].keys_manager;
4568         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4569         nodes[0].chain_monitor = &new_chain_monitor;
4570
4571
4572         let mut node_0_stale_monitors = Vec::new();
4573         for serialized in node_0_stale_monitors_serialized.iter() {
4574                 let mut read = &serialized[..];
4575                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, keys_manager).unwrap();
4576                 assert!(read.is_empty());
4577                 node_0_stale_monitors.push(monitor);
4578         }
4579
4580         let mut node_0_monitors = Vec::new();
4581         for serialized in node_0_monitors_serialized.iter() {
4582                 let mut read = &serialized[..];
4583                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, keys_manager).unwrap();
4584                 assert!(read.is_empty());
4585                 node_0_monitors.push(monitor);
4586         }
4587
4588         let mut nodes_0_read = &nodes_0_serialized[..];
4589         if let Err(msgs::DecodeError::InvalidValue) =
4590                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4591                 default_config: UserConfig::default(),
4592                 keys_manager,
4593                 fee_estimator: &fee_estimator,
4594                 chain_monitor: nodes[0].chain_monitor,
4595                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4596                 logger: &logger,
4597                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4598         }) { } else {
4599                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4600         };
4601
4602         let mut nodes_0_read = &nodes_0_serialized[..];
4603         let (_, nodes_0_deserialized_tmp) =
4604                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4605                 default_config: UserConfig::default(),
4606                 keys_manager,
4607                 fee_estimator: &fee_estimator,
4608                 chain_monitor: nodes[0].chain_monitor,
4609                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4610                 logger: &logger,
4611                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4612         }).unwrap();
4613         nodes_0_deserialized = nodes_0_deserialized_tmp;
4614         assert!(nodes_0_read.is_empty());
4615
4616         { // Channel close should result in a commitment tx and an HTLC tx
4617                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4618                 assert_eq!(txn.len(), 2);
4619                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4620                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4621         }
4622
4623         for monitor in node_0_monitors.drain(..) {
4624                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4625                 check_added_monitors!(nodes[0], 1);
4626         }
4627         nodes[0].node = &nodes_0_deserialized;
4628
4629         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4630         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4631         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4632         //... and we can even still claim the payment!
4633         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4634
4635         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4636         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4637         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4638         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4639         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4640         assert_eq!(msg_events.len(), 1);
4641         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4642                 match action {
4643                         &ErrorAction::SendErrorMessage { ref msg } => {
4644                                 assert_eq!(msg.channel_id, channel_id);
4645                         },
4646                         _ => panic!("Unexpected event!"),
4647                 }
4648         }
4649 }
4650
4651 macro_rules! check_spendable_outputs {
4652         ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4653                 {
4654                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4655                         let mut txn = Vec::new();
4656                         let mut all_outputs = Vec::new();
4657                         let secp_ctx = Secp256k1::new();
4658                         for event in events.drain(..) {
4659                                 match event {
4660                                         Event::SpendableOutputs { mut outputs } => {
4661                                                 for outp in outputs.drain(..) {
4662                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4663                                                         all_outputs.push(outp);
4664                                                 }
4665                                         },
4666                                         _ => panic!("Unexpected event"),
4667                                 };
4668                         }
4669                         if all_outputs.len() > 1 {
4670                                 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) {
4671                                         txn.push(tx);
4672                                 }
4673                         }
4674                         txn
4675                 }
4676         }
4677 }
4678
4679 #[test]
4680 fn test_claim_sizeable_push_msat() {
4681         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4682         let chanmon_cfgs = create_chanmon_cfgs(2);
4683         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4684         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4685         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4686
4687         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4688         nodes[1].node.force_close_channel(&chan.2).unwrap();
4689         check_closed_broadcast!(nodes[1], false);
4690         check_added_monitors!(nodes[1], 1);
4691         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4692         assert_eq!(node_txn.len(), 1);
4693         check_spends!(node_txn[0], chan.3);
4694         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
4695
4696         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4697         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4698         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4699
4700         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4701         assert_eq!(spend_txn.len(), 1);
4702         check_spends!(spend_txn[0], node_txn[0]);
4703 }
4704
4705 #[test]
4706 fn test_claim_on_remote_sizeable_push_msat() {
4707         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4708         // to_remote output is encumbered by a P2WPKH
4709         let chanmon_cfgs = create_chanmon_cfgs(2);
4710         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4711         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4712         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4713
4714         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4715         nodes[0].node.force_close_channel(&chan.2).unwrap();
4716         check_closed_broadcast!(nodes[0], false);
4717         check_added_monitors!(nodes[0], 1);
4718
4719         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4720         assert_eq!(node_txn.len(), 1);
4721         check_spends!(node_txn[0], chan.3);
4722         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
4723
4724         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4725         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4726         check_closed_broadcast!(nodes[1], false);
4727         check_added_monitors!(nodes[1], 1);
4728         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4729
4730         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4731         assert_eq!(spend_txn.len(), 1);
4732         check_spends!(spend_txn[0], node_txn[0]);
4733 }
4734
4735 #[test]
4736 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4737         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4738         // to_remote output is encumbered by a P2WPKH
4739
4740         let chanmon_cfgs = create_chanmon_cfgs(2);
4741         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4742         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4743         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4744
4745         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4746         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4747         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4748         assert_eq!(revoked_local_txn[0].input.len(), 1);
4749         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4750
4751         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4752         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4753         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4754         check_closed_broadcast!(nodes[1], false);
4755         check_added_monitors!(nodes[1], 1);
4756
4757         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4758         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4759         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4760         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4761
4762         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4763         assert_eq!(spend_txn.len(), 3);
4764         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4765         check_spends!(spend_txn[1], node_txn[0]);
4766         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4767 }
4768
4769 #[test]
4770 fn test_static_spendable_outputs_preimage_tx() {
4771         let chanmon_cfgs = create_chanmon_cfgs(2);
4772         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4773         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4774         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4775
4776         // Create some initial channels
4777         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4778
4779         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4780
4781         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4782         assert_eq!(commitment_tx[0].input.len(), 1);
4783         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4784
4785         // Settle A's commitment tx on B's chain
4786         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4787         assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4788         check_added_monitors!(nodes[1], 1);
4789         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4790         check_added_monitors!(nodes[1], 1);
4791         let events = nodes[1].node.get_and_clear_pending_msg_events();
4792         match events[0] {
4793                 MessageSendEvent::UpdateHTLCs { .. } => {},
4794                 _ => panic!("Unexpected event"),
4795         }
4796         match events[1] {
4797                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4798                 _ => panic!("Unexepected event"),
4799         }
4800
4801         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4802         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4803         assert_eq!(node_txn.len(), 3);
4804         check_spends!(node_txn[0], commitment_tx[0]);
4805         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4806         check_spends!(node_txn[1], chan_1.3);
4807         check_spends!(node_txn[2], node_txn[1]);
4808
4809         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4810         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4811         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4812
4813         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4814         assert_eq!(spend_txn.len(), 1);
4815         check_spends!(spend_txn[0], node_txn[0]);
4816 }
4817
4818 #[test]
4819 fn test_static_spendable_outputs_timeout_tx() {
4820         let chanmon_cfgs = create_chanmon_cfgs(2);
4821         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4822         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4823         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4824
4825         // Create some initial channels
4826         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4827
4828         // Rebalance the network a bit by relaying one payment through all the channels ...
4829         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4830
4831         let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4832
4833         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4834         assert_eq!(commitment_tx[0].input.len(), 1);
4835         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4836
4837         // Settle A's commitment tx on B' chain
4838         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4839         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4840         check_added_monitors!(nodes[1], 1);
4841         let events = nodes[1].node.get_and_clear_pending_msg_events();
4842         match events[0] {
4843                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4844                 _ => panic!("Unexpected event"),
4845         }
4846
4847         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4848         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4849         assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4850         check_spends!(node_txn[0],  commitment_tx[0].clone());
4851         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4852         check_spends!(node_txn[1], chan_1.3.clone());
4853         check_spends!(node_txn[2], node_txn[1]);
4854
4855         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4856         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4857         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4858         expect_payment_failed!(nodes[1], our_payment_hash, true);
4859
4860         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4861         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4862         check_spends!(spend_txn[0], commitment_tx[0]);
4863         check_spends!(spend_txn[1], node_txn[0]);
4864         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4865 }
4866
4867 #[test]
4868 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4869         let chanmon_cfgs = create_chanmon_cfgs(2);
4870         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4871         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4872         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4873
4874         // Create some initial channels
4875         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4876
4877         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4878         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4879         assert_eq!(revoked_local_txn[0].input.len(), 1);
4880         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4881
4882         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4883
4884         let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4885         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4886         check_closed_broadcast!(nodes[1], false);
4887         check_added_monitors!(nodes[1], 1);
4888
4889         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4890         assert_eq!(node_txn.len(), 2);
4891         assert_eq!(node_txn[0].input.len(), 2);
4892         check_spends!(node_txn[0], revoked_local_txn[0]);
4893
4894         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4895         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4896         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4897
4898         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4899         assert_eq!(spend_txn.len(), 1);
4900         check_spends!(spend_txn[0], node_txn[0]);
4901 }
4902
4903 #[test]
4904 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4905         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4906         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4907         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4908         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4909         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4910
4911         // Create some initial channels
4912         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4913
4914         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4915         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4916         assert_eq!(revoked_local_txn[0].input.len(), 1);
4917         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4918
4919         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4920
4921         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4922         // A will generate HTLC-Timeout from revoked commitment tx
4923         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4924         check_closed_broadcast!(nodes[0], false);
4925         check_added_monitors!(nodes[0], 1);
4926
4927         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4928         assert_eq!(revoked_htlc_txn.len(), 2);
4929         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4930         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4931         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4932         check_spends!(revoked_htlc_txn[1], chan_1.3);
4933
4934         // B will generate justice tx from A's revoked commitment/HTLC tx
4935         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
4936         check_closed_broadcast!(nodes[1], false);
4937         check_added_monitors!(nodes[1], 1);
4938
4939         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4940         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4941         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4942         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4943         // transactions next...
4944         assert_eq!(node_txn[0].input.len(), 3);
4945         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4946
4947         assert_eq!(node_txn[1].input.len(), 2);
4948         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4949         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4950                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4951         } else {
4952                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4953                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4954         }
4955
4956         assert_eq!(node_txn[2].input.len(), 1);
4957         check_spends!(node_txn[2], chan_1.3);
4958
4959         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4960         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
4961         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4962
4963         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4964         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4965         assert_eq!(spend_txn.len(), 1);
4966         assert_eq!(spend_txn[0].input.len(), 1);
4967         check_spends!(spend_txn[0], node_txn[1]);
4968 }
4969
4970 #[test]
4971 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4972         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4973         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4974         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4975         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4976         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4977
4978         // Create some initial channels
4979         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4980
4981         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4982         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4983         assert_eq!(revoked_local_txn[0].input.len(), 1);
4984         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4985
4986         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4987         assert_eq!(revoked_local_txn[0].output.len(), 2);
4988
4989         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4990
4991         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4992         // B will generate HTLC-Success from revoked commitment tx
4993         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4994         check_closed_broadcast!(nodes[1], false);
4995         check_added_monitors!(nodes[1], 1);
4996         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4997
4998         assert_eq!(revoked_htlc_txn.len(), 2);
4999         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5000         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5001         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5002
5003         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5004         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5005         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5006
5007         // A will generate justice tx from B's revoked commitment/HTLC tx
5008         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5009         check_closed_broadcast!(nodes[0], false);
5010         check_added_monitors!(nodes[0], 1);
5011
5012         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5013         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5014
5015         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5016         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5017         // transactions next...
5018         assert_eq!(node_txn[0].input.len(), 2);
5019         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5020         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5021                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5022         } else {
5023                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5024                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5025         }
5026
5027         assert_eq!(node_txn[1].input.len(), 1);
5028         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5029
5030         check_spends!(node_txn[2], chan_1.3);
5031
5032         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5033         connect_block(&nodes[0], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5034         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5035
5036         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5037         // didn't try to generate any new transactions.
5038
5039         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5040         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5041         assert_eq!(spend_txn.len(), 3);
5042         assert_eq!(spend_txn[0].input.len(), 1);
5043         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5044         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5045         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5046         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5047 }
5048
5049 #[test]
5050 fn test_onchain_to_onchain_claim() {
5051         // Test that in case of channel closure, we detect the state of output and claim HTLC
5052         // on downstream peer's remote commitment tx.
5053         // First, have C claim an HTLC against its own latest commitment transaction.
5054         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5055         // channel.
5056         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5057         // gets broadcast.
5058
5059         let chanmon_cfgs = create_chanmon_cfgs(3);
5060         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5061         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5062         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5063
5064         // Create some initial channels
5065         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5066         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5067
5068         // Rebalance the network a bit by relaying one payment through all the channels ...
5069         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5070         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5071
5072         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5073         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5074         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5075         check_spends!(commitment_tx[0], chan_2.3);
5076         nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5077         check_added_monitors!(nodes[2], 1);
5078         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5079         assert!(updates.update_add_htlcs.is_empty());
5080         assert!(updates.update_fail_htlcs.is_empty());
5081         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5082         assert!(updates.update_fail_malformed_htlcs.is_empty());
5083
5084         connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5085         check_closed_broadcast!(nodes[2], false);
5086         check_added_monitors!(nodes[2], 1);
5087
5088         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5089         assert_eq!(c_txn.len(), 3);
5090         assert_eq!(c_txn[0], c_txn[2]);
5091         assert_eq!(commitment_tx[0], c_txn[1]);
5092         check_spends!(c_txn[1], chan_2.3);
5093         check_spends!(c_txn[2], c_txn[1]);
5094         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5095         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5096         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5097         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5098
5099         // 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
5100         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5101         {
5102                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5103                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5104                 assert_eq!(b_txn.len(), 3);
5105                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5106                 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5107                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5108                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5109                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5110                 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5111                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5112                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5113                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5114                 b_txn.clear();
5115         }
5116         check_added_monitors!(nodes[1], 1);
5117         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5118         check_added_monitors!(nodes[1], 1);
5119         match msg_events[0] {
5120                 MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
5121                 _ => panic!("Unexpected event"),
5122         }
5123         match msg_events[1] {
5124                 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, .. } } => {
5125                         assert!(update_add_htlcs.is_empty());
5126                         assert!(update_fail_htlcs.is_empty());
5127                         assert_eq!(update_fulfill_htlcs.len(), 1);
5128                         assert!(update_fail_malformed_htlcs.is_empty());
5129                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5130                 },
5131                 _ => panic!("Unexpected event"),
5132         };
5133         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5134         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5135         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5136         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5137         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5138         assert_eq!(b_txn.len(), 3);
5139         check_spends!(b_txn[1], chan_1.3);
5140         check_spends!(b_txn[2], b_txn[1]);
5141         check_spends!(b_txn[0], commitment_tx[0]);
5142         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5143         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5144         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5145
5146         check_closed_broadcast!(nodes[1], false);
5147         check_added_monitors!(nodes[1], 1);
5148 }
5149
5150 #[test]
5151 fn test_duplicate_payment_hash_one_failure_one_success() {
5152         // Topology : A --> B --> C
5153         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5154         let chanmon_cfgs = create_chanmon_cfgs(3);
5155         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5156         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5157         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5158
5159         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5160         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5161
5162         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5163         *nodes[0].network_payment_count.borrow_mut() -= 1;
5164         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5165
5166         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5167         assert_eq!(commitment_txn[0].input.len(), 1);
5168         check_spends!(commitment_txn[0], chan_2.3);
5169
5170         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5171         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5172         check_closed_broadcast!(nodes[1], false);
5173         check_added_monitors!(nodes[1], 1);
5174
5175         let htlc_timeout_tx;
5176         { // Extract one of the two HTLC-Timeout transaction
5177                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5178                 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5179                 assert_eq!(node_txn.len(), 5);
5180                 check_spends!(node_txn[0], commitment_txn[0]);
5181                 assert_eq!(node_txn[0].input.len(), 1);
5182                 check_spends!(node_txn[1], commitment_txn[0]);
5183                 assert_eq!(node_txn[1].input.len(), 1);
5184                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5185                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5186                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5187                 check_spends!(node_txn[2], chan_2.3);
5188                 check_spends!(node_txn[3], node_txn[2]);
5189                 check_spends!(node_txn[4], node_txn[2]);
5190                 htlc_timeout_tx = node_txn[1].clone();
5191         }
5192
5193         nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5194         connect_block(&nodes[2], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5195         check_added_monitors!(nodes[2], 3);
5196         let events = nodes[2].node.get_and_clear_pending_msg_events();
5197         match events[0] {
5198                 MessageSendEvent::UpdateHTLCs { .. } => {},
5199                 _ => panic!("Unexpected event"),
5200         }
5201         match events[1] {
5202                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5203                 _ => panic!("Unexepected event"),
5204         }
5205         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5206         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)
5207         check_spends!(htlc_success_txn[2], chan_2.3);
5208         check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5209         check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5210         assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5211         assert_eq!(htlc_success_txn[0].input.len(), 1);
5212         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5213         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5214         assert_eq!(htlc_success_txn[1].input.len(), 1);
5215         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5216         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5217         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5218         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5219
5220         connect_block(&nodes[1], &Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5221         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
5222         expect_pending_htlcs_forwardable!(nodes[1]);
5223         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5224         assert!(htlc_updates.update_add_htlcs.is_empty());
5225         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5226         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5227         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5228         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5229         check_added_monitors!(nodes[1], 1);
5230
5231         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5232         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5233         {
5234                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5235                 let events = nodes[0].node.get_and_clear_pending_msg_events();
5236                 assert_eq!(events.len(), 1);
5237                 match events[0] {
5238                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
5239                         },
5240                         _ => { panic!("Unexpected event"); }
5241                 }
5242         }
5243         expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5244
5245         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5246         connect_block(&nodes[1], &Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5247         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5248         assert!(updates.update_add_htlcs.is_empty());
5249         assert!(updates.update_fail_htlcs.is_empty());
5250         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5251         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5252         assert!(updates.update_fail_malformed_htlcs.is_empty());
5253         check_added_monitors!(nodes[1], 1);
5254
5255         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5256         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5257
5258         let events = nodes[0].node.get_and_clear_pending_events();
5259         match events[0] {
5260                 Event::PaymentSent { ref payment_preimage } => {
5261                         assert_eq!(*payment_preimage, our_payment_preimage);
5262                 }
5263                 _ => panic!("Unexpected event"),
5264         }
5265 }
5266
5267 #[test]
5268 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5269         let chanmon_cfgs = create_chanmon_cfgs(2);
5270         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5271         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5272         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5273
5274         // Create some initial channels
5275         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5276
5277         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5278         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5279         assert_eq!(local_txn.len(), 1);
5280         assert_eq!(local_txn[0].input.len(), 1);
5281         check_spends!(local_txn[0], chan_1.3);
5282
5283         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5284         nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5285         check_added_monitors!(nodes[1], 1);
5286         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5287         connect_block(&nodes[1], &Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5288         check_added_monitors!(nodes[1], 1);
5289         let events = nodes[1].node.get_and_clear_pending_msg_events();
5290         match events[0] {
5291                 MessageSendEvent::UpdateHTLCs { .. } => {},
5292                 _ => panic!("Unexpected event"),
5293         }
5294         match events[1] {
5295                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5296                 _ => panic!("Unexepected event"),
5297         }
5298         let node_txn = {
5299                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5300                 assert_eq!(node_txn.len(), 3);
5301                 assert_eq!(node_txn[0], node_txn[2]);
5302                 assert_eq!(node_txn[1], local_txn[0]);
5303                 assert_eq!(node_txn[0].input.len(), 1);
5304                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5305                 check_spends!(node_txn[0], local_txn[0]);
5306                 vec![node_txn[0].clone()]
5307         };
5308
5309         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5310         connect_block(&nodes[1], &Block { header: header_201, txdata: node_txn.clone() }, 201);
5311         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5312
5313         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5314         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5315         assert_eq!(spend_txn.len(), 1);
5316         check_spends!(spend_txn[0], node_txn[0]);
5317 }
5318
5319 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5320         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5321         // unrevoked commitment transaction.
5322         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5323         // a remote RAA before they could be failed backwards (and combinations thereof).
5324         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5325         // use the same payment hashes.
5326         // Thus, we use a six-node network:
5327         //
5328         // A \         / E
5329         //    - C - D -
5330         // B /         \ F
5331         // And test where C fails back to A/B when D announces its latest commitment transaction
5332         let chanmon_cfgs = create_chanmon_cfgs(6);
5333         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5334         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5335         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5336         let logger = test_utils::TestLogger::new();
5337
5338         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5339         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5340         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5341         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5342         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5343
5344         // Rebalance and check output sanity...
5345         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5346         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5347         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5348
5349         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5350         // 0th HTLC:
5351         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
5352         // 1st HTLC:
5353         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
5354         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5355         let our_node_id = &nodes[1].node.get_our_node_id();
5356         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5357         // 2nd HTLC:
5358         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
5359         // 3rd HTLC:
5360         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
5361         // 4th HTLC:
5362         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5363         // 5th HTLC:
5364         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5365         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5366         // 6th HTLC:
5367         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5368         // 7th HTLC:
5369         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5370
5371         // 8th HTLC:
5372         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5373         // 9th HTLC:
5374         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5375         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
5376
5377         // 10th HTLC:
5378         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
5379         // 11th HTLC:
5380         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5381         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5382
5383         // Double-check that six of the new HTLC were added
5384         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5385         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5386         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5387         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5388
5389         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5390         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5391         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5392         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5393         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5394         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5395         check_added_monitors!(nodes[4], 0);
5396         expect_pending_htlcs_forwardable!(nodes[4]);
5397         check_added_monitors!(nodes[4], 1);
5398
5399         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5400         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5401         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5402         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5403         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5404         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5405
5406         // Fail 3rd below-dust and 7th above-dust HTLCs
5407         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5408         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5409         check_added_monitors!(nodes[5], 0);
5410         expect_pending_htlcs_forwardable!(nodes[5]);
5411         check_added_monitors!(nodes[5], 1);
5412
5413         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5414         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5415         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5416         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5417
5418         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5419
5420         expect_pending_htlcs_forwardable!(nodes[3]);
5421         check_added_monitors!(nodes[3], 1);
5422         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5423         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5424         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5425         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5426         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5427         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5428         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5429         if deliver_last_raa {
5430                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5431         } else {
5432                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5433         }
5434
5435         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5436         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5437         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5438         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5439         //
5440         // We now broadcast the latest commitment transaction, which *should* result in failures for
5441         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5442         // the non-broadcast above-dust HTLCs.
5443         //
5444         // Alternatively, we may broadcast the previous commitment transaction, which should only
5445         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5446         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5447
5448         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5449         if announce_latest {
5450                 connect_block(&nodes[2], &Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5451         } else {
5452                 connect_block(&nodes[2], &Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5453         }
5454         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1, 1, true,  header.block_hash());
5455         check_closed_broadcast!(nodes[2], false);
5456         expect_pending_htlcs_forwardable!(nodes[2]);
5457         check_added_monitors!(nodes[2], 3);
5458
5459         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5460         assert_eq!(cs_msgs.len(), 2);
5461         let mut a_done = false;
5462         for msg in cs_msgs {
5463                 match msg {
5464                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5465                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5466                                 // should be failed-backwards here.
5467                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5468                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5469                                         for htlc in &updates.update_fail_htlcs {
5470                                                 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 });
5471                                         }
5472                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5473                                         assert!(!a_done);
5474                                         a_done = true;
5475                                         &nodes[0]
5476                                 } else {
5477                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5478                                         for htlc in &updates.update_fail_htlcs {
5479                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5480                                         }
5481                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5482                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5483                                         &nodes[1]
5484                                 };
5485                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5486                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5487                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5488                                 if announce_latest {
5489                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5490                                         if *node_id == nodes[0].node.get_our_node_id() {
5491                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5492                                         }
5493                                 }
5494                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5495                         },
5496                         _ => panic!("Unexpected event"),
5497                 }
5498         }
5499
5500         let as_events = nodes[0].node.get_and_clear_pending_events();
5501         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5502         let mut as_failds = HashSet::new();
5503         for event in as_events.iter() {
5504                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5505                         assert!(as_failds.insert(*payment_hash));
5506                         if *payment_hash != payment_hash_2 {
5507                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5508                         } else {
5509                                 assert!(!rejected_by_dest);
5510                         }
5511                 } else { panic!("Unexpected event"); }
5512         }
5513         assert!(as_failds.contains(&payment_hash_1));
5514         assert!(as_failds.contains(&payment_hash_2));
5515         if announce_latest {
5516                 assert!(as_failds.contains(&payment_hash_3));
5517                 assert!(as_failds.contains(&payment_hash_5));
5518         }
5519         assert!(as_failds.contains(&payment_hash_6));
5520
5521         let bs_events = nodes[1].node.get_and_clear_pending_events();
5522         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5523         let mut bs_failds = HashSet::new();
5524         for event in bs_events.iter() {
5525                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5526                         assert!(bs_failds.insert(*payment_hash));
5527                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5528                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5529                         } else {
5530                                 assert!(!rejected_by_dest);
5531                         }
5532                 } else { panic!("Unexpected event"); }
5533         }
5534         assert!(bs_failds.contains(&payment_hash_1));
5535         assert!(bs_failds.contains(&payment_hash_2));
5536         if announce_latest {
5537                 assert!(bs_failds.contains(&payment_hash_4));
5538         }
5539         assert!(bs_failds.contains(&payment_hash_5));
5540
5541         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5542         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5543         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5544         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5545         // PaymentFailureNetworkUpdates.
5546         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5547         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5548         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5549         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5550         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5551                 match event {
5552                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5553                         _ => panic!("Unexpected event"),
5554                 }
5555         }
5556 }
5557
5558 #[test]
5559 fn test_fail_backwards_latest_remote_announce_a() {
5560         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5561 }
5562
5563 #[test]
5564 fn test_fail_backwards_latest_remote_announce_b() {
5565         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5566 }
5567
5568 #[test]
5569 fn test_fail_backwards_previous_remote_announce() {
5570         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5571         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5572         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5573 }
5574
5575 #[test]
5576 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5577         let chanmon_cfgs = create_chanmon_cfgs(2);
5578         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5579         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5580         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5581
5582         // Create some initial channels
5583         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5584
5585         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5586         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5587         assert_eq!(local_txn[0].input.len(), 1);
5588         check_spends!(local_txn[0], chan_1.3);
5589
5590         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5591         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5592         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5593         check_closed_broadcast!(nodes[0], false);
5594         check_added_monitors!(nodes[0], 1);
5595
5596         let htlc_timeout = {
5597                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5598                 assert_eq!(node_txn[0].input.len(), 1);
5599                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5600                 check_spends!(node_txn[0], local_txn[0]);
5601                 node_txn[0].clone()
5602         };
5603
5604         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5605         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5606         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5607         expect_payment_failed!(nodes[0], our_payment_hash, true);
5608
5609         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5610         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5611         assert_eq!(spend_txn.len(), 3);
5612         check_spends!(spend_txn[0], local_txn[0]);
5613         check_spends!(spend_txn[1], htlc_timeout);
5614         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5615 }
5616
5617 #[test]
5618 fn test_key_derivation_params() {
5619         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5620         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5621         // let us re-derive the channel key set to then derive a delayed_payment_key.
5622
5623         let chanmon_cfgs = create_chanmon_cfgs(3);
5624
5625         // We manually create the node configuration to backup the seed.
5626         let seed = [42; 32];
5627         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5628         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);
5629         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 };
5630         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5631         node_cfgs.remove(0);
5632         node_cfgs.insert(0, node);
5633
5634         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5635         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5636
5637         // Create some initial channels
5638         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5639         // for node 0
5640         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5641         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5642         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5643
5644         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5645         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5646         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5647         assert_eq!(local_txn_1[0].input.len(), 1);
5648         check_spends!(local_txn_1[0], chan_1.3);
5649
5650         // We check funding pubkey are unique
5651         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]));
5652         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]));
5653         if from_0_funding_key_0 == from_1_funding_key_0
5654             || from_0_funding_key_0 == from_1_funding_key_1
5655             || from_0_funding_key_1 == from_1_funding_key_0
5656             || from_0_funding_key_1 == from_1_funding_key_1 {
5657                 panic!("Funding pubkeys aren't unique");
5658         }
5659
5660         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5661         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5662         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn_1[0].clone()] }, 200);
5663         check_closed_broadcast!(nodes[0], false);
5664         check_added_monitors!(nodes[0], 1);
5665
5666         let htlc_timeout = {
5667                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5668                 assert_eq!(node_txn[0].input.len(), 1);
5669                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5670                 check_spends!(node_txn[0], local_txn_1[0]);
5671                 node_txn[0].clone()
5672         };
5673
5674         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5675         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5676         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5677         expect_payment_failed!(nodes[0], our_payment_hash, true);
5678
5679         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5680         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5681         let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5682         assert_eq!(spend_txn.len(), 3);
5683         check_spends!(spend_txn[0], local_txn_1[0]);
5684         check_spends!(spend_txn[1], htlc_timeout);
5685         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5686 }
5687
5688 #[test]
5689 fn test_static_output_closing_tx() {
5690         let chanmon_cfgs = create_chanmon_cfgs(2);
5691         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5692         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5693         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5694
5695         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5696
5697         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5698         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5699
5700         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5701         connect_block(&nodes[0], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5702         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5703
5704         let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5705         assert_eq!(spend_txn.len(), 1);
5706         check_spends!(spend_txn[0], closing_tx);
5707
5708         connect_block(&nodes[1], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5709         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5710
5711         let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5712         assert_eq!(spend_txn.len(), 1);
5713         check_spends!(spend_txn[0], closing_tx);
5714 }
5715
5716 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5717         let chanmon_cfgs = create_chanmon_cfgs(2);
5718         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5719         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5720         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5721         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5722
5723         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5724
5725         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5726         // present in B's local commitment transaction, but none of A's commitment transactions.
5727         assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5728         check_added_monitors!(nodes[1], 1);
5729
5730         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5731         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5732         let events = nodes[0].node.get_and_clear_pending_events();
5733         assert_eq!(events.len(), 1);
5734         match events[0] {
5735                 Event::PaymentSent { payment_preimage } => {
5736                         assert_eq!(payment_preimage, our_payment_preimage);
5737                 },
5738                 _ => panic!("Unexpected event"),
5739         }
5740
5741         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5742         check_added_monitors!(nodes[0], 1);
5743         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5744         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5745         check_added_monitors!(nodes[1], 1);
5746
5747         let mut block = Block {
5748                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5749                 txdata: vec![],
5750         };
5751         for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5752                 connect_block(&nodes[1], &block, i);
5753                 block.header.prev_blockhash = block.block_hash();
5754         }
5755         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5756         check_closed_broadcast!(nodes[1], false);
5757         check_added_monitors!(nodes[1], 1);
5758 }
5759
5760 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5761         let chanmon_cfgs = create_chanmon_cfgs(2);
5762         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5763         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5764         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5765         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5766         let logger = test_utils::TestLogger::new();
5767
5768         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5769         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5770         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, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV, &logger).unwrap();
5771         nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5772         check_added_monitors!(nodes[0], 1);
5773
5774         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5775
5776         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5777         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5778         // to "time out" the HTLC.
5779
5780         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5781
5782         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5783                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()}, i);
5784                 header.prev_blockhash = header.block_hash();
5785         }
5786         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5787         check_closed_broadcast!(nodes[0], false);
5788         check_added_monitors!(nodes[0], 1);
5789 }
5790
5791 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5792         let chanmon_cfgs = create_chanmon_cfgs(3);
5793         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5794         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5795         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5796         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5797
5798         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5799         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5800         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5801         // actually revoked.
5802         let htlc_value = if use_dust { 50000 } else { 3000000 };
5803         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5804         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5805         expect_pending_htlcs_forwardable!(nodes[1]);
5806         check_added_monitors!(nodes[1], 1);
5807
5808         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5809         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5810         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5811         check_added_monitors!(nodes[0], 1);
5812         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5813         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5814         check_added_monitors!(nodes[1], 1);
5815         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5816         check_added_monitors!(nodes[1], 1);
5817         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5818
5819         if check_revoke_no_close {
5820                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5821                 check_added_monitors!(nodes[0], 1);
5822         }
5823
5824         let mut block = Block {
5825                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5826                 txdata: vec![],
5827         };
5828         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5829                 connect_block(&nodes[0], &block, i);
5830                 block.header.prev_blockhash = block.block_hash();
5831         }
5832         if !check_revoke_no_close {
5833                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5834                 check_closed_broadcast!(nodes[0], false);
5835                 check_added_monitors!(nodes[0], 1);
5836         } else {
5837                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5838         }
5839 }
5840
5841 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5842 // There are only a few cases to test here:
5843 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5844 //    broadcastable commitment transactions result in channel closure,
5845 //  * its included in an unrevoked-but-previous remote commitment transaction,
5846 //  * its included in the latest remote or local commitment transactions.
5847 // We test each of the three possible commitment transactions individually and use both dust and
5848 // non-dust HTLCs.
5849 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5850 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5851 // tested for at least one of the cases in other tests.
5852 #[test]
5853 fn htlc_claim_single_commitment_only_a() {
5854         do_htlc_claim_local_commitment_only(true);
5855         do_htlc_claim_local_commitment_only(false);
5856
5857         do_htlc_claim_current_remote_commitment_only(true);
5858         do_htlc_claim_current_remote_commitment_only(false);
5859 }
5860
5861 #[test]
5862 fn htlc_claim_single_commitment_only_b() {
5863         do_htlc_claim_previous_remote_commitment_only(true, false);
5864         do_htlc_claim_previous_remote_commitment_only(false, false);
5865         do_htlc_claim_previous_remote_commitment_only(true, true);
5866         do_htlc_claim_previous_remote_commitment_only(false, true);
5867 }
5868
5869 #[test]
5870 #[should_panic]
5871 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5872         let chanmon_cfgs = create_chanmon_cfgs(2);
5873         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5874         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5875         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5876         //Force duplicate channel ids
5877         for node in nodes.iter() {
5878                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5879         }
5880
5881         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5882         let channel_value_satoshis=10000;
5883         let push_msat=10001;
5884         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5885         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5886         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5887
5888         //Create a second channel with a channel_id collision
5889         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5890 }
5891
5892 #[test]
5893 fn bolt2_open_channel_sending_node_checks_part2() {
5894         let chanmon_cfgs = create_chanmon_cfgs(2);
5895         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5896         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5897         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5898
5899         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5900         let channel_value_satoshis=2^24;
5901         let push_msat=10001;
5902         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5903
5904         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5905         let channel_value_satoshis=10000;
5906         // Test when push_msat is equal to 1000 * funding_satoshis.
5907         let push_msat=1000*channel_value_satoshis+1;
5908         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5909
5910         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5911         let channel_value_satoshis=10000;
5912         let push_msat=10001;
5913         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
5914         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5915         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5916
5917         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5918         // 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
5919         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5920
5921         // 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.
5922         assert!(BREAKDOWN_TIMEOUT>0);
5923         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5924
5925         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5926         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5927         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5928
5929         // 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.
5930         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5931         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5932         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5933         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5934         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5935 }
5936
5937 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5938 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5939 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5940 // is no longer affordable once it's freed.
5941 #[test]
5942 fn test_fail_holding_cell_htlc_upon_free() {
5943         let chanmon_cfgs = create_chanmon_cfgs(2);
5944         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5945         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5946         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5947         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5948         let logger = test_utils::TestLogger::new();
5949
5950         // First nodes[0] generates an update_fee, setting the channel's
5951         // pending_update_fee.
5952         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
5953         check_added_monitors!(nodes[0], 1);
5954
5955         let events = nodes[0].node.get_and_clear_pending_msg_events();
5956         assert_eq!(events.len(), 1);
5957         let (update_msg, commitment_signed) = match events[0] {
5958                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5959                         (update_fee.as_ref(), commitment_signed)
5960                 },
5961                 _ => panic!("Unexpected event"),
5962         };
5963
5964         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5965
5966         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5967         let channel_reserve = chan_stat.channel_reserve_msat;
5968         let feerate = get_feerate!(nodes[0], chan.2);
5969
5970         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5971         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5972         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5973         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5974         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, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
5975
5976         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5977         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5978         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5979         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5980
5981         // Flush the pending fee update.
5982         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5983         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5984         check_added_monitors!(nodes[1], 1);
5985         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5986         check_added_monitors!(nodes[0], 1);
5987
5988         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5989         // HTLC, but now that the fee has been raised the payment will now fail, causing
5990         // us to surface its failure to the user.
5991         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5992         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5993         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
5994         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);
5995         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5996
5997         // Check that the payment failed to be sent out.
5998         let events = nodes[0].node.get_and_clear_pending_events();
5999         assert_eq!(events.len(), 1);
6000         match &events[0] {
6001                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6002                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6003                         assert_eq!(*rejected_by_dest, false);
6004                         assert_eq!(*error_code, None);
6005                         assert_eq!(*error_data, None);
6006                 },
6007                 _ => panic!("Unexpected event"),
6008         }
6009 }
6010
6011 // Test that if multiple HTLCs are released from the holding cell and one is
6012 // valid but the other is no longer valid upon release, the valid HTLC can be
6013 // successfully completed while the other one fails as expected.
6014 #[test]
6015 fn test_free_and_fail_holding_cell_htlcs() {
6016         let chanmon_cfgs = create_chanmon_cfgs(2);
6017         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6018         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6019         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6020         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6021         let logger = test_utils::TestLogger::new();
6022
6023         // First nodes[0] generates an update_fee, setting the channel's
6024         // pending_update_fee.
6025         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6026         check_added_monitors!(nodes[0], 1);
6027
6028         let events = nodes[0].node.get_and_clear_pending_msg_events();
6029         assert_eq!(events.len(), 1);
6030         let (update_msg, commitment_signed) = match events[0] {
6031                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6032                         (update_fee.as_ref(), commitment_signed)
6033                 },
6034                 _ => panic!("Unexpected event"),
6035         };
6036
6037         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6038
6039         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6040         let channel_reserve = chan_stat.channel_reserve_msat;
6041         let feerate = get_feerate!(nodes[0], chan.2);
6042
6043         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6044         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6045         let amt_1 = 20000;
6046         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6047         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6048         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6049         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, &[], amt_1, TEST_FINAL_CLTV, &logger).unwrap();
6050         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, &[], amt_2, TEST_FINAL_CLTV, &logger).unwrap();
6051
6052         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6053         nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6054         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6055         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6056         nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6057         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6058         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6059
6060         // Flush the pending fee update.
6061         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6062         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6063         check_added_monitors!(nodes[1], 1);
6064         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6065         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6066         check_added_monitors!(nodes[0], 2);
6067
6068         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6069         // but now that the fee has been raised the second payment will now fail, causing us
6070         // to surface its failure to the user. The first payment should succeed.
6071         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6072         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6073         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6074         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);
6075         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6076
6077         // Check that the second payment failed to be sent out.
6078         let events = nodes[0].node.get_and_clear_pending_events();
6079         assert_eq!(events.len(), 1);
6080         match &events[0] {
6081                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6082                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6083                         assert_eq!(*rejected_by_dest, false);
6084                         assert_eq!(*error_code, None);
6085                         assert_eq!(*error_data, None);
6086                 },
6087                 _ => panic!("Unexpected event"),
6088         }
6089
6090         // Complete the first payment and the RAA from the fee update.
6091         let (payment_event, send_raa_event) = {
6092                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6093                 assert_eq!(msgs.len(), 2);
6094                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6095         };
6096         let raa = match send_raa_event {
6097                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6098                 _ => panic!("Unexpected event"),
6099         };
6100         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6101         check_added_monitors!(nodes[1], 1);
6102         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6103         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6104         let events = nodes[1].node.get_and_clear_pending_events();
6105         assert_eq!(events.len(), 1);
6106         match events[0] {
6107                 Event::PendingHTLCsForwardable { .. } => {},
6108                 _ => panic!("Unexpected event"),
6109         }
6110         nodes[1].node.process_pending_htlc_forwards();
6111         let events = nodes[1].node.get_and_clear_pending_events();
6112         assert_eq!(events.len(), 1);
6113         match events[0] {
6114                 Event::PaymentReceived { .. } => {},
6115                 _ => panic!("Unexpected event"),
6116         }
6117         nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6118         check_added_monitors!(nodes[1], 1);
6119         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6120         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6121         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6122         let events = nodes[0].node.get_and_clear_pending_events();
6123         assert_eq!(events.len(), 1);
6124         match events[0] {
6125                 Event::PaymentSent { ref payment_preimage } => {
6126                         assert_eq!(*payment_preimage, payment_preimage_1);
6127                 }
6128                 _ => panic!("Unexpected event"),
6129         }
6130 }
6131
6132 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6133 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6134 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6135 // once it's freed.
6136 #[test]
6137 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6138         let chanmon_cfgs = create_chanmon_cfgs(3);
6139         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6140         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6141         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6142         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6143         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6144         let logger = test_utils::TestLogger::new();
6145
6146         // First nodes[1] generates an update_fee, setting the channel's
6147         // pending_update_fee.
6148         nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6149         check_added_monitors!(nodes[1], 1);
6150
6151         let events = nodes[1].node.get_and_clear_pending_msg_events();
6152         assert_eq!(events.len(), 1);
6153         let (update_msg, commitment_signed) = match events[0] {
6154                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6155                         (update_fee.as_ref(), commitment_signed)
6156                 },
6157                 _ => panic!("Unexpected event"),
6158         };
6159
6160         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6161
6162         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6163         let channel_reserve = chan_stat.channel_reserve_msat;
6164         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6165
6166         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6167         let feemsat = 239;
6168         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6169         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6170         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6171         let payment_event = {
6172                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6173                 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, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6174                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6175                 check_added_monitors!(nodes[0], 1);
6176
6177                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6178                 assert_eq!(events.len(), 1);
6179
6180                 SendEvent::from_event(events.remove(0))
6181         };
6182         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6183         check_added_monitors!(nodes[1], 0);
6184         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6185         expect_pending_htlcs_forwardable!(nodes[1]);
6186
6187         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6188         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6189
6190         // Flush the pending fee update.
6191         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6192         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6193         check_added_monitors!(nodes[2], 1);
6194         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6195         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6196         check_added_monitors!(nodes[1], 2);
6197
6198         // A final RAA message is generated to finalize the fee update.
6199         let events = nodes[1].node.get_and_clear_pending_msg_events();
6200         assert_eq!(events.len(), 1);
6201
6202         let raa_msg = match &events[0] {
6203                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6204                         msg.clone()
6205                 },
6206                 _ => panic!("Unexpected event"),
6207         };
6208
6209         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6210         check_added_monitors!(nodes[2], 1);
6211         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6212
6213         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6214         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6215         assert_eq!(process_htlc_forwards_event.len(), 1);
6216         match &process_htlc_forwards_event[0] {
6217                 &Event::PendingHTLCsForwardable { .. } => {},
6218                 _ => panic!("Unexpected event"),
6219         }
6220
6221         // In response, we call ChannelManager's process_pending_htlc_forwards
6222         nodes[1].node.process_pending_htlc_forwards();
6223         check_added_monitors!(nodes[1], 1);
6224
6225         // This causes the HTLC to be failed backwards.
6226         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6227         assert_eq!(fail_event.len(), 1);
6228         let (fail_msg, commitment_signed) = match &fail_event[0] {
6229                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6230                         assert_eq!(updates.update_add_htlcs.len(), 0);
6231                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6232                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6233                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6234                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6235                 },
6236                 _ => panic!("Unexpected event"),
6237         };
6238
6239         // Pass the failure messages back to nodes[0].
6240         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6241         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6242
6243         // Complete the HTLC failure+removal process.
6244         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6245         check_added_monitors!(nodes[0], 1);
6246         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6247         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6248         check_added_monitors!(nodes[1], 2);
6249         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6250         assert_eq!(final_raa_event.len(), 1);
6251         let raa = match &final_raa_event[0] {
6252                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6253                 _ => panic!("Unexpected event"),
6254         };
6255         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6256         let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6257         assert_eq!(fail_msg_event.len(), 1);
6258         match &fail_msg_event[0] {
6259                 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6260                 _ => panic!("Unexpected event"),
6261         }
6262         let failure_event = nodes[0].node.get_and_clear_pending_events();
6263         assert_eq!(failure_event.len(), 1);
6264         match &failure_event[0] {
6265                 &Event::PaymentFailed { rejected_by_dest, .. } => {
6266                         assert!(!rejected_by_dest);
6267                 },
6268                 _ => panic!("Unexpected event"),
6269         }
6270         check_added_monitors!(nodes[0], 1);
6271 }
6272
6273 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6274 // 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.
6275 //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.
6276
6277 #[test]
6278 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6279         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6280         let chanmon_cfgs = create_chanmon_cfgs(2);
6281         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6282         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6283         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6284         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6285
6286         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6287         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6288         let logger = test_utils::TestLogger::new();
6289         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, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6290         route.paths[0][0].fee_msat = 100;
6291
6292         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6293                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6294         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6295         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6296 }
6297
6298 #[test]
6299 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6300         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6301         let chanmon_cfgs = create_chanmon_cfgs(2);
6302         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6303         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6304         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6305         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6306         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6307
6308         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6309         let logger = test_utils::TestLogger::new();
6310         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, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6311         route.paths[0][0].fee_msat = 0;
6312         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6313                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6314
6315         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6316         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6317 }
6318
6319 #[test]
6320 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6321         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6322         let chanmon_cfgs = create_chanmon_cfgs(2);
6323         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6324         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6325         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6326         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6327
6328         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6329         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6330         let logger = test_utils::TestLogger::new();
6331         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, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6332         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6333         check_added_monitors!(nodes[0], 1);
6334         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6335         updates.update_add_htlcs[0].amount_msat = 0;
6336
6337         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6338         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6339         check_closed_broadcast!(nodes[1], true).unwrap();
6340         check_added_monitors!(nodes[1], 1);
6341 }
6342
6343 #[test]
6344 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6345         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6346         //It is enforced when constructing a route.
6347         let chanmon_cfgs = create_chanmon_cfgs(2);
6348         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6349         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6350         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6351         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::known(), InitFeatures::known());
6352         let logger = test_utils::TestLogger::new();
6353
6354         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6355
6356         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6357         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, &[], 100000000, 500000001, &logger).unwrap();
6358         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6359                 assert_eq!(err, &"Channel CLTV overflowed?"));
6360 }
6361
6362 #[test]
6363 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6364         //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.
6365         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6366         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6367         let chanmon_cfgs = create_chanmon_cfgs(2);
6368         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6369         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6370         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6371         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6372         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6373
6374         let logger = test_utils::TestLogger::new();
6375         for i in 0..max_accepted_htlcs {
6376                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6377                 let payment_event = {
6378                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6379                         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, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6380                         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6381                         check_added_monitors!(nodes[0], 1);
6382
6383                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6384                         assert_eq!(events.len(), 1);
6385                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6386                                 assert_eq!(htlcs[0].htlc_id, i);
6387                         } else {
6388                                 assert!(false);
6389                         }
6390                         SendEvent::from_event(events.remove(0))
6391                 };
6392                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6393                 check_added_monitors!(nodes[1], 0);
6394                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6395
6396                 expect_pending_htlcs_forwardable!(nodes[1]);
6397                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6398         }
6399         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6400         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6401         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, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6402         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6403                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6404
6405         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6406         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6407 }
6408
6409 #[test]
6410 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6411         //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.
6412         let chanmon_cfgs = create_chanmon_cfgs(2);
6413         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6414         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6415         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6416         let channel_value = 100000;
6417         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6418         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6419
6420         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6421
6422         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6423         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6424         let logger = test_utils::TestLogger::new();
6425         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, &[], max_in_flight+1, TEST_FINAL_CLTV, &logger).unwrap();
6426         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6427                 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)));
6428
6429         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6430         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);
6431
6432         send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6433 }
6434
6435 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6436 #[test]
6437 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6438         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6439         let chanmon_cfgs = create_chanmon_cfgs(2);
6440         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6441         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6442         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6443         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6444         let htlc_minimum_msat: u64;
6445         {
6446                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6447                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6448                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6449         }
6450
6451         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6452         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6453         let logger = test_utils::TestLogger::new();
6454         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, &[], htlc_minimum_msat, TEST_FINAL_CLTV, &logger).unwrap();
6455         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6456         check_added_monitors!(nodes[0], 1);
6457         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6458         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6459         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6460         assert!(nodes[1].node.list_channels().is_empty());
6461         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6462         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()));
6463         check_added_monitors!(nodes[1], 1);
6464 }
6465
6466 #[test]
6467 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6468         //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
6469         let chanmon_cfgs = create_chanmon_cfgs(2);
6470         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6471         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6472         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6473         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6474         let logger = test_utils::TestLogger::new();
6475
6476         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6477         let channel_reserve = chan_stat.channel_reserve_msat;
6478         let feerate = get_feerate!(nodes[0], chan.2);
6479         // The 2* and +1 are for the fee spike reserve.
6480         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6481
6482         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6483         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6484         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6485         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, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6486         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6487         check_added_monitors!(nodes[0], 1);
6488         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6489
6490         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6491         // at this time channel-initiatee receivers are not required to enforce that senders
6492         // respect the fee_spike_reserve.
6493         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6494         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6495
6496         assert!(nodes[1].node.list_channels().is_empty());
6497         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6498         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6499         check_added_monitors!(nodes[1], 1);
6500 }
6501
6502 #[test]
6503 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6504         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6505         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6506         let chanmon_cfgs = create_chanmon_cfgs(2);
6507         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6508         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6509         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6510         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6511         let logger = test_utils::TestLogger::new();
6512
6513         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6514         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6515
6516         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6517         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, &[], 3999999, TEST_FINAL_CLTV, &logger).unwrap();
6518
6519         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6520         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6521         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6522         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6523
6524         let mut msg = msgs::UpdateAddHTLC {
6525                 channel_id: chan.2,
6526                 htlc_id: 0,
6527                 amount_msat: 1000,
6528                 payment_hash: our_payment_hash,
6529                 cltv_expiry: htlc_cltv,
6530                 onion_routing_packet: onion_packet.clone(),
6531         };
6532
6533         for i in 0..super::channel::OUR_MAX_HTLCS {
6534                 msg.htlc_id = i as u64;
6535                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6536         }
6537         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6538         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6539
6540         assert!(nodes[1].node.list_channels().is_empty());
6541         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6542         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6543         check_added_monitors!(nodes[1], 1);
6544 }
6545
6546 #[test]
6547 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6548         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6549         let chanmon_cfgs = create_chanmon_cfgs(2);
6550         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6551         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6552         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6553         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6554         let logger = test_utils::TestLogger::new();
6555
6556         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6557         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6558         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, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6559         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6560         check_added_monitors!(nodes[0], 1);
6561         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6562         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6563         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6564
6565         assert!(nodes[1].node.list_channels().is_empty());
6566         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6567         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6568         check_added_monitors!(nodes[1], 1);
6569 }
6570
6571 #[test]
6572 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6573         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6574         let chanmon_cfgs = create_chanmon_cfgs(2);
6575         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6576         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6577         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6578         let logger = test_utils::TestLogger::new();
6579
6580         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6581         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6582         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6583         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, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6584         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6585         check_added_monitors!(nodes[0], 1);
6586         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6587         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6588         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6589
6590         assert!(nodes[1].node.list_channels().is_empty());
6591         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6592         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6593         check_added_monitors!(nodes[1], 1);
6594 }
6595
6596 #[test]
6597 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6598         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6599         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6600         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6601         let chanmon_cfgs = create_chanmon_cfgs(2);
6602         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6603         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6604         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6605         let logger = test_utils::TestLogger::new();
6606
6607         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6608         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6609         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6610         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, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6611         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6612         check_added_monitors!(nodes[0], 1);
6613         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6614         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6615
6616         //Disconnect and Reconnect
6617         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6618         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6619         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6620         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6621         assert_eq!(reestablish_1.len(), 1);
6622         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6623         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6624         assert_eq!(reestablish_2.len(), 1);
6625         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6626         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6627         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6628         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6629
6630         //Resend HTLC
6631         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6632         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6633         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6634         check_added_monitors!(nodes[1], 1);
6635         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6636
6637         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6638
6639         assert!(nodes[1].node.list_channels().is_empty());
6640         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6641         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6642         check_added_monitors!(nodes[1], 1);
6643 }
6644
6645 #[test]
6646 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6647         //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.
6648
6649         let chanmon_cfgs = create_chanmon_cfgs(2);
6650         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6651         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6652         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6653         let logger = test_utils::TestLogger::new();
6654         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6655         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6656         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6657         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, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6658         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6659
6660         check_added_monitors!(nodes[0], 1);
6661         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6662         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6663
6664         let update_msg = msgs::UpdateFulfillHTLC{
6665                 channel_id: chan.2,
6666                 htlc_id: 0,
6667                 payment_preimage: our_payment_preimage,
6668         };
6669
6670         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6671
6672         assert!(nodes[0].node.list_channels().is_empty());
6673         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6674         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()));
6675         check_added_monitors!(nodes[0], 1);
6676 }
6677
6678 #[test]
6679 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6680         //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.
6681
6682         let chanmon_cfgs = create_chanmon_cfgs(2);
6683         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6684         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6685         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6686         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6687         let logger = test_utils::TestLogger::new();
6688
6689         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6690         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6691         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, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6692         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6693         check_added_monitors!(nodes[0], 1);
6694         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6695         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6696
6697         let update_msg = msgs::UpdateFailHTLC{
6698                 channel_id: chan.2,
6699                 htlc_id: 0,
6700                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6701         };
6702
6703         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6704
6705         assert!(nodes[0].node.list_channels().is_empty());
6706         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6707         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()));
6708         check_added_monitors!(nodes[0], 1);
6709 }
6710
6711 #[test]
6712 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6713         //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.
6714
6715         let chanmon_cfgs = create_chanmon_cfgs(2);
6716         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6717         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6718         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6719         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6720         let logger = test_utils::TestLogger::new();
6721
6722         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6723         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6724         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, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6725         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6726         check_added_monitors!(nodes[0], 1);
6727         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6728         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6729
6730         let update_msg = msgs::UpdateFailMalformedHTLC{
6731                 channel_id: chan.2,
6732                 htlc_id: 0,
6733                 sha256_of_onion: [1; 32],
6734                 failure_code: 0x8000,
6735         };
6736
6737         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6738
6739         assert!(nodes[0].node.list_channels().is_empty());
6740         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6741         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()));
6742         check_added_monitors!(nodes[0], 1);
6743 }
6744
6745 #[test]
6746 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6747         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6748
6749         let chanmon_cfgs = create_chanmon_cfgs(2);
6750         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6751         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6752         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6753         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6754
6755         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6756
6757         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6758         check_added_monitors!(nodes[1], 1);
6759
6760         let events = nodes[1].node.get_and_clear_pending_msg_events();
6761         assert_eq!(events.len(), 1);
6762         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6763                 match events[0] {
6764                         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, .. } } => {
6765                                 assert!(update_add_htlcs.is_empty());
6766                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6767                                 assert!(update_fail_htlcs.is_empty());
6768                                 assert!(update_fail_malformed_htlcs.is_empty());
6769                                 assert!(update_fee.is_none());
6770                                 update_fulfill_htlcs[0].clone()
6771                         },
6772                         _ => panic!("Unexpected event"),
6773                 }
6774         };
6775
6776         update_fulfill_msg.htlc_id = 1;
6777
6778         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6779
6780         assert!(nodes[0].node.list_channels().is_empty());
6781         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6782         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6783         check_added_monitors!(nodes[0], 1);
6784 }
6785
6786 #[test]
6787 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6788         //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.
6789
6790         let chanmon_cfgs = create_chanmon_cfgs(2);
6791         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6792         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6793         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6794         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6795
6796         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6797
6798         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6799         check_added_monitors!(nodes[1], 1);
6800
6801         let events = nodes[1].node.get_and_clear_pending_msg_events();
6802         assert_eq!(events.len(), 1);
6803         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6804                 match events[0] {
6805                         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, .. } } => {
6806                                 assert!(update_add_htlcs.is_empty());
6807                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6808                                 assert!(update_fail_htlcs.is_empty());
6809                                 assert!(update_fail_malformed_htlcs.is_empty());
6810                                 assert!(update_fee.is_none());
6811                                 update_fulfill_htlcs[0].clone()
6812                         },
6813                         _ => panic!("Unexpected event"),
6814                 }
6815         };
6816
6817         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6818
6819         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6820
6821         assert!(nodes[0].node.list_channels().is_empty());
6822         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6823         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6824         check_added_monitors!(nodes[0], 1);
6825 }
6826
6827 #[test]
6828 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6829         //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.
6830
6831         let chanmon_cfgs = create_chanmon_cfgs(2);
6832         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6833         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6834         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6835         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6836         let logger = test_utils::TestLogger::new();
6837
6838         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6839         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6840         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, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6841         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6842         check_added_monitors!(nodes[0], 1);
6843
6844         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6845         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6846
6847         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6848         check_added_monitors!(nodes[1], 0);
6849         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6850
6851         let events = nodes[1].node.get_and_clear_pending_msg_events();
6852
6853         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6854                 match events[0] {
6855                         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, .. } } => {
6856                                 assert!(update_add_htlcs.is_empty());
6857                                 assert!(update_fulfill_htlcs.is_empty());
6858                                 assert!(update_fail_htlcs.is_empty());
6859                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6860                                 assert!(update_fee.is_none());
6861                                 update_fail_malformed_htlcs[0].clone()
6862                         },
6863                         _ => panic!("Unexpected event"),
6864                 }
6865         };
6866         update_msg.failure_code &= !0x8000;
6867         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6868
6869         assert!(nodes[0].node.list_channels().is_empty());
6870         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6871         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6872         check_added_monitors!(nodes[0], 1);
6873 }
6874
6875 #[test]
6876 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6877         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6878         //    * 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.
6879
6880         let chanmon_cfgs = create_chanmon_cfgs(3);
6881         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6882         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6883         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6884         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6885         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6886         let logger = test_utils::TestLogger::new();
6887
6888         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6889
6890         //First hop
6891         let mut payment_event = {
6892                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6893                 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, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
6894                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6895                 check_added_monitors!(nodes[0], 1);
6896                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6897                 assert_eq!(events.len(), 1);
6898                 SendEvent::from_event(events.remove(0))
6899         };
6900         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6901         check_added_monitors!(nodes[1], 0);
6902         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6903         expect_pending_htlcs_forwardable!(nodes[1]);
6904         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6905         assert_eq!(events_2.len(), 1);
6906         check_added_monitors!(nodes[1], 1);
6907         payment_event = SendEvent::from_event(events_2.remove(0));
6908         assert_eq!(payment_event.msgs.len(), 1);
6909
6910         //Second Hop
6911         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6912         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6913         check_added_monitors!(nodes[2], 0);
6914         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6915
6916         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6917         assert_eq!(events_3.len(), 1);
6918         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6919                 match events_3[0] {
6920                         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 } } => {
6921                                 assert!(update_add_htlcs.is_empty());
6922                                 assert!(update_fulfill_htlcs.is_empty());
6923                                 assert!(update_fail_htlcs.is_empty());
6924                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6925                                 assert!(update_fee.is_none());
6926                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6927                         },
6928                         _ => panic!("Unexpected event"),
6929                 }
6930         };
6931
6932         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6933
6934         check_added_monitors!(nodes[1], 0);
6935         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6936         expect_pending_htlcs_forwardable!(nodes[1]);
6937         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6938         assert_eq!(events_4.len(), 1);
6939
6940         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6941         match events_4[0] {
6942                 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, .. } } => {
6943                         assert!(update_add_htlcs.is_empty());
6944                         assert!(update_fulfill_htlcs.is_empty());
6945                         assert_eq!(update_fail_htlcs.len(), 1);
6946                         assert!(update_fail_malformed_htlcs.is_empty());
6947                         assert!(update_fee.is_none());
6948                 },
6949                 _ => panic!("Unexpected event"),
6950         };
6951
6952         check_added_monitors!(nodes[1], 1);
6953 }
6954
6955 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6956         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6957         // 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
6958         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6959
6960         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6961         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6962         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6963         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6964         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6965         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6966
6967         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6968
6969         // We route 2 dust-HTLCs between A and B
6970         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6971         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6972         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6973
6974         // Cache one local commitment tx as previous
6975         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6976
6977         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6978         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
6979         check_added_monitors!(nodes[1], 0);
6980         expect_pending_htlcs_forwardable!(nodes[1]);
6981         check_added_monitors!(nodes[1], 1);
6982
6983         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6984         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6985         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6986         check_added_monitors!(nodes[0], 1);
6987
6988         // Cache one local commitment tx as lastest
6989         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6990
6991         let events = nodes[0].node.get_and_clear_pending_msg_events();
6992         match events[0] {
6993                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6994                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6995                 },
6996                 _ => panic!("Unexpected event"),
6997         }
6998         match events[1] {
6999                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7000                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7001                 },
7002                 _ => panic!("Unexpected event"),
7003         }
7004
7005         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7006         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7007         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7008
7009         if announce_latest {
7010                 connect_block(&nodes[0], &Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
7011         } else {
7012                 connect_block(&nodes[0], &Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
7013         }
7014
7015         check_closed_broadcast!(nodes[0], false);
7016         check_added_monitors!(nodes[0], 1);
7017
7018         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7019         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true,  header.block_hash());
7020         let events = nodes[0].node.get_and_clear_pending_events();
7021         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7022         assert_eq!(events.len(), 2);
7023         let mut first_failed = false;
7024         for event in events {
7025                 match event {
7026                         Event::PaymentFailed { payment_hash, .. } => {
7027                                 if payment_hash == payment_hash_1 {
7028                                         assert!(!first_failed);
7029                                         first_failed = true;
7030                                 } else {
7031                                         assert_eq!(payment_hash, payment_hash_2);
7032                                 }
7033                         }
7034                         _ => panic!("Unexpected event"),
7035                 }
7036         }
7037 }
7038
7039 #[test]
7040 fn test_failure_delay_dust_htlc_local_commitment() {
7041         do_test_failure_delay_dust_htlc_local_commitment(true);
7042         do_test_failure_delay_dust_htlc_local_commitment(false);
7043 }
7044
7045 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7046         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7047         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7048         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7049         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7050         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7051         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7052
7053         let chanmon_cfgs = create_chanmon_cfgs(3);
7054         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7055         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7056         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7057         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7058
7059         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7060
7061         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7062         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7063
7064         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7065         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7066
7067         // We revoked bs_commitment_tx
7068         if revoked {
7069                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7070                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7071         }
7072
7073         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7074         let mut timeout_tx = Vec::new();
7075         if local {
7076                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7077                 connect_block(&nodes[0], &Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
7078                 check_closed_broadcast!(nodes[0], false);
7079                 check_added_monitors!(nodes[0], 1);
7080                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7081                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7082                 let parent_hash  = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7083                 expect_payment_failed!(nodes[0], dust_hash, true);
7084                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7085                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7086                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7087                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7088                 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7089                 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7090                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7091                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7092         } else {
7093                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7094                 connect_block(&nodes[0], &Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
7095                 check_closed_broadcast!(nodes[0], false);
7096                 check_added_monitors!(nodes[0], 1);
7097                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7098                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7099                 let parent_hash  = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7100                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7101                 if !revoked {
7102                         expect_payment_failed!(nodes[0], dust_hash, true);
7103                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7104                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7105                         connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7106                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7107                         let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7108                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7109                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7110                 } else {
7111                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7112                         // commitment tx
7113                         let events = nodes[0].node.get_and_clear_pending_events();
7114                         assert_eq!(events.len(), 2);
7115                         let first;
7116                         match events[0] {
7117                                 Event::PaymentFailed { payment_hash, .. } => {
7118                                         if payment_hash == dust_hash { first = true; }
7119                                         else { first = false; }
7120                                 },
7121                                 _ => panic!("Unexpected event"),
7122                         }
7123                         match events[1] {
7124                                 Event::PaymentFailed { payment_hash, .. } => {
7125                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7126                                         else { assert_eq!(payment_hash, dust_hash); }
7127                                 },
7128                                 _ => panic!("Unexpected event"),
7129                         }
7130                 }
7131         }
7132 }
7133
7134 #[test]
7135 fn test_sweep_outbound_htlc_failure_update() {
7136         do_test_sweep_outbound_htlc_failure_update(false, true);
7137         do_test_sweep_outbound_htlc_failure_update(false, false);
7138         do_test_sweep_outbound_htlc_failure_update(true, false);
7139 }
7140
7141 #[test]
7142 fn test_upfront_shutdown_script() {
7143         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7144         // enforce it at shutdown message
7145
7146         let mut config = UserConfig::default();
7147         config.channel_options.announced_channel = true;
7148         config.peer_channel_config_limits.force_announced_channel_preference = false;
7149         config.channel_options.commit_upfront_shutdown_pubkey = false;
7150         let user_cfgs = [None, Some(config), None];
7151         let chanmon_cfgs = create_chanmon_cfgs(3);
7152         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7153         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7154         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7155
7156         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7157         let flags = InitFeatures::known();
7158         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7159         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7160         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7161         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7162         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
7163         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7164     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()));
7165         check_added_monitors!(nodes[2], 1);
7166
7167         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7168         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7169         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7170         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7171         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7172         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7173         let events = nodes[2].node.get_and_clear_pending_msg_events();
7174         assert_eq!(events.len(), 1);
7175         match events[0] {
7176                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7177                 _ => panic!("Unexpected event"),
7178         }
7179
7180         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7181         let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7182         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7183         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7184         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7185         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7186         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
7187         let events = nodes[1].node.get_and_clear_pending_msg_events();
7188         assert_eq!(events.len(), 1);
7189         match events[0] {
7190                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7191                 _ => panic!("Unexpected event"),
7192         }
7193
7194         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7195         // channel smoothly, opt-out is from channel initiator here
7196         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7197         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7198         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7199         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7200         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7201         let events = nodes[0].node.get_and_clear_pending_msg_events();
7202         assert_eq!(events.len(), 1);
7203         match events[0] {
7204                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7205                 _ => panic!("Unexpected event"),
7206         }
7207
7208         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7209         //// channel smoothly
7210         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7211         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7212         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7213         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7214         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7215         let events = nodes[0].node.get_and_clear_pending_msg_events();
7216         assert_eq!(events.len(), 2);
7217         match events[0] {
7218                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7219                 _ => panic!("Unexpected event"),
7220         }
7221         match events[1] {
7222                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7223                 _ => panic!("Unexpected event"),
7224         }
7225 }
7226
7227 #[test]
7228 fn test_user_configurable_csv_delay() {
7229         // We test our channel constructors yield errors when we pass them absurd csv delay
7230
7231         let mut low_our_to_self_config = UserConfig::default();
7232         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7233         let mut high_their_to_self_config = UserConfig::default();
7234         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7235         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7236         let chanmon_cfgs = create_chanmon_cfgs(2);
7237         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7238         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7239         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7240
7241         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7242         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) {
7243                 match error {
7244                         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())); },
7245                         _ => panic!("Unexpected event"),
7246                 }
7247         } else { assert!(false) }
7248
7249         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7250         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7251         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7252         open_channel.to_self_delay = 200;
7253         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) {
7254                 match error {
7255                         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()));  },
7256                         _ => panic!("Unexpected event"),
7257                 }
7258         } else { assert!(false); }
7259
7260         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7261         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7262         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()));
7263         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7264         accept_channel.to_self_delay = 200;
7265         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7266         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7267                 match action {
7268                         &ErrorAction::SendErrorMessage { ref msg } => {
7269                                 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()));
7270                         },
7271                         _ => { assert!(false); }
7272                 }
7273         } else { assert!(false); }
7274
7275         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7276         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7277         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7278         open_channel.to_self_delay = 200;
7279         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) {
7280                 match error {
7281                         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())); },
7282                         _ => panic!("Unexpected event"),
7283                 }
7284         } else { assert!(false); }
7285 }
7286
7287 #[test]
7288 fn test_data_loss_protect() {
7289         // We want to be sure that :
7290         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7291         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7292         // * we close channel in case of detecting other being fallen behind
7293         // * we are able to claim our own outputs thanks to to_remote being static
7294         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7295         let persister;
7296         let logger;
7297         let fee_estimator;
7298         let tx_broadcaster;
7299         let chain_source;
7300         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7301         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7302         // during signing due to revoked tx
7303         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7304         let keys_manager = &chanmon_cfgs[0].keys_manager;
7305         let monitor;
7306         let node_state_0;
7307         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7308         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7309         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7310
7311         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7312
7313         // Cache node A state before any channel update
7314         let previous_node_state = nodes[0].node.encode();
7315         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7316         nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7317
7318         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7319         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7320
7321         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7322         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7323
7324         // Restore node A from previous state
7325         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7326         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7327         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7328         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7329         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7330         persister = test_utils::TestPersister::new();
7331         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7332         node_state_0 = {
7333                 let mut channel_monitors = HashMap::new();
7334                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7335                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &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 {
7336                         keys_manager: keys_manager,
7337                         fee_estimator: &fee_estimator,
7338                         chain_monitor: &monitor,
7339                         logger: &logger,
7340                         tx_broadcaster: &tx_broadcaster,
7341                         default_config: UserConfig::default(),
7342                         channel_monitors,
7343                 }).unwrap().1
7344         };
7345         nodes[0].node = &node_state_0;
7346         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7347         nodes[0].chain_monitor = &monitor;
7348         nodes[0].chain_source = &chain_source;
7349
7350         check_added_monitors!(nodes[0], 1);
7351
7352         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7353         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7354
7355         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7356
7357         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7358         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7359         check_added_monitors!(nodes[0], 1);
7360
7361         {
7362                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7363                 assert_eq!(node_txn.len(), 0);
7364         }
7365
7366         let mut reestablish_1 = Vec::with_capacity(1);
7367         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7368                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7369                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7370                         reestablish_1.push(msg.clone());
7371                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7372                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7373                         match action {
7374                                 &ErrorAction::SendErrorMessage { ref msg } => {
7375                                         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");
7376                                 },
7377                                 _ => panic!("Unexpected event!"),
7378                         }
7379                 } else {
7380                         panic!("Unexpected event")
7381                 }
7382         }
7383
7384         // Check we close channel detecting A is fallen-behind
7385         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7386         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7387         check_added_monitors!(nodes[1], 1);
7388
7389
7390         // Check A is able to claim to_remote output
7391         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7392         assert_eq!(node_txn.len(), 1);
7393         check_spends!(node_txn[0], chan.3);
7394         assert_eq!(node_txn[0].output.len(), 2);
7395         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7396         connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7397         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
7398         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 1000000);
7399         assert_eq!(spend_txn.len(), 1);
7400         check_spends!(spend_txn[0], node_txn[0]);
7401 }
7402
7403 #[test]
7404 fn test_check_htlc_underpaying() {
7405         // Send payment through A -> B but A is maliciously
7406         // sending a probe payment (i.e less than expected value0
7407         // to B, B should refuse payment.
7408
7409         let chanmon_cfgs = create_chanmon_cfgs(2);
7410         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7411         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7412         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7413
7414         // Create some initial channels
7415         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7416
7417         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7418
7419         // Node 3 is expecting payment of 100_000 but receive 10_000,
7420         // fail htlc like we didn't know the preimage.
7421         nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7422         nodes[1].node.process_pending_htlc_forwards();
7423
7424         let events = nodes[1].node.get_and_clear_pending_msg_events();
7425         assert_eq!(events.len(), 1);
7426         let (update_fail_htlc, commitment_signed) = match events[0] {
7427                 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 } } => {
7428                         assert!(update_add_htlcs.is_empty());
7429                         assert!(update_fulfill_htlcs.is_empty());
7430                         assert_eq!(update_fail_htlcs.len(), 1);
7431                         assert!(update_fail_malformed_htlcs.is_empty());
7432                         assert!(update_fee.is_none());
7433                         (update_fail_htlcs[0].clone(), commitment_signed)
7434                 },
7435                 _ => panic!("Unexpected event"),
7436         };
7437         check_added_monitors!(nodes[1], 1);
7438
7439         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7440         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7441
7442         // 10_000 msat as u64, followed by a height of 99 as u32
7443         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7444         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7445         expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7446         nodes[1].node.get_and_clear_pending_events();
7447 }
7448
7449 #[test]
7450 fn test_announce_disable_channels() {
7451         // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7452         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7453
7454         let chanmon_cfgs = create_chanmon_cfgs(2);
7455         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7456         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7457         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7458
7459         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7460         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7461         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7462
7463         // Disconnect peers
7464         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7465         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7466
7467         nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7468         nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7469         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7470         assert_eq!(msg_events.len(), 3);
7471         for e in msg_events {
7472                 match e {
7473                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7474                                 let short_id = msg.contents.short_channel_id;
7475                                 // Check generated channel_update match list in PendingChannelUpdate
7476                                 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7477                                         panic!("Generated ChannelUpdate for wrong chan!");
7478                                 }
7479                         },
7480                         _ => panic!("Unexpected event"),
7481                 }
7482         }
7483         // Reconnect peers
7484         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7485         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7486         assert_eq!(reestablish_1.len(), 3);
7487         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7488         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7489         assert_eq!(reestablish_2.len(), 3);
7490
7491         // Reestablish chan_1
7492         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7493         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7494         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7495         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7496         // Reestablish chan_2
7497         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7498         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7499         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7500         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7501         // Reestablish chan_3
7502         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7503         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7504         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7505         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7506
7507         nodes[0].node.timer_chan_freshness_every_min();
7508         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7509 }
7510
7511 #[test]
7512 fn test_bump_penalty_txn_on_revoked_commitment() {
7513         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7514         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7515
7516         let chanmon_cfgs = create_chanmon_cfgs(2);
7517         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7518         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7519         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7520
7521         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7522         let logger = test_utils::TestLogger::new();
7523
7524
7525         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7526         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7527         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, &Vec::new(), 3000000, 30, &logger).unwrap();
7528         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7529
7530         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7531         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7532         assert_eq!(revoked_txn[0].output.len(), 4);
7533         assert_eq!(revoked_txn[0].input.len(), 1);
7534         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7535         let revoked_txid = revoked_txn[0].txid();
7536
7537         let mut penalty_sum = 0;
7538         for outp in revoked_txn[0].output.iter() {
7539                 if outp.script_pubkey.is_v0_p2wsh() {
7540                         penalty_sum += outp.value;
7541                 }
7542         }
7543
7544         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7545         let header_114 = connect_blocks(&nodes[1], 114, 0, false, Default::default());
7546
7547         // Actually revoke tx by claiming a HTLC
7548         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7549         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7550         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7551         check_added_monitors!(nodes[1], 1);
7552
7553         // One or more justice tx should have been broadcast, check it
7554         let penalty_1;
7555         let feerate_1;
7556         {
7557                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7558                 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7559                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7560                 assert_eq!(node_txn[0].output.len(), 1);
7561                 check_spends!(node_txn[0], revoked_txn[0]);
7562                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7563                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7564                 penalty_1 = node_txn[0].txid();
7565                 node_txn.clear();
7566         };
7567
7568         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7569         let header = connect_blocks(&nodes[1], 3, 115,  true, header.block_hash());
7570         let mut penalty_2 = penalty_1;
7571         let mut feerate_2 = 0;
7572         {
7573                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7574                 assert_eq!(node_txn.len(), 1);
7575                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7576                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7577                         assert_eq!(node_txn[0].output.len(), 1);
7578                         check_spends!(node_txn[0], revoked_txn[0]);
7579                         penalty_2 = node_txn[0].txid();
7580                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7581                         assert_ne!(penalty_2, penalty_1);
7582                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7583                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7584                         // Verify 25% bump heuristic
7585                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7586                         node_txn.clear();
7587                 }
7588         }
7589         assert_ne!(feerate_2, 0);
7590
7591         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7592         connect_blocks(&nodes[1], 3, 118, true, header);
7593         let penalty_3;
7594         let mut feerate_3 = 0;
7595         {
7596                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7597                 assert_eq!(node_txn.len(), 1);
7598                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7599                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7600                         assert_eq!(node_txn[0].output.len(), 1);
7601                         check_spends!(node_txn[0], revoked_txn[0]);
7602                         penalty_3 = node_txn[0].txid();
7603                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7604                         assert_ne!(penalty_3, penalty_2);
7605                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7606                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7607                         // Verify 25% bump heuristic
7608                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7609                         node_txn.clear();
7610                 }
7611         }
7612         assert_ne!(feerate_3, 0);
7613
7614         nodes[1].node.get_and_clear_pending_events();
7615         nodes[1].node.get_and_clear_pending_msg_events();
7616 }
7617
7618 #[test]
7619 fn test_bump_penalty_txn_on_revoked_htlcs() {
7620         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7621         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7622
7623         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7624         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7625         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7626         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7627         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7628
7629         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7630         // Lock HTLC in both directions
7631         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7632         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7633
7634         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7635         assert_eq!(revoked_local_txn[0].input.len(), 1);
7636         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7637
7638         // Revoke local commitment tx
7639         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7640
7641         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7642         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7643         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7644         check_closed_broadcast!(nodes[1], false);
7645         check_added_monitors!(nodes[1], 1);
7646
7647         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7648         assert_eq!(revoked_htlc_txn.len(), 4);
7649         if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7650                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7651                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7652                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7653                 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7654                 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7655                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7656         } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7657                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7658                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7659                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7660                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7661                 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7662                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7663         }
7664
7665         // Broadcast set of revoked txn on A
7666         let header_128 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7667         connect_block(&nodes[0], &Block { header: header_128, txdata: vec![revoked_local_txn[0].clone()] }, 128);
7668         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7669         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7670         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
7671         let first;
7672         let feerate_1;
7673         let penalty_txn;
7674         {
7675                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7676                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7677                 // Verify claim tx are spending revoked HTLC txn
7678
7679                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7680                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7681                 // which are included in the same block (they are broadcasted because we scan the
7682                 // transactions linearly and generate claims as we go, they likely should be removed in the
7683                 // future).
7684                 assert_eq!(node_txn[0].input.len(), 1);
7685                 check_spends!(node_txn[0], revoked_local_txn[0]);
7686                 assert_eq!(node_txn[1].input.len(), 1);
7687                 check_spends!(node_txn[1], revoked_local_txn[0]);
7688                 assert_eq!(node_txn[2].input.len(), 1);
7689                 check_spends!(node_txn[2], revoked_local_txn[0]);
7690
7691                 // Each of the three justice transactions claim a separate (single) output of the three
7692                 // available, which we check here:
7693                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7694                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7695                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7696
7697                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7698                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7699
7700                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7701                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7702                 // a remote commitment tx has already been confirmed).
7703                 check_spends!(node_txn[3], chan.3);
7704
7705                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7706                 // output, checked above).
7707                 assert_eq!(node_txn[4].input.len(), 2);
7708                 assert_eq!(node_txn[4].output.len(), 1);
7709                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7710
7711                 first = node_txn[4].txid();
7712                 // Store both feerates for later comparison
7713                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7714                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7715                 penalty_txn = vec![node_txn[2].clone()];
7716                 node_txn.clear();
7717         }
7718
7719         // Connect one more block to see if bumped penalty are issued for HTLC txn
7720         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7721         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
7722         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7723         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() }, 131);
7724         {
7725                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7726                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7727
7728                 check_spends!(node_txn[0], revoked_local_txn[0]);
7729                 check_spends!(node_txn[1], revoked_local_txn[0]);
7730                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7731                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7732                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7733                 } else {
7734                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7735                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7736                 }
7737
7738                 node_txn.clear();
7739         };
7740
7741         // Few more blocks to confirm penalty txn
7742         let header_135 = connect_blocks(&nodes[0], 4, 131, true, header_131.block_hash());
7743         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7744         let header_144 = connect_blocks(&nodes[0], 9, 135, true, header_135);
7745         let node_txn = {
7746                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7747                 assert_eq!(node_txn.len(), 1);
7748
7749                 assert_eq!(node_txn[0].input.len(), 2);
7750                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7751                 // Verify bumped tx is different and 25% bump heuristic
7752                 assert_ne!(first, node_txn[0].txid());
7753                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7754                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7755                 assert!(feerate_2 * 100 > feerate_1 * 125);
7756                 let txn = vec![node_txn[0].clone()];
7757                 node_txn.clear();
7758                 txn
7759         };
7760         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7761         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7762         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn }, 145);
7763         connect_blocks(&nodes[0], 20, 145, true, header_145.block_hash());
7764         {
7765                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7766                 // We verify than no new transaction has been broadcast because previously
7767                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7768                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7769                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7770                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7771                 // up bumped justice generation.
7772                 assert_eq!(node_txn.len(), 0);
7773                 node_txn.clear();
7774         }
7775         check_closed_broadcast!(nodes[0], false);
7776         check_added_monitors!(nodes[0], 1);
7777 }
7778
7779 #[test]
7780 fn test_bump_penalty_txn_on_remote_commitment() {
7781         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7782         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7783
7784         // Create 2 HTLCs
7785         // Provide preimage for one
7786         // Check aggregation
7787
7788         let chanmon_cfgs = create_chanmon_cfgs(2);
7789         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7790         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7791         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7792
7793         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7794         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7795         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7796
7797         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7798         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7799         assert_eq!(remote_txn[0].output.len(), 4);
7800         assert_eq!(remote_txn[0].input.len(), 1);
7801         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7802
7803         // Claim a HTLC without revocation (provide B monitor with preimage)
7804         nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7805         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7806         connect_block(&nodes[1], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7807         check_added_monitors!(nodes[1], 2);
7808
7809         // One or more claim tx should have been broadcast, check it
7810         let timeout;
7811         let preimage;
7812         let feerate_timeout;
7813         let feerate_preimage;
7814         {
7815                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7816                 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7817                 assert_eq!(node_txn[0].input.len(), 1);
7818                 assert_eq!(node_txn[1].input.len(), 1);
7819                 check_spends!(node_txn[0], remote_txn[0]);
7820                 check_spends!(node_txn[1], remote_txn[0]);
7821                 check_spends!(node_txn[2], chan.3);
7822                 check_spends!(node_txn[3], node_txn[2]);
7823                 check_spends!(node_txn[4], node_txn[2]);
7824                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7825                         timeout = node_txn[0].txid();
7826                         let index = node_txn[0].input[0].previous_output.vout;
7827                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7828                         feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7829
7830                         preimage = node_txn[1].txid();
7831                         let index = node_txn[1].input[0].previous_output.vout;
7832                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7833                         feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7834                 } else {
7835                         timeout = node_txn[1].txid();
7836                         let index = node_txn[1].input[0].previous_output.vout;
7837                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7838                         feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7839
7840                         preimage = node_txn[0].txid();
7841                         let index = node_txn[0].input[0].previous_output.vout;
7842                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7843                         feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7844                 }
7845                 node_txn.clear();
7846         };
7847         assert_ne!(feerate_timeout, 0);
7848         assert_ne!(feerate_preimage, 0);
7849
7850         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7851         connect_blocks(&nodes[1], 15, 1,  true, header.block_hash());
7852         {
7853                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7854                 assert_eq!(node_txn.len(), 2);
7855                 assert_eq!(node_txn[0].input.len(), 1);
7856                 assert_eq!(node_txn[1].input.len(), 1);
7857                 check_spends!(node_txn[0], remote_txn[0]);
7858                 check_spends!(node_txn[1], remote_txn[0]);
7859                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7860                         let index = node_txn[0].input[0].previous_output.vout;
7861                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7862                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7863                         assert!(new_feerate * 100 > feerate_timeout * 125);
7864                         assert_ne!(timeout, node_txn[0].txid());
7865
7866                         let index = node_txn[1].input[0].previous_output.vout;
7867                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7868                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7869                         assert!(new_feerate * 100 > feerate_preimage * 125);
7870                         assert_ne!(preimage, node_txn[1].txid());
7871                 } else {
7872                         let index = node_txn[1].input[0].previous_output.vout;
7873                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7874                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7875                         assert!(new_feerate * 100 > feerate_timeout * 125);
7876                         assert_ne!(timeout, node_txn[1].txid());
7877
7878                         let index = node_txn[0].input[0].previous_output.vout;
7879                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7880                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7881                         assert!(new_feerate * 100 > feerate_preimage * 125);
7882                         assert_ne!(preimage, node_txn[0].txid());
7883                 }
7884                 node_txn.clear();
7885         }
7886
7887         nodes[1].node.get_and_clear_pending_events();
7888         nodes[1].node.get_and_clear_pending_msg_events();
7889 }
7890
7891 #[test]
7892 fn test_set_outpoints_partial_claiming() {
7893         // - remote party claim tx, new bump tx
7894         // - disconnect remote claiming tx, new bump
7895         // - disconnect tx, see no tx anymore
7896         let chanmon_cfgs = create_chanmon_cfgs(2);
7897         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7898         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7899         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7900
7901         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7902         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7903         let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7904
7905         // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
7906         let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
7907         assert_eq!(remote_txn.len(), 3);
7908         assert_eq!(remote_txn[0].output.len(), 4);
7909         assert_eq!(remote_txn[0].input.len(), 1);
7910         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7911         check_spends!(remote_txn[1], remote_txn[0]);
7912         check_spends!(remote_txn[2], remote_txn[0]);
7913
7914         // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
7915         let prev_header_100 = connect_blocks(&nodes[1], 100, 0, false, Default::default());
7916         // Provide node A with both preimage
7917         nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
7918         nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
7919         check_added_monitors!(nodes[0], 2);
7920         nodes[0].node.get_and_clear_pending_events();
7921         nodes[0].node.get_and_clear_pending_msg_events();
7922
7923         // Connect blocks on node A commitment transaction
7924         let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7925         connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
7926         check_closed_broadcast!(nodes[0], false);
7927         check_added_monitors!(nodes[0], 1);
7928         // Verify node A broadcast tx claiming both HTLCs
7929         {
7930                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7931                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
7932                 assert_eq!(node_txn.len(), 4);
7933                 check_spends!(node_txn[0], remote_txn[0]);
7934                 check_spends!(node_txn[1], chan.3);
7935                 check_spends!(node_txn[2], node_txn[1]);
7936                 check_spends!(node_txn[3], node_txn[1]);
7937                 assert_eq!(node_txn[0].input.len(), 2);
7938                 node_txn.clear();
7939         }
7940
7941         // Connect blocks on node B
7942         connect_blocks(&nodes[1], 135, 0, false, Default::default());
7943         check_closed_broadcast!(nodes[1], false);
7944         check_added_monitors!(nodes[1], 1);
7945         // Verify node B broadcast 2 HTLC-timeout txn
7946         let partial_claim_tx = {
7947                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7948                 assert_eq!(node_txn.len(), 3);
7949                 check_spends!(node_txn[1], node_txn[0]);
7950                 check_spends!(node_txn[2], node_txn[0]);
7951                 assert_eq!(node_txn[1].input.len(), 1);
7952                 assert_eq!(node_txn[2].input.len(), 1);
7953                 node_txn[1].clone()
7954         };
7955
7956         // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
7957         let header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7958         connect_block(&nodes[0], &Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
7959         {
7960                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7961                 assert_eq!(node_txn.len(), 1);
7962                 check_spends!(node_txn[0], remote_txn[0]);
7963                 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
7964                 node_txn.clear();
7965         }
7966         nodes[0].node.get_and_clear_pending_msg_events();
7967
7968         // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
7969         disconnect_block(&nodes[0], &header, 102);
7970         {
7971                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7972                 assert_eq!(node_txn.len(), 1);
7973                 check_spends!(node_txn[0], remote_txn[0]);
7974                 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
7975                 node_txn.clear();
7976         }
7977
7978         //// Disconnect one more block and then reconnect multiple no transaction should be generated
7979         disconnect_block(&nodes[0], &header, 101);
7980         connect_blocks(&nodes[1], 15, 101, false, prev_header_100);
7981         {
7982                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7983                 assert_eq!(node_txn.len(), 0);
7984                 node_txn.clear();
7985         }
7986 }
7987
7988 #[test]
7989 fn test_counterparty_raa_skip_no_crash() {
7990         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7991         // commitment transaction, we would have happily carried on and provided them the next
7992         // commitment transaction based on one RAA forward. This would probably eventually have led to
7993         // channel closure, but it would not have resulted in funds loss. Still, our
7994         // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
7995         // check simply that the channel is closed in response to such an RAA, but don't check whether
7996         // we decide to punish our counterparty for revoking their funds (as we don't currently
7997         // implement that).
7998         let chanmon_cfgs = create_chanmon_cfgs(2);
7999         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8000         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8001         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8002         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8003
8004         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8005         let keys = &guard.by_id.get_mut(&channel_id).unwrap().holder_keys;
8006         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8007         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8008         // Must revoke without gaps
8009         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8010         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8011                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8012
8013         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8014                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8015         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8016         check_added_monitors!(nodes[1], 1);
8017 }
8018
8019 #[test]
8020 fn test_bump_txn_sanitize_tracking_maps() {
8021         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8022         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8023
8024         let chanmon_cfgs = create_chanmon_cfgs(2);
8025         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8026         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8027         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8028
8029         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8030         // Lock HTLC in both directions
8031         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8032         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8033
8034         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8035         assert_eq!(revoked_local_txn[0].input.len(), 1);
8036         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8037
8038         // Revoke local commitment tx
8039         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8040
8041         // Broadcast set of revoked txn on A
8042         let header_128 = connect_blocks(&nodes[0], 128, 0,  false, Default::default());
8043         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8044
8045         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8046         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
8047         check_closed_broadcast!(nodes[0], false);
8048         check_added_monitors!(nodes[0], 1);
8049         let penalty_txn = {
8050                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8051                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8052                 check_spends!(node_txn[0], revoked_local_txn[0]);
8053                 check_spends!(node_txn[1], revoked_local_txn[0]);
8054                 check_spends!(node_txn[2], revoked_local_txn[0]);
8055                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8056                 node_txn.clear();
8057                 penalty_txn
8058         };
8059         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8060         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
8061         connect_blocks(&nodes[0], 5, 130,  false, header_130.block_hash());
8062         {
8063                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8064                 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8065                         assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
8066                         assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
8067                 }
8068         }
8069 }
8070
8071 #[test]
8072 fn test_override_channel_config() {
8073         let chanmon_cfgs = create_chanmon_cfgs(2);
8074         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8075         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8076         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8077
8078         // Node0 initiates a channel to node1 using the override config.
8079         let mut override_config = UserConfig::default();
8080         override_config.own_channel_config.our_to_self_delay = 200;
8081
8082         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8083
8084         // Assert the channel created by node0 is using the override config.
8085         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8086         assert_eq!(res.channel_flags, 0);
8087         assert_eq!(res.to_self_delay, 200);
8088 }
8089
8090 #[test]
8091 fn test_override_0msat_htlc_minimum() {
8092         let mut zero_config = UserConfig::default();
8093         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8094         let chanmon_cfgs = create_chanmon_cfgs(2);
8095         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8096         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8097         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8098
8099         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8100         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8101         assert_eq!(res.htlc_minimum_msat, 1);
8102
8103         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8104         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8105         assert_eq!(res.htlc_minimum_msat, 1);
8106 }
8107
8108 #[test]
8109 fn test_simple_payment_secret() {
8110         // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8111         // features, however.
8112         let chanmon_cfgs = create_chanmon_cfgs(3);
8113         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8114         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8115         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8116
8117         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8118         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8119         let logger = test_utils::TestLogger::new();
8120
8121         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8122         let payment_secret = PaymentSecret([0xdb; 32]);
8123         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8124         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, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8125         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8126         // Claiming with all the correct values but the wrong secret should result in nothing...
8127         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8128         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8129         // ...but with the right secret we should be able to claim all the way back
8130         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8131 }
8132
8133 #[test]
8134 fn test_simple_mpp() {
8135         // Simple test of sending a multi-path payment.
8136         let chanmon_cfgs = create_chanmon_cfgs(4);
8137         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8138         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8139         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8140
8141         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8142         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8143         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8144         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8145         let logger = test_utils::TestLogger::new();
8146
8147         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8148         let payment_secret = PaymentSecret([0xdb; 32]);
8149         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8150         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, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8151         let path = route.paths[0].clone();
8152         route.paths.push(path);
8153         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8154         route.paths[0][0].short_channel_id = chan_1_id;
8155         route.paths[0][1].short_channel_id = chan_3_id;
8156         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8157         route.paths[1][0].short_channel_id = chan_2_id;
8158         route.paths[1][1].short_channel_id = chan_4_id;
8159         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8160         // Claiming with all the correct values but the wrong secret should result in nothing...
8161         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8162         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8163         // ...but with the right secret we should be able to claim all the way back
8164         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8165 }
8166
8167 #[test]
8168 fn test_update_err_monitor_lockdown() {
8169         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8170         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8171         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8172         //
8173         // This scenario may happen in a watchtower setup, where watchtower process a block height
8174         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8175         // commitment at same time.
8176
8177         let chanmon_cfgs = create_chanmon_cfgs(2);
8178         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8179         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8180         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8181
8182         // Create some initial channel
8183         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8184         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8185
8186         // Rebalance the network to generate htlc in the two directions
8187         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8188
8189         // Route a HTLC from node 0 to node 1 (but don't settle)
8190         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8191
8192         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8193         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8194         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8195         let persister = test_utils::TestPersister::new();
8196         let watchtower = {
8197                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8198                 let monitor = monitors.get(&outpoint).unwrap();
8199                 let mut w = test_utils::TestVecWriter(Vec::new());
8200                 monitor.write(&mut w).unwrap();
8201                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8202                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8203                 assert!(new_monitor == *monitor);
8204                 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);
8205                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8206                 watchtower
8207         };
8208         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8209         watchtower.chain_monitor.block_connected(&header, &[], 200);
8210
8211         // Try to update ChannelMonitor
8212         assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8213         check_added_monitors!(nodes[1], 1);
8214         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8215         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8216         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8217         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8218                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8219                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8220                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8221                 } else { assert!(false); }
8222         } else { assert!(false); };
8223         // Our local monitor is in-sync and hasn't processed yet timeout
8224         check_added_monitors!(nodes[0], 1);
8225         let events = nodes[0].node.get_and_clear_pending_events();
8226         assert_eq!(events.len(), 1);
8227 }
8228
8229 #[test]
8230 fn test_concurrent_monitor_claim() {
8231         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8232         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8233         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8234         // state N+1 confirms. Alice claims output from state N+1.
8235
8236         let chanmon_cfgs = create_chanmon_cfgs(2);
8237         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8238         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8239         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8240
8241         // Create some initial channel
8242         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8243         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8244
8245         // Rebalance the network to generate htlc in the two directions
8246         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8247
8248         // Route a HTLC from node 0 to node 1 (but don't settle)
8249         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8250
8251         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8252         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8253         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8254         let persister = test_utils::TestPersister::new();
8255         let watchtower_alice = {
8256                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8257                 let monitor = monitors.get(&outpoint).unwrap();
8258                 let mut w = test_utils::TestVecWriter(Vec::new());
8259                 monitor.write(&mut w).unwrap();
8260                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8261                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8262                 assert!(new_monitor == *monitor);
8263                 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);
8264                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8265                 watchtower
8266         };
8267         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8268         watchtower_alice.chain_monitor.block_connected(&header, &vec![], 135);
8269
8270         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8271         {
8272                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8273                 assert_eq!(txn.len(), 2);
8274                 txn.clear();
8275         }
8276
8277         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8278         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8279         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8280         let persister = test_utils::TestPersister::new();
8281         let watchtower_bob = {
8282                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8283                 let monitor = monitors.get(&outpoint).unwrap();
8284                 let mut w = test_utils::TestVecWriter(Vec::new());
8285                 monitor.write(&mut w).unwrap();
8286                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8287                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8288                 assert!(new_monitor == *monitor);
8289                 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);
8290                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8291                 watchtower
8292         };
8293         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8294         watchtower_bob.chain_monitor.block_connected(&header, &vec![], 134);
8295
8296         // Route another payment to generate another update with still previous HTLC pending
8297         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8298         {
8299                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8300                 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, &Vec::new(), 3000000 , TEST_FINAL_CLTV, &logger).unwrap();
8301                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8302         }
8303         check_added_monitors!(nodes[1], 1);
8304
8305         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8306         assert_eq!(updates.update_add_htlcs.len(), 1);
8307         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8308         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8309                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8310                         // Watchtower Alice should already have seen the block and reject the update
8311                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8312                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8313                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8314                 } else { assert!(false); }
8315         } else { assert!(false); };
8316         // Our local monitor is in-sync and hasn't processed yet timeout
8317         check_added_monitors!(nodes[0], 1);
8318
8319         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8320         watchtower_bob.chain_monitor.block_connected(&header, &vec![], 135);
8321
8322         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8323         let bob_state_y;
8324         {
8325                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8326                 assert_eq!(txn.len(), 2);
8327                 bob_state_y = txn[0].clone();
8328                 txn.clear();
8329         };
8330
8331         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8332         watchtower_alice.chain_monitor.block_connected(&header, &vec![(0, &bob_state_y)], 136);
8333         {
8334                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8335                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8336                 // the onchain detection of the HTLC output
8337                 assert_eq!(htlc_txn.len(), 2);
8338                 check_spends!(htlc_txn[0], bob_state_y);
8339                 check_spends!(htlc_txn[1], bob_state_y);
8340         }
8341 }
8342
8343 #[test]
8344 fn test_pre_lockin_no_chan_closed_update() {
8345         // Test that if a peer closes a channel in response to a funding_created message we don't
8346         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8347         // message).
8348         //
8349         // Doing so would imply a channel monitor update before the initial channel monitor
8350         // registration, violating our API guarantees.
8351         //
8352         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8353         // then opening a second channel with the same funding output as the first (which is not
8354         // rejected because the first channel does not exist in the ChannelManager) and closing it
8355         // before receiving funding_signed.
8356         let chanmon_cfgs = create_chanmon_cfgs(2);
8357         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8358         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8359         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8360
8361         // Create an initial channel
8362         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8363         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8364         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8365         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8366         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8367
8368         // Move the first channel through the funding flow...
8369         let (temporary_channel_id, _tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8370
8371         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8372         check_added_monitors!(nodes[0], 0);
8373
8374         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8375         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8376         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8377         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8378 }
8379
8380 #[test]
8381 fn test_htlc_no_detection() {
8382         // This test is a mutation to underscore the detection logic bug we had
8383         // before #653. HTLC value routed is above the remaining balance, thus
8384         // inverting HTLC and `to_remote` output. HTLC will come second and
8385         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8386         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8387         // outputs order detection for correct spending children filtring.
8388
8389         let chanmon_cfgs = create_chanmon_cfgs(2);
8390         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8391         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8392         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8393
8394         // Create some initial channels
8395         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8396
8397         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000, 1_000_000);
8398         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8399         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8400         assert_eq!(local_txn[0].input.len(), 1);
8401         assert_eq!(local_txn[0].output.len(), 3);
8402         check_spends!(local_txn[0], chan_1.3);
8403
8404         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8405         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8406         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8407         // We deliberately connect the local tx twice as this should provoke a failure calling
8408         // this test before #653 fix.
8409         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8410         check_closed_broadcast!(nodes[0], false);
8411         check_added_monitors!(nodes[0], 1);
8412
8413         let htlc_timeout = {
8414                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8415                 assert_eq!(node_txn[0].input.len(), 1);
8416                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8417                 check_spends!(node_txn[0], local_txn[0]);
8418                 node_txn[0].clone()
8419         };
8420
8421         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8422         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
8423         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
8424         expect_payment_failed!(nodes[0], our_payment_hash, true);
8425 }
8426
8427 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8428         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8429         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8430         // Carol, Alice would be the upstream node, and Carol the downstream.)
8431         //
8432         // Steps of the test:
8433         // 1) Alice sends a HTLC to Carol through Bob.
8434         // 2) Carol doesn't settle the HTLC.
8435         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8436         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8437         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8438         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8439         // 5) Carol release the preimage to Bob off-chain.
8440         // 6) Bob claims the offered output on the broadcasted commitment.
8441         let chanmon_cfgs = create_chanmon_cfgs(3);
8442         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8443         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8444         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8445
8446         // Create some initial channels
8447         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8448         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8449
8450         // Steps (1) and (2):
8451         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8452         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8453
8454         // Check that Alice's commitment transaction now contains an output for this HTLC.
8455         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8456         check_spends!(alice_txn[0], chan_ab.3);
8457         assert_eq!(alice_txn[0].output.len(), 2);
8458         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8459         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8460         assert_eq!(alice_txn.len(), 2);
8461
8462         // Steps (3) and (4):
8463         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8464         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8465         let mut force_closing_node = 0; // Alice force-closes
8466         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8467         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8468         check_closed_broadcast!(nodes[force_closing_node], false);
8469         check_added_monitors!(nodes[force_closing_node], 1);
8470         if go_onchain_before_fulfill {
8471                 let txn_to_broadcast = match broadcast_alice {
8472                         true => alice_txn.clone(),
8473                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8474                 };
8475                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8476                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]}, 1);
8477                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8478                 if broadcast_alice {
8479                         check_closed_broadcast!(nodes[1], false);
8480                         check_added_monitors!(nodes[1], 1);
8481                 }
8482                 assert_eq!(bob_txn.len(), 1);
8483                 check_spends!(bob_txn[0], chan_ab.3);
8484         }
8485
8486         // Step (5):
8487         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8488         // process of removing the HTLC from their commitment transactions.
8489         assert!(nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000));
8490         check_added_monitors!(nodes[2], 1);
8491         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8492         assert!(carol_updates.update_add_htlcs.is_empty());
8493         assert!(carol_updates.update_fail_htlcs.is_empty());
8494         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8495         assert!(carol_updates.update_fee.is_none());
8496         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8497
8498         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8499         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8500         if !go_onchain_before_fulfill && broadcast_alice {
8501                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8502                 assert_eq!(events.len(), 1);
8503                 match events[0] {
8504                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8505                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8506                         },
8507                         _ => panic!("Unexpected event"),
8508                 };
8509         }
8510         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8511         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8512         // Carol<->Bob's updated commitment transaction info.
8513         check_added_monitors!(nodes[1], 2);
8514
8515         let events = nodes[1].node.get_and_clear_pending_msg_events();
8516         assert_eq!(events.len(), 2);
8517         let bob_revocation = match events[0] {
8518                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8519                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8520                         (*msg).clone()
8521                 },
8522                 _ => panic!("Unexpected event"),
8523         };
8524         let bob_updates = match events[1] {
8525                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8526                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8527                         (*updates).clone()
8528                 },
8529                 _ => panic!("Unexpected event"),
8530         };
8531
8532         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8533         check_added_monitors!(nodes[2], 1);
8534         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8535         check_added_monitors!(nodes[2], 1);
8536
8537         let events = nodes[2].node.get_and_clear_pending_msg_events();
8538         assert_eq!(events.len(), 1);
8539         let carol_revocation = match events[0] {
8540                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8541                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8542                         (*msg).clone()
8543                 },
8544                 _ => panic!("Unexpected event"),
8545         };
8546         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8547         check_added_monitors!(nodes[1], 1);
8548
8549         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8550         // here's where we put said channel's commitment tx on-chain.
8551         let mut txn_to_broadcast = alice_txn.clone();
8552         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8553         if !go_onchain_before_fulfill {
8554                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8555                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]}, 1);
8556                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8557                 if broadcast_alice {
8558                         check_closed_broadcast!(nodes[1], false);
8559                         check_added_monitors!(nodes[1], 1);
8560                 }
8561                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8562                 if broadcast_alice {
8563                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8564                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8565                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8566                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8567                         // broadcasted.
8568                         assert_eq!(bob_txn.len(), 3);
8569                         check_spends!(bob_txn[1], chan_ab.3);
8570                 } else {
8571                         assert_eq!(bob_txn.len(), 2);
8572                         check_spends!(bob_txn[0], chan_ab.3);
8573                 }
8574         }
8575
8576         // Step (6):
8577         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8578         // broadcasted commitment transaction.
8579         {
8580                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8581                 if go_onchain_before_fulfill {
8582                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8583                         assert_eq!(bob_txn.len(), 2);
8584                 }
8585                 let script_weight = match broadcast_alice {
8586                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8587                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8588                 };
8589                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8590                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8591                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8592                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8593                 if broadcast_alice && !go_onchain_before_fulfill {
8594                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8595                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8596                 } else {
8597                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8598                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8599                 }
8600         }
8601 }
8602
8603 #[test]
8604 fn test_onchain_htlc_settlement_after_close() {
8605         do_test_onchain_htlc_settlement_after_close(true, true);
8606         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8607         do_test_onchain_htlc_settlement_after_close(true, false);
8608         do_test_onchain_htlc_settlement_after_close(false, false);
8609 }
8610
8611 #[test]
8612 fn test_duplicate_chan_id() {
8613         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8614         // already open we reject it and keep the old channel.
8615         //
8616         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8617         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8618         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8619         // updating logic for the existing channel.
8620         let chanmon_cfgs = create_chanmon_cfgs(2);
8621         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8622         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8623         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8624
8625         // Create an initial channel
8626         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8627         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8628         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8629         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()));
8630
8631         // Try to create a second channel with the same temporary_channel_id as the first and check
8632         // that it is rejected.
8633         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8634         {
8635                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8636                 assert_eq!(events.len(), 1);
8637                 match events[0] {
8638                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8639                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8640                                 // first (valid) and second (invalid) channels are closed, given they both have
8641                                 // the same non-temporary channel_id. However, currently we do not, so we just
8642                                 // move forward with it.
8643                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8644                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8645                         },
8646                         _ => panic!("Unexpected event"),
8647                 }
8648         }
8649
8650         // Move the first channel through the funding flow...
8651         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8652
8653         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8654         check_added_monitors!(nodes[0], 0);
8655
8656         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8657         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8658         {
8659                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8660                 assert_eq!(added_monitors.len(), 1);
8661                 assert_eq!(added_monitors[0].0, funding_output);
8662                 added_monitors.clear();
8663         }
8664         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8665
8666         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8667         let channel_id = funding_outpoint.to_channel_id();
8668
8669         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8670         // temporary one).
8671
8672         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8673         // Technically this is allowed by the spec, but we don't support it and there's little reason
8674         // to. Still, it shouldn't cause any other issues.
8675         open_chan_msg.temporary_channel_id = channel_id;
8676         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8677         {
8678                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8679                 assert_eq!(events.len(), 1);
8680                 match events[0] {
8681                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8682                                 // Technically, at this point, nodes[1] would be justified in thinking both
8683                                 // channels are closed, but currently we do not, so we just 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         // Now try to create a second channel which has a duplicate funding output.
8692         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8693         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8694         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8695         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()));
8696         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8697
8698         let funding_created = {
8699                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8700                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8701                 let logger = test_utils::TestLogger::new();
8702                 as_chan.get_outbound_funding_created(funding_outpoint, &&logger).unwrap()
8703         };
8704         check_added_monitors!(nodes[0], 0);
8705         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8706         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8707         // still needs to be cleared here.
8708         check_added_monitors!(nodes[1], 1);
8709
8710         // ...still, nodes[1] will reject the duplicate channel.
8711         {
8712                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8713                 assert_eq!(events.len(), 1);
8714                 match events[0] {
8715                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8716                                 // Technically, at this point, nodes[1] would be justified in thinking both
8717                                 // channels are closed, but currently we do not, so we just move forward with it.
8718                                 assert_eq!(msg.channel_id, channel_id);
8719                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8720                         },
8721                         _ => panic!("Unexpected event"),
8722                 }
8723         }
8724
8725         // finally, finish creating the original channel and send a payment over it to make sure
8726         // everything is functional.
8727         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8728         {
8729                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8730                 assert_eq!(added_monitors.len(), 1);
8731                 assert_eq!(added_monitors[0].0, funding_output);
8732                 added_monitors.clear();
8733         }
8734
8735         let events_4 = nodes[0].node.get_and_clear_pending_events();
8736         assert_eq!(events_4.len(), 1);
8737         match events_4[0] {
8738                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
8739                         assert_eq!(user_channel_id, 42);
8740                         assert_eq!(*funding_txo, funding_output);
8741                 },
8742                 _ => panic!("Unexpected event"),
8743         };
8744
8745         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8746         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8747         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8748         send_payment(&nodes[0], &[&nodes[1]], 8000000, 8_000_000);
8749 }
8750
8751 #[test]
8752 fn test_error_chans_closed() {
8753         // Test that we properly handle error messages, closing appropriate channels.
8754         //
8755         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8756         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8757         // we can test various edge cases around it to ensure we don't regress.
8758         let chanmon_cfgs = create_chanmon_cfgs(3);
8759         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8760         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8761         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8762
8763         // Create some initial channels
8764         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8765         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8766         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8767
8768         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8769         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8770         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8771
8772         // Closing a channel from a different peer has no effect
8773         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8774         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8775
8776         // Closing one channel doesn't impact others
8777         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8778         check_added_monitors!(nodes[0], 1);
8779         check_closed_broadcast!(nodes[0], false);
8780         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8781         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);
8782         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);
8783
8784         // A null channel ID should close all channels
8785         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8786         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8787         check_added_monitors!(nodes[0], 2);
8788         let events = nodes[0].node.get_and_clear_pending_msg_events();
8789         assert_eq!(events.len(), 2);
8790         match events[0] {
8791                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8792                         assert_eq!(msg.contents.flags & 2, 2);
8793                 },
8794                 _ => panic!("Unexpected event"),
8795         }
8796         match events[1] {
8797                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8798                         assert_eq!(msg.contents.flags & 2, 2);
8799                 },
8800                 _ => panic!("Unexpected event"),
8801         }
8802         // Note that at this point users of a standard PeerHandler will end up calling
8803         // peer_disconnected with no_connection_possible set to false, duplicating the
8804         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8805         // users with their own peer handling logic. We duplicate the call here, however.
8806         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8807         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8808
8809         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8810         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8811         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8812 }