Combine ChannelManager's block hash and height
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use chain;
15 use chain::Watch;
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::{KeysInterface, BaseSign};
20 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
21 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
22 use ln::channel::{Channel, ChannelError};
23 use ln::{chan_utils, onion_utils};
24 use routing::router::{Route, RouteHop, get_route};
25 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
26 use ln::msgs;
27 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
28 use util::enforcing_trait_impls::EnforcingSigner;
29 use util::{byte_utils, test_utils};
30 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
31 use util::errors::APIError;
32 use util::ser::{Writeable, ReadableArgs};
33 use util::config::UserConfig;
34
35 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
36 use bitcoin::hash_types::{Txid, BlockHash};
37 use bitcoin::blockdata::block::{Block, BlockHeader};
38 use bitcoin::blockdata::script::Builder;
39 use bitcoin::blockdata::opcodes;
40 use bitcoin::blockdata::constants::genesis_block;
41 use bitcoin::network::constants::Network;
42
43 use bitcoin::hashes::sha256::Hash as Sha256;
44 use bitcoin::hashes::Hash;
45
46 use bitcoin::secp256k1::{Secp256k1, Message};
47 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
48
49 use regex;
50
51 use std::collections::{BTreeSet, HashMap, HashSet};
52 use std::default::Default;
53 use std::sync::Mutex;
54
55 use ln::functional_test_utils::*;
56 use ln::chan_utils::CommitmentTransaction;
57 use ln::msgs::OptionalField::Present;
58
59 #[test]
60 fn test_insane_channel_opens() {
61         // Stand up a network of 2 nodes
62         let chanmon_cfgs = create_chanmon_cfgs(2);
63         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
64         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
65         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
66
67         // Instantiate channel parameters where we push the maximum msats given our
68         // funding satoshis
69         let channel_value_sat = 31337; // same as funding satoshis
70         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
71         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
72
73         // Have node0 initiate a channel to node1 with aforementioned parameters
74         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
75
76         // Extract the channel open message from node0 to node1
77         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
78
79         // Test helper that asserts we get the correct error string given a mutator
80         // that supposedly makes the channel open message insane
81         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
82                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
83                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
84                 assert_eq!(msg_events.len(), 1);
85                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
86                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
87                         match action {
88                                 &ErrorAction::SendErrorMessage { .. } => {
89                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
90                                 },
91                                 _ => panic!("unexpected event!"),
92                         }
93                 } else { assert!(false); }
94         };
95
96         use ln::channel::MAX_FUNDING_SATOSHIS;
97         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
98
99         // Test all mutations that would make the channel open message insane
100         insane_open_helper(format!("Funding must be smaller than {}. It was {}", MAX_FUNDING_SATOSHIS, MAX_FUNDING_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
101
102         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
103
104         insane_open_helper(r"push_msat \d+ was larger than funding value \d+", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
105
106         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
107
108         insane_open_helper(r"Bogus; channel reserve \(\d+\) is less than dust limit \(\d+\)", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
109
110         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
111
112         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
113
114         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
115
116         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
117 }
118
119 #[test]
120 fn test_async_inbound_update_fee() {
121         let chanmon_cfgs = create_chanmon_cfgs(2);
122         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
123         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
124         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
125         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
126         let logger = test_utils::TestLogger::new();
127         let channel_id = chan.2;
128
129         // balancing
130         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
131
132         // A                                        B
133         // update_fee                            ->
134         // send (1) commitment_signed            -.
135         //                                       <- update_add_htlc/commitment_signed
136         // send (2) RAA (awaiting remote revoke) -.
137         // (1) commitment_signed is delivered    ->
138         //                                       .- send (3) RAA (awaiting remote revoke)
139         // (2) RAA is delivered                  ->
140         //                                       .- send (4) commitment_signed
141         //                                       <- (3) RAA is delivered
142         // send (5) commitment_signed            -.
143         //                                       <- (4) commitment_signed is delivered
144         // send (6) RAA                          -.
145         // (5) commitment_signed is delivered    ->
146         //                                       <- RAA
147         // (6) RAA is delivered                  ->
148
149         // First nodes[0] generates an update_fee
150         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
151         check_added_monitors!(nodes[0], 1);
152
153         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
154         assert_eq!(events_0.len(), 1);
155         let (update_msg, commitment_signed) = match events_0[0] { // (1)
156                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
157                         (update_fee.as_ref(), commitment_signed)
158                 },
159                 _ => panic!("Unexpected event"),
160         };
161
162         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
163
164         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
165         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
166         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
167         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
168         check_added_monitors!(nodes[1], 1);
169
170         let payment_event = {
171                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
172                 assert_eq!(events_1.len(), 1);
173                 SendEvent::from_event(events_1.remove(0))
174         };
175         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
176         assert_eq!(payment_event.msgs.len(), 1);
177
178         // ...now when the messages get delivered everyone should be happy
179         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
180         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
181         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
182         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
183         check_added_monitors!(nodes[0], 1);
184
185         // deliver(1), generate (3):
186         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
187         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
188         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
189         check_added_monitors!(nodes[1], 1);
190
191         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
192         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
193         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
194         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
195         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
196         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
197         assert!(bs_update.update_fee.is_none()); // (4)
198         check_added_monitors!(nodes[1], 1);
199
200         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
201         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
202         assert!(as_update.update_add_htlcs.is_empty()); // (5)
203         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
204         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
205         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
206         assert!(as_update.update_fee.is_none()); // (5)
207         check_added_monitors!(nodes[0], 1);
208
209         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
210         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
211         // only (6) so get_event_msg's assert(len == 1) passes
212         check_added_monitors!(nodes[0], 1);
213
214         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
215         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
216         check_added_monitors!(nodes[1], 1);
217
218         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
219         check_added_monitors!(nodes[0], 1);
220
221         let events_2 = nodes[0].node.get_and_clear_pending_events();
222         assert_eq!(events_2.len(), 1);
223         match events_2[0] {
224                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
225                 _ => panic!("Unexpected event"),
226         }
227
228         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
229         check_added_monitors!(nodes[1], 1);
230 }
231
232 #[test]
233 fn test_update_fee_unordered_raa() {
234         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
235         // crash in an earlier version of the update_fee patch)
236         let chanmon_cfgs = create_chanmon_cfgs(2);
237         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
238         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
239         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
240         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
241         let channel_id = chan.2;
242         let logger = test_utils::TestLogger::new();
243
244         // balancing
245         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
246
247         // First nodes[0] generates an update_fee
248         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
249         check_added_monitors!(nodes[0], 1);
250
251         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
252         assert_eq!(events_0.len(), 1);
253         let update_msg = match events_0[0] { // (1)
254                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
255                         update_fee.as_ref()
256                 },
257                 _ => panic!("Unexpected event"),
258         };
259
260         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
261
262         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
263         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
264         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
265         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
266         check_added_monitors!(nodes[1], 1);
267
268         let payment_event = {
269                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
270                 assert_eq!(events_1.len(), 1);
271                 SendEvent::from_event(events_1.remove(0))
272         };
273         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
274         assert_eq!(payment_event.msgs.len(), 1);
275
276         // ...now when the messages get delivered everyone should be happy
277         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
278         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
279         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
280         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
281         check_added_monitors!(nodes[0], 1);
282
283         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
284         check_added_monitors!(nodes[1], 1);
285
286         // We can't continue, sadly, because our (1) now has a bogus signature
287 }
288
289 #[test]
290 fn test_multi_flight_update_fee() {
291         let chanmon_cfgs = create_chanmon_cfgs(2);
292         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
293         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
294         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
295         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
296         let channel_id = chan.2;
297
298         // A                                        B
299         // update_fee/commitment_signed          ->
300         //                                       .- send (1) RAA and (2) commitment_signed
301         // update_fee (never committed)          ->
302         // (3) update_fee                        ->
303         // We have to manually generate the above update_fee, it is allowed by the protocol but we
304         // don't track which updates correspond to which revoke_and_ack responses so we're in
305         // AwaitingRAA mode and will not generate the update_fee yet.
306         //                                       <- (1) RAA delivered
307         // (3) is generated and send (4) CS      -.
308         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
309         // know the per_commitment_point to use for it.
310         //                                       <- (2) commitment_signed delivered
311         // revoke_and_ack                        ->
312         //                                          B should send no response here
313         // (4) commitment_signed delivered       ->
314         //                                       <- RAA/commitment_signed delivered
315         // revoke_and_ack                        ->
316
317         // First nodes[0] generates an update_fee
318         let initial_feerate = get_feerate!(nodes[0], channel_id);
319         nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
320         check_added_monitors!(nodes[0], 1);
321
322         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
323         assert_eq!(events_0.len(), 1);
324         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
325                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
326                         (update_fee.as_ref().unwrap(), commitment_signed)
327                 },
328                 _ => panic!("Unexpected event"),
329         };
330
331         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
332         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
333         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
334         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
335         check_added_monitors!(nodes[1], 1);
336
337         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
338         // transaction:
339         nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
340         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
341         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
342
343         // Create the (3) update_fee message that nodes[0] will generate before it does...
344         let mut update_msg_2 = msgs::UpdateFee {
345                 channel_id: update_msg_1.channel_id.clone(),
346                 feerate_per_kw: (initial_feerate + 30) as u32,
347         };
348
349         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
350
351         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
352         // Deliver (3)
353         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
354
355         // Deliver (1), generating (3) and (4)
356         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
357         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
358         check_added_monitors!(nodes[0], 1);
359         assert!(as_second_update.update_add_htlcs.is_empty());
360         assert!(as_second_update.update_fulfill_htlcs.is_empty());
361         assert!(as_second_update.update_fail_htlcs.is_empty());
362         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
363         // Check that the update_fee newly generated matches what we delivered:
364         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
365         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
366
367         // Deliver (2) commitment_signed
368         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
369         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
370         check_added_monitors!(nodes[0], 1);
371         // No commitment_signed so get_event_msg's assert(len == 1) passes
372
373         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
374         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
375         check_added_monitors!(nodes[1], 1);
376
377         // Delever (4)
378         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
379         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
380         check_added_monitors!(nodes[1], 1);
381
382         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
383         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
384         check_added_monitors!(nodes[0], 1);
385
386         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
387         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
388         // No commitment_signed so get_event_msg's assert(len == 1) passes
389         check_added_monitors!(nodes[0], 1);
390
391         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
392         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
393         check_added_monitors!(nodes[1], 1);
394 }
395
396 fn do_test_1_conf_open(connect_style: ConnectStyle) {
397         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
398         // tests that we properly send one in that case.
399         let mut alice_config = UserConfig::default();
400         alice_config.own_channel_config.minimum_depth = 1;
401         alice_config.channel_options.announced_channel = true;
402         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
403         let mut bob_config = UserConfig::default();
404         bob_config.own_channel_config.minimum_depth = 1;
405         bob_config.channel_options.announced_channel = true;
406         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
407         let chanmon_cfgs = create_chanmon_cfgs(2);
408         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
409         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
410         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
411         *nodes[0].connect_style.borrow_mut() = connect_style;
412
413         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
414         mine_transaction(&nodes[1], &tx);
415         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()));
416
417         mine_transaction(&nodes[0], &tx);
418         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
419         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
420
421         for node in nodes {
422                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
423                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
424                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
425         }
426 }
427 #[test]
428 fn test_1_conf_open() {
429         do_test_1_conf_open(ConnectStyle::BestBlockFirst);
430         do_test_1_conf_open(ConnectStyle::TransactionsFirst);
431         do_test_1_conf_open(ConnectStyle::FullBlockViaListen);
432 }
433
434 fn do_test_sanity_on_in_flight_opens(steps: u8) {
435         // Previously, we had issues deserializing channels when we hadn't connected the first block
436         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
437         // serialization round-trips and simply do steps towards opening a channel and then drop the
438         // Node objects.
439
440         let chanmon_cfgs = create_chanmon_cfgs(2);
441         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
442         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
443         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
444
445         if steps & 0b1000_0000 != 0{
446                 let block = Block {
447                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
448                         txdata: vec![],
449                 };
450                 connect_block(&nodes[0], &block);
451                 connect_block(&nodes[1], &block);
452         }
453
454         if steps & 0x0f == 0 { return; }
455         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
456         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
457
458         if steps & 0x0f == 1 { return; }
459         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
460         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
461
462         if steps & 0x0f == 2 { return; }
463         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
464
465         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
466
467         if steps & 0x0f == 3 { return; }
468         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
469         check_added_monitors!(nodes[0], 0);
470         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
471
472         if steps & 0x0f == 4 { return; }
473         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
474         {
475                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
476                 assert_eq!(added_monitors.len(), 1);
477                 assert_eq!(added_monitors[0].0, funding_output);
478                 added_monitors.clear();
479         }
480         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
481
482         if steps & 0x0f == 5 { return; }
483         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
484         {
485                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
486                 assert_eq!(added_monitors.len(), 1);
487                 assert_eq!(added_monitors[0].0, funding_output);
488                 added_monitors.clear();
489         }
490
491         let events_4 = nodes[0].node.get_and_clear_pending_events();
492         assert_eq!(events_4.len(), 0);
493
494         if steps & 0x0f == 6 { return; }
495         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
496
497         if steps & 0x0f == 7 { return; }
498         confirm_transaction_at(&nodes[0], &tx, 2);
499         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
500         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
501 }
502
503 #[test]
504 fn test_sanity_on_in_flight_opens() {
505         do_test_sanity_on_in_flight_opens(0);
506         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
507         do_test_sanity_on_in_flight_opens(1);
508         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
509         do_test_sanity_on_in_flight_opens(2);
510         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
511         do_test_sanity_on_in_flight_opens(3);
512         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
513         do_test_sanity_on_in_flight_opens(4);
514         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
515         do_test_sanity_on_in_flight_opens(5);
516         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
517         do_test_sanity_on_in_flight_opens(6);
518         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
519         do_test_sanity_on_in_flight_opens(7);
520         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
521         do_test_sanity_on_in_flight_opens(8);
522         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
523 }
524
525 #[test]
526 fn test_update_fee_vanilla() {
527         let chanmon_cfgs = create_chanmon_cfgs(2);
528         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
529         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
530         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
531         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
532         let channel_id = chan.2;
533
534         let feerate = get_feerate!(nodes[0], channel_id);
535         nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
536         check_added_monitors!(nodes[0], 1);
537
538         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
539         assert_eq!(events_0.len(), 1);
540         let (update_msg, commitment_signed) = match events_0[0] {
541                         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 } } => {
542                         (update_fee.as_ref(), commitment_signed)
543                 },
544                 _ => panic!("Unexpected event"),
545         };
546         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
547
548         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
549         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
550         check_added_monitors!(nodes[1], 1);
551
552         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
553         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
554         check_added_monitors!(nodes[0], 1);
555
556         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
557         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
558         // No commitment_signed so get_event_msg's assert(len == 1) passes
559         check_added_monitors!(nodes[0], 1);
560
561         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
562         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
563         check_added_monitors!(nodes[1], 1);
564 }
565
566 #[test]
567 fn test_update_fee_that_funder_cannot_afford() {
568         let chanmon_cfgs = create_chanmon_cfgs(2);
569         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
570         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
571         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
572         let channel_value = 1888;
573         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
574         let channel_id = chan.2;
575
576         let feerate = 260;
577         nodes[0].node.update_fee(channel_id, feerate).unwrap();
578         check_added_monitors!(nodes[0], 1);
579         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
580
581         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
582
583         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
584
585         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
586         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
587         {
588                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
589
590                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
591                 let num_htlcs = commitment_tx.output.len() - 2;
592                 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
593                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
594                 actual_fee = channel_value - actual_fee;
595                 assert_eq!(total_fee, actual_fee);
596         }
597
598         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
599         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
600         nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
601         check_added_monitors!(nodes[0], 1);
602
603         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
604
605         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
606
607         //While producing the commitment_signed response after handling a received update_fee request the
608         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
609         //Should produce and error.
610         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
611         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
612         check_added_monitors!(nodes[1], 1);
613         check_closed_broadcast!(nodes[1], true);
614 }
615
616 #[test]
617 fn test_update_fee_with_fundee_update_add_htlc() {
618         let chanmon_cfgs = create_chanmon_cfgs(2);
619         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
620         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
621         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
622         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
623         let channel_id = chan.2;
624         let logger = test_utils::TestLogger::new();
625
626         // balancing
627         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
628
629         let feerate = get_feerate!(nodes[0], channel_id);
630         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
631         check_added_monitors!(nodes[0], 1);
632
633         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
634         assert_eq!(events_0.len(), 1);
635         let (update_msg, commitment_signed) = match events_0[0] {
636                         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 } } => {
637                         (update_fee.as_ref(), commitment_signed)
638                 },
639                 _ => panic!("Unexpected event"),
640         };
641         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
642         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
643         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
644         check_added_monitors!(nodes[1], 1);
645
646         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
647         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
648         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 800000, TEST_FINAL_CLTV, &logger).unwrap();
649
650         // nothing happens since node[1] is in AwaitingRemoteRevoke
651         nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
652         {
653                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
654                 assert_eq!(added_monitors.len(), 0);
655                 added_monitors.clear();
656         }
657         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
658         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
659         // node[1] has nothing to do
660
661         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
662         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
663         check_added_monitors!(nodes[0], 1);
664
665         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
666         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
667         // No commitment_signed so get_event_msg's assert(len == 1) passes
668         check_added_monitors!(nodes[0], 1);
669         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
670         check_added_monitors!(nodes[1], 1);
671         // AwaitingRemoteRevoke ends here
672
673         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
674         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
675         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
676         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
677         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
678         assert_eq!(commitment_update.update_fee.is_none(), true);
679
680         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
681         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
682         check_added_monitors!(nodes[0], 1);
683         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
684
685         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
686         check_added_monitors!(nodes[1], 1);
687         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
688
689         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
690         check_added_monitors!(nodes[1], 1);
691         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
692         // No commitment_signed so get_event_msg's assert(len == 1) passes
693
694         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
695         check_added_monitors!(nodes[0], 1);
696         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
697
698         expect_pending_htlcs_forwardable!(nodes[0]);
699
700         let events = nodes[0].node.get_and_clear_pending_events();
701         assert_eq!(events.len(), 1);
702         match events[0] {
703                 Event::PaymentReceived { .. } => { },
704                 _ => panic!("Unexpected event"),
705         };
706
707         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
708
709         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
710         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
711         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
712 }
713
714 #[test]
715 fn test_update_fee() {
716         let chanmon_cfgs = create_chanmon_cfgs(2);
717         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
718         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
719         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
720         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
721         let channel_id = chan.2;
722
723         // A                                        B
724         // (1) update_fee/commitment_signed      ->
725         //                                       <- (2) revoke_and_ack
726         //                                       .- send (3) commitment_signed
727         // (4) update_fee/commitment_signed      ->
728         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
729         //                                       <- (3) commitment_signed delivered
730         // send (6) revoke_and_ack               -.
731         //                                       <- (5) deliver revoke_and_ack
732         // (6) deliver revoke_and_ack            ->
733         //                                       .- send (7) commitment_signed in response to (4)
734         //                                       <- (7) deliver commitment_signed
735         // revoke_and_ack                        ->
736
737         // Create and deliver (1)...
738         let feerate = get_feerate!(nodes[0], channel_id);
739         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
740         check_added_monitors!(nodes[0], 1);
741
742         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
743         assert_eq!(events_0.len(), 1);
744         let (update_msg, commitment_signed) = match events_0[0] {
745                         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 } } => {
746                         (update_fee.as_ref(), commitment_signed)
747                 },
748                 _ => panic!("Unexpected event"),
749         };
750         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
751
752         // Generate (2) and (3):
753         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
754         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
755         check_added_monitors!(nodes[1], 1);
756
757         // Deliver (2):
758         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
759         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
760         check_added_monitors!(nodes[0], 1);
761
762         // Create and deliver (4)...
763         nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
764         check_added_monitors!(nodes[0], 1);
765         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
766         assert_eq!(events_0.len(), 1);
767         let (update_msg, commitment_signed) = match events_0[0] {
768                         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 } } => {
769                         (update_fee.as_ref(), commitment_signed)
770                 },
771                 _ => panic!("Unexpected event"),
772         };
773
774         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
775         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
776         check_added_monitors!(nodes[1], 1);
777         // ... creating (5)
778         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
779         // No commitment_signed so get_event_msg's assert(len == 1) passes
780
781         // Handle (3), creating (6):
782         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
783         check_added_monitors!(nodes[0], 1);
784         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
785         // No commitment_signed so get_event_msg's assert(len == 1) passes
786
787         // Deliver (5):
788         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
789         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
790         check_added_monitors!(nodes[0], 1);
791
792         // Deliver (6), creating (7):
793         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
794         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
795         assert!(commitment_update.update_add_htlcs.is_empty());
796         assert!(commitment_update.update_fulfill_htlcs.is_empty());
797         assert!(commitment_update.update_fail_htlcs.is_empty());
798         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
799         assert!(commitment_update.update_fee.is_none());
800         check_added_monitors!(nodes[1], 1);
801
802         // Deliver (7)
803         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
804         check_added_monitors!(nodes[0], 1);
805         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
806         // No commitment_signed so get_event_msg's assert(len == 1) passes
807
808         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
809         check_added_monitors!(nodes[1], 1);
810         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
811
812         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
813         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
814         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
815 }
816
817 #[test]
818 fn pre_funding_lock_shutdown_test() {
819         // Test sending a shutdown prior to funding_locked after funding generation
820         let chanmon_cfgs = create_chanmon_cfgs(2);
821         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
822         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
823         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
824         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
825         mine_transaction(&nodes[0], &tx);
826         mine_transaction(&nodes[1], &tx);
827
828         nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
829         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
830         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
831         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
832         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
833
834         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
835         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
836         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
837         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
838         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
839         assert!(node_0_none.is_none());
840
841         assert!(nodes[0].node.list_channels().is_empty());
842         assert!(nodes[1].node.list_channels().is_empty());
843 }
844
845 #[test]
846 fn updates_shutdown_wait() {
847         // Test sending a shutdown with outstanding updates pending
848         let chanmon_cfgs = create_chanmon_cfgs(3);
849         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
850         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
851         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
852         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
853         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
854         let logger = test_utils::TestLogger::new();
855
856         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
857
858         nodes[0].node.close_channel(&chan_1.2).unwrap();
859         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
860         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
861         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
862         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
863
864         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
865         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
866
867         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
868
869         let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
870         let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
871         let route_1 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler0.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
872         let route_2 = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler1.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
873         unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
874         unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
875
876         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
877         check_added_monitors!(nodes[2], 1);
878         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
879         assert!(updates.update_add_htlcs.is_empty());
880         assert!(updates.update_fail_htlcs.is_empty());
881         assert!(updates.update_fail_malformed_htlcs.is_empty());
882         assert!(updates.update_fee.is_none());
883         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
884         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
885         check_added_monitors!(nodes[1], 1);
886         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
887         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
888
889         assert!(updates_2.update_add_htlcs.is_empty());
890         assert!(updates_2.update_fail_htlcs.is_empty());
891         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
892         assert!(updates_2.update_fee.is_none());
893         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
894         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
895         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
896
897         let events = nodes[0].node.get_and_clear_pending_events();
898         assert_eq!(events.len(), 1);
899         match events[0] {
900                 Event::PaymentSent { ref payment_preimage } => {
901                         assert_eq!(our_payment_preimage, *payment_preimage);
902                 },
903                 _ => panic!("Unexpected event"),
904         }
905
906         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
907         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
908         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
909         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
910         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
911         assert!(node_0_none.is_none());
912
913         assert!(nodes[0].node.list_channels().is_empty());
914
915         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
916         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
917         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
918         assert!(nodes[1].node.list_channels().is_empty());
919         assert!(nodes[2].node.list_channels().is_empty());
920 }
921
922 #[test]
923 fn htlc_fail_async_shutdown() {
924         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
925         let chanmon_cfgs = create_chanmon_cfgs(3);
926         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
927         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
928         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
929         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
930         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
931         let logger = test_utils::TestLogger::new();
932
933         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
934         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
935         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
936         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
937         check_added_monitors!(nodes[0], 1);
938         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
939         assert_eq!(updates.update_add_htlcs.len(), 1);
940         assert!(updates.update_fulfill_htlcs.is_empty());
941         assert!(updates.update_fail_htlcs.is_empty());
942         assert!(updates.update_fail_malformed_htlcs.is_empty());
943         assert!(updates.update_fee.is_none());
944
945         nodes[1].node.close_channel(&chan_1.2).unwrap();
946         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
947         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
948         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
949
950         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
951         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
952         check_added_monitors!(nodes[1], 1);
953         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
954         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
955
956         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
957         assert!(updates_2.update_add_htlcs.is_empty());
958         assert!(updates_2.update_fulfill_htlcs.is_empty());
959         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
960         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
961         assert!(updates_2.update_fee.is_none());
962
963         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
964         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
965
966         expect_payment_failed!(nodes[0], our_payment_hash, false);
967
968         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
969         assert_eq!(msg_events.len(), 2);
970         let node_0_closing_signed = match msg_events[0] {
971                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
972                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
973                         (*msg).clone()
974                 },
975                 _ => panic!("Unexpected event"),
976         };
977         match msg_events[1] {
978                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
979                         assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
980                 },
981                 _ => panic!("Unexpected event"),
982         }
983
984         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
985         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
986         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
987         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
988         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
989         assert!(node_0_none.is_none());
990
991         assert!(nodes[0].node.list_channels().is_empty());
992
993         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
994         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
995         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
996         assert!(nodes[1].node.list_channels().is_empty());
997         assert!(nodes[2].node.list_channels().is_empty());
998 }
999
1000 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1001         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1002         // messages delivered prior to disconnect
1003         let chanmon_cfgs = create_chanmon_cfgs(3);
1004         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1005         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1006         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1007         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1008         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1009
1010         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1011
1012         nodes[1].node.close_channel(&chan_1.2).unwrap();
1013         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1014         if recv_count > 0 {
1015                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
1016                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1017                 if recv_count > 1 {
1018                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
1019                 }
1020         }
1021
1022         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1023         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1024
1025         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1026         let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1027         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1028         let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1029
1030         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1031         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1032         assert!(node_1_shutdown == node_1_2nd_shutdown);
1033
1034         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1035         let node_0_2nd_shutdown = if recv_count > 0 {
1036                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1037                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1038                 node_0_2nd_shutdown
1039         } else {
1040                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1041                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1042                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1043         };
1044         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_2nd_shutdown);
1045
1046         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1047         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1048
1049         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1050         check_added_monitors!(nodes[2], 1);
1051         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1052         assert!(updates.update_add_htlcs.is_empty());
1053         assert!(updates.update_fail_htlcs.is_empty());
1054         assert!(updates.update_fail_malformed_htlcs.is_empty());
1055         assert!(updates.update_fee.is_none());
1056         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1057         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1058         check_added_monitors!(nodes[1], 1);
1059         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1060         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1061
1062         assert!(updates_2.update_add_htlcs.is_empty());
1063         assert!(updates_2.update_fail_htlcs.is_empty());
1064         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1065         assert!(updates_2.update_fee.is_none());
1066         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1067         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1068         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1069
1070         let events = nodes[0].node.get_and_clear_pending_events();
1071         assert_eq!(events.len(), 1);
1072         match events[0] {
1073                 Event::PaymentSent { ref payment_preimage } => {
1074                         assert_eq!(our_payment_preimage, *payment_preimage);
1075                 },
1076                 _ => panic!("Unexpected event"),
1077         }
1078
1079         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1080         if recv_count > 0 {
1081                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1082                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1083                 assert!(node_1_closing_signed.is_some());
1084         }
1085
1086         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1087         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1088
1089         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1090         let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1091         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1092         if recv_count == 0 {
1093                 // If all closing_signeds weren't delivered we can just resume where we left off...
1094                 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1095
1096                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1097                 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1098                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1099
1100                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1101                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1102                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1103
1104                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_3rd_shutdown);
1105                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1106
1107                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_3rd_shutdown);
1108                 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1109                 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1110
1111                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1112                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1113                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1114                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1115                 assert!(node_0_none.is_none());
1116         } else {
1117                 // If one node, however, received + responded with an identical closing_signed we end
1118                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1119                 // There isn't really anything better we can do simply, but in the future we might
1120                 // explore storing a set of recently-closed channels that got disconnected during
1121                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1122                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1123                 // transaction.
1124                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1125
1126                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1127                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1128                 assert_eq!(msg_events.len(), 1);
1129                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1130                         match action {
1131                                 &ErrorAction::SendErrorMessage { ref msg } => {
1132                                         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1133                                         assert_eq!(msg.channel_id, chan_1.2);
1134                                 },
1135                                 _ => panic!("Unexpected event!"),
1136                         }
1137                 } else { panic!("Needed SendErrorMessage close"); }
1138
1139                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1140                 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1141                 // closing_signed so we do it ourselves
1142                 check_closed_broadcast!(nodes[0], false);
1143                 check_added_monitors!(nodes[0], 1);
1144         }
1145
1146         assert!(nodes[0].node.list_channels().is_empty());
1147
1148         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1149         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1150         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1151         assert!(nodes[1].node.list_channels().is_empty());
1152         assert!(nodes[2].node.list_channels().is_empty());
1153 }
1154
1155 #[test]
1156 fn test_shutdown_rebroadcast() {
1157         do_test_shutdown_rebroadcast(0);
1158         do_test_shutdown_rebroadcast(1);
1159         do_test_shutdown_rebroadcast(2);
1160 }
1161
1162 #[test]
1163 fn fake_network_test() {
1164         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1165         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1166         let chanmon_cfgs = create_chanmon_cfgs(4);
1167         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1168         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1169         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1170
1171         // Create some initial channels
1172         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1173         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1174         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1175
1176         // Rebalance the network a bit by relaying one payment through all the channels...
1177         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1178         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1179         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1180         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1181
1182         // Send some more payments
1183         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1184         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1185         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1186
1187         // Test failure packets
1188         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1189         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1190
1191         // Add a new channel that skips 3
1192         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1193
1194         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1195         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1196         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1197         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1198         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1199         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1200         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1201
1202         // Do some rebalance loop payments, simultaneously
1203         let mut hops = Vec::with_capacity(3);
1204         hops.push(RouteHop {
1205                 pubkey: nodes[2].node.get_our_node_id(),
1206                 node_features: NodeFeatures::empty(),
1207                 short_channel_id: chan_2.0.contents.short_channel_id,
1208                 channel_features: ChannelFeatures::empty(),
1209                 fee_msat: 0,
1210                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1211         });
1212         hops.push(RouteHop {
1213                 pubkey: nodes[3].node.get_our_node_id(),
1214                 node_features: NodeFeatures::empty(),
1215                 short_channel_id: chan_3.0.contents.short_channel_id,
1216                 channel_features: ChannelFeatures::empty(),
1217                 fee_msat: 0,
1218                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1219         });
1220         hops.push(RouteHop {
1221                 pubkey: nodes[1].node.get_our_node_id(),
1222                 node_features: NodeFeatures::empty(),
1223                 short_channel_id: chan_4.0.contents.short_channel_id,
1224                 channel_features: ChannelFeatures::empty(),
1225                 fee_msat: 1000000,
1226                 cltv_expiry_delta: TEST_FINAL_CLTV,
1227         });
1228         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;
1229         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;
1230         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1231
1232         let mut hops = Vec::with_capacity(3);
1233         hops.push(RouteHop {
1234                 pubkey: nodes[3].node.get_our_node_id(),
1235                 node_features: NodeFeatures::empty(),
1236                 short_channel_id: chan_4.0.contents.short_channel_id,
1237                 channel_features: ChannelFeatures::empty(),
1238                 fee_msat: 0,
1239                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1240         });
1241         hops.push(RouteHop {
1242                 pubkey: nodes[2].node.get_our_node_id(),
1243                 node_features: NodeFeatures::empty(),
1244                 short_channel_id: chan_3.0.contents.short_channel_id,
1245                 channel_features: ChannelFeatures::empty(),
1246                 fee_msat: 0,
1247                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1248         });
1249         hops.push(RouteHop {
1250                 pubkey: nodes[1].node.get_our_node_id(),
1251                 node_features: NodeFeatures::empty(),
1252                 short_channel_id: chan_2.0.contents.short_channel_id,
1253                 channel_features: ChannelFeatures::empty(),
1254                 fee_msat: 1000000,
1255                 cltv_expiry_delta: TEST_FINAL_CLTV,
1256         });
1257         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;
1258         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;
1259         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1260
1261         // Claim the rebalances...
1262         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1263         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1264
1265         // Add a duplicate new channel from 2 to 4
1266         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1267
1268         // Send some payments across both channels
1269         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1270         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1271         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1272
1273
1274         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1275         let events = nodes[0].node.get_and_clear_pending_msg_events();
1276         assert_eq!(events.len(), 0);
1277         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);
1278
1279         //TODO: Test that routes work again here as we've been notified that the channel is full
1280
1281         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1282         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1283         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1284
1285         // Close down the channels...
1286         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1287         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1288         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1289         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1290         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1291 }
1292
1293 #[test]
1294 fn holding_cell_htlc_counting() {
1295         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1296         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1297         // commitment dance rounds.
1298         let chanmon_cfgs = create_chanmon_cfgs(3);
1299         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1300         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1301         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1302         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1303         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1304         let logger = test_utils::TestLogger::new();
1305
1306         let mut payments = Vec::new();
1307         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1308                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1309                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1310                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1311                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1312                 payments.push((payment_preimage, payment_hash));
1313         }
1314         check_added_monitors!(nodes[1], 1);
1315
1316         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1317         assert_eq!(events.len(), 1);
1318         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1319         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1320
1321         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1322         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1323         // another HTLC.
1324         let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1325         {
1326                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1327                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1328                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1329                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1330                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1331                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1332         }
1333
1334         // This should also be true if we try to forward a payment.
1335         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1336         {
1337                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1338                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1339                 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1340                 check_added_monitors!(nodes[0], 1);
1341         }
1342
1343         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1344         assert_eq!(events.len(), 1);
1345         let payment_event = SendEvent::from_event(events.pop().unwrap());
1346         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1347
1348         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1349         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1350         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1351         // fails), the second will process the resulting failure and fail the HTLC backward.
1352         expect_pending_htlcs_forwardable!(nodes[1]);
1353         expect_pending_htlcs_forwardable!(nodes[1]);
1354         check_added_monitors!(nodes[1], 1);
1355
1356         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1357         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1358         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1359
1360         let events = nodes[0].node.get_and_clear_pending_msg_events();
1361         assert_eq!(events.len(), 1);
1362         match events[0] {
1363                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1364                         assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1365                 },
1366                 _ => panic!("Unexpected event"),
1367         }
1368
1369         expect_payment_failed!(nodes[0], payment_hash_2, false);
1370
1371         // Now forward all the pending HTLCs and claim them back
1372         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1373         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1374         check_added_monitors!(nodes[2], 1);
1375
1376         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1377         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1378         check_added_monitors!(nodes[1], 1);
1379         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1380
1381         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1382         check_added_monitors!(nodes[1], 1);
1383         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1384
1385         for ref update in as_updates.update_add_htlcs.iter() {
1386                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1387         }
1388         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1389         check_added_monitors!(nodes[2], 1);
1390         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1391         check_added_monitors!(nodes[2], 1);
1392         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1393
1394         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1395         check_added_monitors!(nodes[1], 1);
1396         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1397         check_added_monitors!(nodes[1], 1);
1398         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1399
1400         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1401         check_added_monitors!(nodes[2], 1);
1402
1403         expect_pending_htlcs_forwardable!(nodes[2]);
1404
1405         let events = nodes[2].node.get_and_clear_pending_events();
1406         assert_eq!(events.len(), payments.len());
1407         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1408                 match event {
1409                         &Event::PaymentReceived { ref payment_hash, .. } => {
1410                                 assert_eq!(*payment_hash, *hash);
1411                         },
1412                         _ => panic!("Unexpected event"),
1413                 };
1414         }
1415
1416         for (preimage, _) in payments.drain(..) {
1417                 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1418         }
1419
1420         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1421 }
1422
1423 #[test]
1424 fn duplicate_htlc_test() {
1425         // Test that we accept duplicate payment_hash HTLCs across the network and that
1426         // claiming/failing them are all separate and don't affect each other
1427         let chanmon_cfgs = create_chanmon_cfgs(6);
1428         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1429         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1430         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1431
1432         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1433         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1434         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1435         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1436         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1437         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1438
1439         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1440
1441         *nodes[0].network_payment_count.borrow_mut() -= 1;
1442         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1443
1444         *nodes[0].network_payment_count.borrow_mut() -= 1;
1445         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1446
1447         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1448         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1449         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1450 }
1451
1452 #[test]
1453 fn test_duplicate_htlc_different_direction_onchain() {
1454         // Test that ChannelMonitor doesn't generate 2 preimage txn
1455         // when we have 2 HTLCs with same preimage that go across a node
1456         // in opposite directions.
1457         let chanmon_cfgs = create_chanmon_cfgs(2);
1458         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1459         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1460         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1461
1462         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1463         let logger = test_utils::TestLogger::new();
1464
1465         // balancing
1466         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1467
1468         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1469
1470         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1471         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 800_000, TEST_FINAL_CLTV, &logger).unwrap();
1472         send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1473
1474         // Provide preimage to node 0 by claiming payment
1475         nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1476         check_added_monitors!(nodes[0], 1);
1477
1478         // Broadcast node 1 commitment txn
1479         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1480
1481         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1482         let mut has_both_htlcs = 0; // check htlcs match ones committed
1483         for outp in remote_txn[0].output.iter() {
1484                 if outp.value == 800_000 / 1000 {
1485                         has_both_htlcs += 1;
1486                 } else if outp.value == 900_000 / 1000 {
1487                         has_both_htlcs += 1;
1488                 }
1489         }
1490         assert_eq!(has_both_htlcs, 2);
1491
1492         mine_transaction(&nodes[0], &remote_txn[0]);
1493         check_added_monitors!(nodes[0], 1);
1494
1495         // Check we only broadcast 1 timeout tx
1496         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1497         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()) };
1498         assert_eq!(claim_txn.len(), 5);
1499         check_spends!(claim_txn[2], chan_1.3);
1500         check_spends!(claim_txn[3], claim_txn[2]);
1501         assert_eq!(htlc_pair.0.input.len(), 1);
1502         assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1503         check_spends!(htlc_pair.0, remote_txn[0]);
1504         assert_eq!(htlc_pair.1.input.len(), 1);
1505         assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1506         check_spends!(htlc_pair.1, remote_txn[0]);
1507
1508         let events = nodes[0].node.get_and_clear_pending_msg_events();
1509         assert_eq!(events.len(), 3);
1510         for e in events {
1511                 match e {
1512                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1513                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1514                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1515                                 assert_eq!(msg.data, "Commitment or closing transaction was confirmed on chain.");
1516                         },
1517                         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, .. } } => {
1518                                 assert!(update_add_htlcs.is_empty());
1519                                 assert!(update_fail_htlcs.is_empty());
1520                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1521                                 assert!(update_fail_malformed_htlcs.is_empty());
1522                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1523                         },
1524                         _ => panic!("Unexpected event"),
1525                 }
1526         }
1527 }
1528
1529 #[test]
1530 fn test_basic_channel_reserve() {
1531         let chanmon_cfgs = create_chanmon_cfgs(2);
1532         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1533         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1534         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1535         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1536         let logger = test_utils::TestLogger::new();
1537
1538         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1539         let channel_reserve = chan_stat.channel_reserve_msat;
1540
1541         // The 2* and +1 are for the fee spike reserve.
1542         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1543         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1544         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1545         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1546         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), None, None, &Vec::new(), max_can_send + 1, TEST_FINAL_CLTV, &logger).unwrap();
1547         let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1548         match err {
1549                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1550                         match &fails[0] {
1551                                 &APIError::ChannelUnavailable{ref err} =>
1552                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1553                                 _ => panic!("Unexpected error variant"),
1554                         }
1555                 },
1556                 _ => panic!("Unexpected error variant"),
1557         }
1558         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1559         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);
1560
1561         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1562 }
1563
1564 #[test]
1565 fn test_fee_spike_violation_fails_htlc() {
1566         let chanmon_cfgs = create_chanmon_cfgs(2);
1567         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1568         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1569         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1570         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1571         let logger = test_utils::TestLogger::new();
1572
1573         macro_rules! get_route_and_payment_hash {
1574                 ($recv_value: expr) => {{
1575                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1576                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1577                         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes.last().unwrap().node.get_our_node_id(), None, None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1578                         (route, payment_hash, payment_preimage)
1579                 }}
1580         }
1581
1582         let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1583         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1584         let secp_ctx = Secp256k1::new();
1585         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1586
1587         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1588
1589         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1590         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1591         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1592         let msg = msgs::UpdateAddHTLC {
1593                 channel_id: chan.2,
1594                 htlc_id: 0,
1595                 amount_msat: htlc_msat,
1596                 payment_hash: payment_hash,
1597                 cltv_expiry: htlc_cltv,
1598                 onion_routing_packet: onion_packet,
1599         };
1600
1601         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1602
1603         // Now manually create the commitment_signed message corresponding to the update_add
1604         // nodes[0] just sent. In the code for construction of this message, "local" refers
1605         // to the sender of the message, and "remote" refers to the receiver.
1606
1607         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1608
1609         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1610
1611         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1612         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1613         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point) = {
1614                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1615                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1616                 let chan_signer = local_chan.get_signer();
1617                 let pubkeys = chan_signer.pubkeys();
1618                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1619                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1620                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
1621         };
1622         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point) = {
1623                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1624                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1625                 let chan_signer = remote_chan.get_signer();
1626                 let pubkeys = chan_signer.pubkeys();
1627                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1628                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
1629         };
1630
1631         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1632         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1633                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1634
1635         // Build the remote commitment transaction so we can sign it, and then later use the
1636         // signature for the commitment_signed message.
1637         let local_chan_balance = 1313;
1638
1639         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1640                 offered: false,
1641                 amount_msat: 3460001,
1642                 cltv_expiry: htlc_cltv,
1643                 payment_hash,
1644                 transaction_output_index: Some(1),
1645         };
1646
1647         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1648
1649         let res = {
1650                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1651                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1652                 let local_chan_signer = local_chan.get_signer();
1653                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1654                         commitment_number,
1655                         95000,
1656                         local_chan_balance,
1657                         commit_tx_keys.clone(),
1658                         feerate_per_kw,
1659                         &mut vec![(accepted_htlc_info, ())],
1660                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1661                 );
1662                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1663         };
1664
1665         let commit_signed_msg = msgs::CommitmentSigned {
1666                 channel_id: chan.2,
1667                 signature: res.0,
1668                 htlc_signatures: res.1
1669         };
1670
1671         // Send the commitment_signed message to the nodes[1].
1672         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1673         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1674
1675         // Send the RAA to nodes[1].
1676         let raa_msg = msgs::RevokeAndACK {
1677                 channel_id: chan.2,
1678                 per_commitment_secret: local_secret,
1679                 next_per_commitment_point: next_local_point
1680         };
1681         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1682
1683         let events = nodes[1].node.get_and_clear_pending_msg_events();
1684         assert_eq!(events.len(), 1);
1685         // Make sure the HTLC failed in the way we expect.
1686         match events[0] {
1687                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1688                         assert_eq!(update_fail_htlcs.len(), 1);
1689                         update_fail_htlcs[0].clone()
1690                 },
1691                 _ => panic!("Unexpected event"),
1692         };
1693         nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1694
1695         check_added_monitors!(nodes[1], 2);
1696 }
1697
1698 #[test]
1699 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1700         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1701         // Set the fee rate for the channel very high, to the point where the fundee
1702         // sending any above-dust amount would result in a channel reserve violation.
1703         // In this test we check that we would be prevented from sending an HTLC in
1704         // this situation.
1705         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1706         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1707         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1708         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1709         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1710         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1711         let logger = test_utils::TestLogger::new();
1712
1713         macro_rules! get_route_and_payment_hash {
1714                 ($recv_value: expr) => {{
1715                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1716                         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1717                         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.first().unwrap().node.get_our_node_id(), None, None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1718                         (route, payment_hash, payment_preimage)
1719                 }}
1720         }
1721
1722         let (route, our_payment_hash, _) = get_route_and_payment_hash!(4843000);
1723         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1724                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1725         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1726         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);
1727 }
1728
1729 #[test]
1730 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1731         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1732         // Set the fee rate for the channel very high, to the point where the funder
1733         // receiving 1 update_add_htlc would result in them closing the channel due
1734         // to channel reserve violation. This close could also happen if the fee went
1735         // up a more realistic amount, but many HTLCs were outstanding at the time of
1736         // the update_add_htlc.
1737         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1738         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1739         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1740         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1741         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1742         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1743         let logger = test_utils::TestLogger::new();
1744
1745         macro_rules! get_route_and_payment_hash {
1746                 ($recv_value: expr) => {{
1747                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1748                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1749                         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.first().unwrap().node.get_our_node_id(), None, None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1750                         (route, payment_hash, payment_preimage)
1751                 }}
1752         }
1753
1754         let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1755         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1756         let secp_ctx = Secp256k1::new();
1757         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1758         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1759         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1760         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1761         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1762         let msg = msgs::UpdateAddHTLC {
1763                 channel_id: chan.2,
1764                 htlc_id: 1,
1765                 amount_msat: htlc_msat + 1,
1766                 payment_hash: payment_hash,
1767                 cltv_expiry: htlc_cltv,
1768                 onion_routing_packet: onion_packet,
1769         };
1770
1771         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1772         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1773         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);
1774         assert_eq!(nodes[0].node.list_channels().len(), 0);
1775         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1776         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1777         check_added_monitors!(nodes[0], 1);
1778 }
1779
1780 #[test]
1781 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1782         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1783         // calculating our commitment transaction fee (this was previously broken).
1784         let chanmon_cfgs = create_chanmon_cfgs(2);
1785         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1786         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1787         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1788
1789         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1790         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1791         // transaction fee with 0 HTLCs (183 sats)).
1792         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98817000, InitFeatures::known(), InitFeatures::known());
1793
1794         let dust_amt = 546000; // Dust amount
1795         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1796         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1797         // commitment transaction fee.
1798         let (_, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1799 }
1800
1801 #[test]
1802 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1803         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1804         // calculating our counterparty's commitment transaction fee (this was previously broken).
1805         let chanmon_cfgs = create_chanmon_cfgs(2);
1806         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1807         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1808         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1809         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1810
1811         let payment_amt = 46000; // Dust amount
1812         // In the previous code, these first four payments would succeed.
1813         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1814         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1815         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1816         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1817
1818         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1819         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1820         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1821         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1822         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1823         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1824
1825         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1826         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1827         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1828         let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1829 }
1830
1831 #[test]
1832 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1833         let chanmon_cfgs = create_chanmon_cfgs(3);
1834         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1835         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1836         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1837         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1838         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1839         let logger = test_utils::TestLogger::new();
1840
1841         macro_rules! get_route_and_payment_hash {
1842                 ($recv_value: expr) => {{
1843                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1844                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1845                         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), None, None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1846                         (route, payment_hash, payment_preimage)
1847                 }}
1848         }
1849
1850         let feemsat = 239;
1851         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1852         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1853         let feerate = get_feerate!(nodes[0], chan.2);
1854
1855         // Add a 2* and +1 for the fee spike reserve.
1856         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1857         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;
1858         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1859
1860         // Add a pending HTLC.
1861         let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1862         let payment_event_1 = {
1863                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1864                 check_added_monitors!(nodes[0], 1);
1865
1866                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1867                 assert_eq!(events.len(), 1);
1868                 SendEvent::from_event(events.remove(0))
1869         };
1870         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1871
1872         // Attempt to trigger a channel reserve violation --> payment failure.
1873         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1874         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;
1875         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1876         let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1877
1878         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1879         let secp_ctx = Secp256k1::new();
1880         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1881         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1882         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1883         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1884         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1885         let msg = msgs::UpdateAddHTLC {
1886                 channel_id: chan.2,
1887                 htlc_id: 1,
1888                 amount_msat: htlc_msat + 1,
1889                 payment_hash: our_payment_hash_1,
1890                 cltv_expiry: htlc_cltv,
1891                 onion_routing_packet: onion_packet,
1892         };
1893
1894         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1895         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1896         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1897         assert_eq!(nodes[1].node.list_channels().len(), 1);
1898         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1899         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1900         check_added_monitors!(nodes[1], 1);
1901 }
1902
1903 #[test]
1904 fn test_inbound_outbound_capacity_is_not_zero() {
1905         let chanmon_cfgs = create_chanmon_cfgs(2);
1906         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1907         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1908         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1909         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1910         let channels0 = node_chanmgrs[0].list_channels();
1911         let channels1 = node_chanmgrs[1].list_channels();
1912         assert_eq!(channels0.len(), 1);
1913         assert_eq!(channels1.len(), 1);
1914
1915         assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1916         assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1917
1918         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1919         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1920 }
1921
1922 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1923         (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1924 }
1925
1926 #[test]
1927 fn test_channel_reserve_holding_cell_htlcs() {
1928         let chanmon_cfgs = create_chanmon_cfgs(3);
1929         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1930         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1931         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1932         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1933         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1934         let logger = test_utils::TestLogger::new();
1935
1936         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1937         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1938
1939         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1940         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1941
1942         macro_rules! get_route_and_payment_hash {
1943                 ($recv_value: expr) => {{
1944                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1945                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1946                         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), None, None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1947                         (route, payment_hash, payment_preimage)
1948                 }}
1949         }
1950
1951         macro_rules! expect_forward {
1952                 ($node: expr) => {{
1953                         let mut events = $node.node.get_and_clear_pending_msg_events();
1954                         assert_eq!(events.len(), 1);
1955                         check_added_monitors!($node, 1);
1956                         let payment_event = SendEvent::from_event(events.remove(0));
1957                         payment_event
1958                 }}
1959         }
1960
1961         let feemsat = 239; // somehow we know?
1962         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1963         let feerate = get_feerate!(nodes[0], chan_1.2);
1964
1965         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1966
1967         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1968         {
1969                 let (mut route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0);
1970                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1971                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1972                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1973                         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)));
1974                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1975                 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);
1976         }
1977
1978         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1979         // nodes[0]'s wealth
1980         loop {
1981                 let amt_msat = recv_value_0 + total_fee_msat;
1982                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1983                 // Also, ensure that each payment has enough to be over the dust limit to
1984                 // ensure it'll be included in each commit tx fee calculation.
1985                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1986                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1987                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1988                         break;
1989                 }
1990                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1991
1992                 let (stat01_, stat11_, stat12_, stat22_) = (
1993                         get_channel_value_stat!(nodes[0], chan_1.2),
1994                         get_channel_value_stat!(nodes[1], chan_1.2),
1995                         get_channel_value_stat!(nodes[1], chan_2.2),
1996                         get_channel_value_stat!(nodes[2], chan_2.2),
1997                 );
1998
1999                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
2000                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
2001                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
2002                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
2003                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
2004         }
2005
2006         // adding pending output.
2007         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
2008         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2009         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2010         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2011         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2012         // cases where 1 msat over X amount will cause a payment failure, but anything less than
2013         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2014         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2015         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2016         // policy.
2017         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2018         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2019         let amt_msat_1 = recv_value_1 + total_fee_msat;
2020
2021         let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2022         let payment_event_1 = {
2023                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
2024                 check_added_monitors!(nodes[0], 1);
2025
2026                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2027                 assert_eq!(events.len(), 1);
2028                 SendEvent::from_event(events.remove(0))
2029         };
2030         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2031
2032         // channel reserve test with htlc pending output > 0
2033         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2034         {
2035                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2036                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2037                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2038                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2039         }
2040
2041         // split the rest to test holding cell
2042         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2043         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2044         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2045         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2046         {
2047                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2048                 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);
2049         }
2050
2051         // now see if they go through on both sides
2052         let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2053         // but this will stuck in the holding cell
2054         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2055         check_added_monitors!(nodes[0], 0);
2056         let events = nodes[0].node.get_and_clear_pending_events();
2057         assert_eq!(events.len(), 0);
2058
2059         // test with outbound holding cell amount > 0
2060         {
2061                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2062                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2063                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2064                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2065                 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);
2066         }
2067
2068         let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2069         // this will also stuck in the holding cell
2070         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2071         check_added_monitors!(nodes[0], 0);
2072         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2073         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2074
2075         // flush the pending htlc
2076         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2077         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2078         check_added_monitors!(nodes[1], 1);
2079
2080         // the pending htlc should be promoted to committed
2081         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2082         check_added_monitors!(nodes[0], 1);
2083         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2084
2085         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2086         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2087         // No commitment_signed so get_event_msg's assert(len == 1) passes
2088         check_added_monitors!(nodes[0], 1);
2089
2090         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2091         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2092         check_added_monitors!(nodes[1], 1);
2093
2094         expect_pending_htlcs_forwardable!(nodes[1]);
2095
2096         let ref payment_event_11 = expect_forward!(nodes[1]);
2097         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2098         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2099
2100         expect_pending_htlcs_forwardable!(nodes[2]);
2101         expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2102
2103         // flush the htlcs in the holding cell
2104         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2105         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2106         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2107         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2108         expect_pending_htlcs_forwardable!(nodes[1]);
2109
2110         let ref payment_event_3 = expect_forward!(nodes[1]);
2111         assert_eq!(payment_event_3.msgs.len(), 2);
2112         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2113         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2114
2115         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2116         expect_pending_htlcs_forwardable!(nodes[2]);
2117
2118         let events = nodes[2].node.get_and_clear_pending_events();
2119         assert_eq!(events.len(), 2);
2120         match events[0] {
2121                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2122                         assert_eq!(our_payment_hash_21, *payment_hash);
2123                         assert_eq!(*payment_secret, None);
2124                         assert_eq!(recv_value_21, amt);
2125                 },
2126                 _ => panic!("Unexpected event"),
2127         }
2128         match events[1] {
2129                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2130                         assert_eq!(our_payment_hash_22, *payment_hash);
2131                         assert_eq!(None, *payment_secret);
2132                         assert_eq!(recv_value_22, amt);
2133                 },
2134                 _ => panic!("Unexpected event"),
2135         }
2136
2137         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2138         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2139         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2140
2141         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2142         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2143         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2144
2145         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2146         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);
2147         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2148         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2149         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2150
2151         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2152         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2153 }
2154
2155 #[test]
2156 fn channel_reserve_in_flight_removes() {
2157         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2158         // can send to its counterparty, but due to update ordering, the other side may not yet have
2159         // considered those HTLCs fully removed.
2160         // This tests that we don't count HTLCs which will not be included in the next remote
2161         // commitment transaction towards the reserve value (as it implies no commitment transaction
2162         // will be generated which violates the remote reserve value).
2163         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2164         // To test this we:
2165         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2166         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2167         //    you only consider the value of the first HTLC, it may not),
2168         //  * start routing a third HTLC from A to B,
2169         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2170         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2171         //  * deliver the first fulfill from B
2172         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2173         //    claim,
2174         //  * deliver A's response CS and RAA.
2175         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2176         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2177         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2178         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2179         let chanmon_cfgs = create_chanmon_cfgs(2);
2180         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2181         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2182         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2183         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2184         let logger = test_utils::TestLogger::new();
2185
2186         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2187         // Route the first two HTLCs.
2188         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2189         let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2190
2191         // Start routing the third HTLC (this is just used to get everyone in the right state).
2192         let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2193         let send_1 = {
2194                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2195                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
2196                 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2197                 check_added_monitors!(nodes[0], 1);
2198                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2199                 assert_eq!(events.len(), 1);
2200                 SendEvent::from_event(events.remove(0))
2201         };
2202
2203         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2204         // initial fulfill/CS.
2205         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2206         check_added_monitors!(nodes[1], 1);
2207         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2208
2209         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2210         // remove the second HTLC when we send the HTLC back from B to A.
2211         assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2212         check_added_monitors!(nodes[1], 1);
2213         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2214
2215         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2216         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2217         check_added_monitors!(nodes[0], 1);
2218         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2219         expect_payment_sent!(nodes[0], payment_preimage_1);
2220
2221         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2222         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2223         check_added_monitors!(nodes[1], 1);
2224         // B is already AwaitingRAA, so cant generate a CS here
2225         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2226
2227         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2228         check_added_monitors!(nodes[1], 1);
2229         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2230
2231         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2232         check_added_monitors!(nodes[0], 1);
2233         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2234
2235         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2236         check_added_monitors!(nodes[1], 1);
2237         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2238
2239         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2240         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2241         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2242         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2243         // on-chain as necessary).
2244         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2245         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2246         check_added_monitors!(nodes[0], 1);
2247         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2248         expect_payment_sent!(nodes[0], payment_preimage_2);
2249
2250         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2251         check_added_monitors!(nodes[1], 1);
2252         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2253
2254         expect_pending_htlcs_forwardable!(nodes[1]);
2255         expect_payment_received!(nodes[1], payment_hash_3, 100000);
2256
2257         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2258         // resolve the second HTLC from A's point of view.
2259         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2260         check_added_monitors!(nodes[0], 1);
2261         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2262
2263         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2264         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2265         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2266         let send_2 = {
2267                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2268                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &[], 10000, TEST_FINAL_CLTV, &logger).unwrap();
2269                 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2270                 check_added_monitors!(nodes[1], 1);
2271                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2272                 assert_eq!(events.len(), 1);
2273                 SendEvent::from_event(events.remove(0))
2274         };
2275
2276         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2277         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2278         check_added_monitors!(nodes[0], 1);
2279         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2280
2281         // Now just resolve all the outstanding messages/HTLCs for completeness...
2282
2283         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2284         check_added_monitors!(nodes[1], 1);
2285         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2286
2287         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2288         check_added_monitors!(nodes[1], 1);
2289
2290         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2291         check_added_monitors!(nodes[0], 1);
2292         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2293
2294         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2295         check_added_monitors!(nodes[1], 1);
2296         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2297
2298         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2299         check_added_monitors!(nodes[0], 1);
2300
2301         expect_pending_htlcs_forwardable!(nodes[0]);
2302         expect_payment_received!(nodes[0], payment_hash_4, 10000);
2303
2304         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2305         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2306 }
2307
2308 #[test]
2309 fn channel_monitor_network_test() {
2310         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2311         // tests that ChannelMonitor is able to recover from various states.
2312         let chanmon_cfgs = create_chanmon_cfgs(5);
2313         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2314         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2315         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2316
2317         // Create some initial channels
2318         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2319         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2320         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2321         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2322
2323         // Make sure all nodes are at the same starting height
2324         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2325         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2326         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2327         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2328         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2329
2330         // Rebalance the network a bit by relaying one payment through all the channels...
2331         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2332         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2333         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2334         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2335
2336         // Simple case with no pending HTLCs:
2337         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2338         check_added_monitors!(nodes[1], 1);
2339         check_closed_broadcast!(nodes[1], false);
2340         {
2341                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2342                 assert_eq!(node_txn.len(), 1);
2343                 mine_transaction(&nodes[0], &node_txn[0]);
2344                 check_added_monitors!(nodes[0], 1);
2345                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2346         }
2347         check_closed_broadcast!(nodes[0], true);
2348         assert_eq!(nodes[0].node.list_channels().len(), 0);
2349         assert_eq!(nodes[1].node.list_channels().len(), 1);
2350
2351         // One pending HTLC is discarded by the force-close:
2352         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2353
2354         // Simple case of one pending HTLC to HTLC-Timeout
2355         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2356         check_closed_broadcast!(nodes[1], false);
2357         check_added_monitors!(nodes[1], 1);
2358         {
2359                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2360                 mine_transaction(&nodes[2], &node_txn[0]);
2361                 check_added_monitors!(nodes[2], 1);
2362                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2363         }
2364         check_closed_broadcast!(nodes[2], true);
2365         assert_eq!(nodes[1].node.list_channels().len(), 0);
2366         assert_eq!(nodes[2].node.list_channels().len(), 1);
2367
2368         macro_rules! claim_funds {
2369                 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2370                         {
2371                                 assert!($node.node.claim_funds($preimage, &None, $amount));
2372                                 check_added_monitors!($node, 1);
2373
2374                                 let events = $node.node.get_and_clear_pending_msg_events();
2375                                 assert_eq!(events.len(), 1);
2376                                 match events[0] {
2377                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2378                                                 assert!(update_add_htlcs.is_empty());
2379                                                 assert!(update_fail_htlcs.is_empty());
2380                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2381                                         },
2382                                         _ => panic!("Unexpected event"),
2383                                 };
2384                         }
2385                 }
2386         }
2387
2388         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2389         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2390         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2391         check_added_monitors!(nodes[2], 1);
2392         check_closed_broadcast!(nodes[2], false);
2393         let node2_commitment_txid;
2394         {
2395                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2396                 node2_commitment_txid = node_txn[0].txid();
2397
2398                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2399                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2400                 mine_transaction(&nodes[3], &node_txn[0]);
2401                 check_added_monitors!(nodes[3], 1);
2402                 check_preimage_claim(&nodes[3], &node_txn);
2403         }
2404         check_closed_broadcast!(nodes[3], true);
2405         assert_eq!(nodes[2].node.list_channels().len(), 0);
2406         assert_eq!(nodes[3].node.list_channels().len(), 1);
2407
2408         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2409         // confusing us in the following tests.
2410         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().remove(&OutPoint { txid: chan_3.3.txid(), index: 0 }).unwrap();
2411
2412         // One pending HTLC to time out:
2413         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2414         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2415         // buffer space).
2416
2417         let (close_chan_update_1, close_chan_update_2) = {
2418                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2419                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2420                 assert_eq!(events.len(), 2);
2421                 let close_chan_update_1 = match events[0] {
2422                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2423                                 msg.clone()
2424                         },
2425                         _ => panic!("Unexpected event"),
2426                 };
2427                 match events[1] {
2428                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2429                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2430                         },
2431                         _ => panic!("Unexpected event"),
2432                 }
2433                 check_added_monitors!(nodes[3], 1);
2434
2435                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2436                 {
2437                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2438                         node_txn.retain(|tx| {
2439                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2440                                         false
2441                                 } else { true }
2442                         });
2443                 }
2444
2445                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2446
2447                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2448                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2449
2450                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2451                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2452                 assert_eq!(events.len(), 2);
2453                 let close_chan_update_2 = match events[0] {
2454                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2455                                 msg.clone()
2456                         },
2457                         _ => panic!("Unexpected event"),
2458                 };
2459                 match events[1] {
2460                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2461                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2462                         },
2463                         _ => panic!("Unexpected event"),
2464                 }
2465                 check_added_monitors!(nodes[4], 1);
2466                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2467
2468                 mine_transaction(&nodes[4], &node_txn[0]);
2469                 check_preimage_claim(&nodes[4], &node_txn);
2470                 (close_chan_update_1, close_chan_update_2)
2471         };
2472         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2473         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2474         assert_eq!(nodes[3].node.list_channels().len(), 0);
2475         assert_eq!(nodes[4].node.list_channels().len(), 0);
2476
2477         nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().insert(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon);
2478 }
2479
2480 #[test]
2481 fn test_justice_tx() {
2482         // Test justice txn built on revoked HTLC-Success tx, against both sides
2483         let mut alice_config = UserConfig::default();
2484         alice_config.channel_options.announced_channel = true;
2485         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2486         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2487         let mut bob_config = UserConfig::default();
2488         bob_config.channel_options.announced_channel = true;
2489         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2490         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2491         let user_cfgs = [Some(alice_config), Some(bob_config)];
2492         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2493         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2494         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2495         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2496         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2497         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2498         // Create some new channels:
2499         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2500
2501         // A pending HTLC which will be revoked:
2502         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2503         // Get the will-be-revoked local txn from nodes[0]
2504         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2505         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2506         assert_eq!(revoked_local_txn[0].input.len(), 1);
2507         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2508         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2509         assert_eq!(revoked_local_txn[1].input.len(), 1);
2510         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2511         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2512         // Revoke the old state
2513         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2514
2515         {
2516                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2517                 {
2518                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2519                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2520                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2521
2522                         check_spends!(node_txn[0], revoked_local_txn[0]);
2523                         node_txn.swap_remove(0);
2524                         node_txn.truncate(1);
2525                 }
2526                 check_added_monitors!(nodes[1], 1);
2527                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2528
2529                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2530                 // Verify broadcast of revoked HTLC-timeout
2531                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2532                 check_added_monitors!(nodes[0], 1);
2533                 // Broadcast revoked HTLC-timeout on node 1
2534                 mine_transaction(&nodes[1], &node_txn[1]);
2535                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2536         }
2537         get_announce_close_broadcast_events(&nodes, 0, 1);
2538
2539         assert_eq!(nodes[0].node.list_channels().len(), 0);
2540         assert_eq!(nodes[1].node.list_channels().len(), 0);
2541
2542         // We test justice_tx build by A on B's revoked HTLC-Success tx
2543         // Create some new channels:
2544         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2545         {
2546                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2547                 node_txn.clear();
2548         }
2549
2550         // A pending HTLC which will be revoked:
2551         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2552         // Get the will-be-revoked local txn from B
2553         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2554         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2555         assert_eq!(revoked_local_txn[0].input.len(), 1);
2556         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2557         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2558         // Revoke the old state
2559         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2560         {
2561                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2562                 {
2563                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2564                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2565                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2566
2567                         check_spends!(node_txn[0], revoked_local_txn[0]);
2568                         node_txn.swap_remove(0);
2569                 }
2570                 check_added_monitors!(nodes[0], 1);
2571                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2572
2573                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2574                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2575                 check_added_monitors!(nodes[1], 1);
2576                 mine_transaction(&nodes[0], &node_txn[1]);
2577                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2578         }
2579         get_announce_close_broadcast_events(&nodes, 0, 1);
2580         assert_eq!(nodes[0].node.list_channels().len(), 0);
2581         assert_eq!(nodes[1].node.list_channels().len(), 0);
2582 }
2583
2584 #[test]
2585 fn revoked_output_claim() {
2586         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2587         // transaction is broadcast by its counterparty
2588         let chanmon_cfgs = create_chanmon_cfgs(2);
2589         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2590         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2591         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2592         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2593         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2594         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2595         assert_eq!(revoked_local_txn.len(), 1);
2596         // Only output is the full channel value back to nodes[0]:
2597         assert_eq!(revoked_local_txn[0].output.len(), 1);
2598         // Send a payment through, updating everyone's latest commitment txn
2599         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2600
2601         // Inform nodes[1] that nodes[0] broadcast a stale tx
2602         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2603         check_added_monitors!(nodes[1], 1);
2604         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2605         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2606
2607         check_spends!(node_txn[0], revoked_local_txn[0]);
2608         check_spends!(node_txn[1], chan_1.3);
2609
2610         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2611         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2612         get_announce_close_broadcast_events(&nodes, 0, 1);
2613         check_added_monitors!(nodes[0], 1)
2614 }
2615
2616 #[test]
2617 fn claim_htlc_outputs_shared_tx() {
2618         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2619         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2620         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2621         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2622         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2623         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2624
2625         // Create some new channel:
2626         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2627
2628         // Rebalance the network to generate htlc in the two directions
2629         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2630         // 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
2631         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2632         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2633
2634         // Get the will-be-revoked local txn from node[0]
2635         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2636         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2637         assert_eq!(revoked_local_txn[0].input.len(), 1);
2638         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2639         assert_eq!(revoked_local_txn[1].input.len(), 1);
2640         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2641         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2642         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2643
2644         //Revoke the old state
2645         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2646
2647         {
2648                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2649                 check_added_monitors!(nodes[0], 1);
2650                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2651                 check_added_monitors!(nodes[1], 1);
2652                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2653                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2654
2655                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2656                 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2657
2658                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2659                 check_spends!(node_txn[0], revoked_local_txn[0]);
2660
2661                 let mut witness_lens = BTreeSet::new();
2662                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2663                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2664                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2665                 assert_eq!(witness_lens.len(), 3);
2666                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2667                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2668                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2669
2670                 // Next nodes[1] broadcasts its current local tx state:
2671                 assert_eq!(node_txn[1].input.len(), 1);
2672                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2673
2674                 assert_eq!(node_txn[2].input.len(), 1);
2675                 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2676                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2677                 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2678                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2679                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2680         }
2681         get_announce_close_broadcast_events(&nodes, 0, 1);
2682         assert_eq!(nodes[0].node.list_channels().len(), 0);
2683         assert_eq!(nodes[1].node.list_channels().len(), 0);
2684 }
2685
2686 #[test]
2687 fn claim_htlc_outputs_single_tx() {
2688         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2689         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2690         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2691         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2692         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2693         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2694
2695         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2696
2697         // Rebalance the network to generate htlc in the two directions
2698         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2699         // 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
2700         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2701         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2702         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2703
2704         // Get the will-be-revoked local txn from node[0]
2705         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2706
2707         //Revoke the old state
2708         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2709
2710         {
2711                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2712                 check_added_monitors!(nodes[0], 1);
2713                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2714                 check_added_monitors!(nodes[1], 1);
2715                 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2716
2717                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2718                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2719
2720                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2721                 assert_eq!(node_txn.len(), 9);
2722                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2723                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2724                 // 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)
2725                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2726
2727                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2728                 assert_eq!(node_txn[0].input.len(), 1);
2729                 check_spends!(node_txn[0], chan_1.3);
2730                 assert_eq!(node_txn[1].input.len(), 1);
2731                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2732                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2733                 check_spends!(node_txn[1], node_txn[0]);
2734
2735                 // Justice transactions are indices 1-2-4
2736                 assert_eq!(node_txn[2].input.len(), 1);
2737                 assert_eq!(node_txn[3].input.len(), 1);
2738                 assert_eq!(node_txn[4].input.len(), 1);
2739
2740                 check_spends!(node_txn[2], revoked_local_txn[0]);
2741                 check_spends!(node_txn[3], revoked_local_txn[0]);
2742                 check_spends!(node_txn[4], revoked_local_txn[0]);
2743
2744                 let mut witness_lens = BTreeSet::new();
2745                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2746                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2747                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2748                 assert_eq!(witness_lens.len(), 3);
2749                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2750                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2751                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2752         }
2753         get_announce_close_broadcast_events(&nodes, 0, 1);
2754         assert_eq!(nodes[0].node.list_channels().len(), 0);
2755         assert_eq!(nodes[1].node.list_channels().len(), 0);
2756 }
2757
2758 #[test]
2759 fn test_htlc_on_chain_success() {
2760         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2761         // the preimage backward accordingly. So here we test that ChannelManager is
2762         // broadcasting the right event to other nodes in payment path.
2763         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2764         // A --------------------> B ----------------------> C (preimage)
2765         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2766         // commitment transaction was broadcast.
2767         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2768         // towards B.
2769         // B should be able to claim via preimage if A then broadcasts its local tx.
2770         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2771         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2772         // PaymentSent event).
2773
2774         let chanmon_cfgs = create_chanmon_cfgs(3);
2775         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2776         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2777         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2778
2779         // Create some initial channels
2780         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2781         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2782
2783         // Rebalance the network a bit by relaying one payment through all the channels...
2784         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2785         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2786
2787         let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2788         let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2789
2790         // Broadcast legit commitment tx from C on B's chain
2791         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2792         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2793         assert_eq!(commitment_tx.len(), 1);
2794         check_spends!(commitment_tx[0], chan_2.3);
2795         nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2796         nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2797         check_added_monitors!(nodes[2], 2);
2798         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2799         assert!(updates.update_add_htlcs.is_empty());
2800         assert!(updates.update_fail_htlcs.is_empty());
2801         assert!(updates.update_fail_malformed_htlcs.is_empty());
2802         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2803
2804         mine_transaction(&nodes[2], &commitment_tx[0]);
2805         check_closed_broadcast!(nodes[2], true);
2806         check_added_monitors!(nodes[2], 1);
2807         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)
2808         assert_eq!(node_txn.len(), 5);
2809         assert_eq!(node_txn[0], node_txn[3]);
2810         assert_eq!(node_txn[1], node_txn[4]);
2811         assert_eq!(node_txn[2], commitment_tx[0]);
2812         check_spends!(node_txn[0], commitment_tx[0]);
2813         check_spends!(node_txn[1], commitment_tx[0]);
2814         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2815         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2816         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2817         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2818         assert_eq!(node_txn[0].lock_time, 0);
2819         assert_eq!(node_txn[1].lock_time, 0);
2820
2821         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2822         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2823         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2824         {
2825                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2826                 assert_eq!(added_monitors.len(), 1);
2827                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2828                 added_monitors.clear();
2829         }
2830         let events = nodes[1].node.get_and_clear_pending_msg_events();
2831         {
2832                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2833                 assert_eq!(added_monitors.len(), 2);
2834                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2835                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2836                 added_monitors.clear();
2837         }
2838         assert_eq!(events.len(), 3);
2839         match events[0] {
2840                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2841                 _ => panic!("Unexpected event"),
2842         }
2843         match events[1] {
2844                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2845                 _ => panic!("Unexpected event"),
2846         }
2847
2848         match events[2] {
2849                 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, .. } } => {
2850                         assert!(update_add_htlcs.is_empty());
2851                         assert!(update_fail_htlcs.is_empty());
2852                         assert_eq!(update_fulfill_htlcs.len(), 1);
2853                         assert!(update_fail_malformed_htlcs.is_empty());
2854                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2855                 },
2856                 _ => panic!("Unexpected event"),
2857         };
2858         macro_rules! check_tx_local_broadcast {
2859                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2860                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2861                         assert_eq!(node_txn.len(), 5);
2862                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2863                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2864                         check_spends!(node_txn[0], $commitment_tx);
2865                         check_spends!(node_txn[1], $commitment_tx);
2866                         assert_ne!(node_txn[0].lock_time, 0);
2867                         assert_ne!(node_txn[1].lock_time, 0);
2868                         if $htlc_offered {
2869                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2870                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2871                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2872                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2873                         } else {
2874                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2875                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2876                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2877                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2878                         }
2879                         check_spends!(node_txn[2], $chan_tx);
2880                         check_spends!(node_txn[3], node_txn[2]);
2881                         check_spends!(node_txn[4], node_txn[2]);
2882                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2883                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2884                         assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2885                         assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2886                         assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2887                         assert_ne!(node_txn[3].lock_time, 0);
2888                         assert_ne!(node_txn[4].lock_time, 0);
2889                         node_txn.clear();
2890                 } }
2891         }
2892         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2893         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2894         // timeout-claim of the output that nodes[2] just claimed via success.
2895         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2896
2897         // Broadcast legit commitment tx from A on B's chain
2898         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2899         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2900         check_spends!(commitment_tx[0], chan_1.3);
2901         mine_transaction(&nodes[1], &commitment_tx[0]);
2902         check_closed_broadcast!(nodes[1], true);
2903         check_added_monitors!(nodes[1], 1);
2904         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2905         assert_eq!(node_txn.len(), 4);
2906         check_spends!(node_txn[0], commitment_tx[0]);
2907         assert_eq!(node_txn[0].input.len(), 2);
2908         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2909         assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2910         assert_eq!(node_txn[0].lock_time, 0);
2911         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2912         check_spends!(node_txn[1], chan_1.3);
2913         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2914         check_spends!(node_txn[2], node_txn[1]);
2915         check_spends!(node_txn[3], node_txn[1]);
2916         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2917         // we already checked the same situation with A.
2918
2919         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2920         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2921         connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] });
2922         check_closed_broadcast!(nodes[0], true);
2923         check_added_monitors!(nodes[0], 1);
2924         let events = nodes[0].node.get_and_clear_pending_events();
2925         assert_eq!(events.len(), 2);
2926         let mut first_claimed = false;
2927         for event in events {
2928                 match event {
2929                         Event::PaymentSent { payment_preimage } => {
2930                                 if payment_preimage == our_payment_preimage {
2931                                         assert!(!first_claimed);
2932                                         first_claimed = true;
2933                                 } else {
2934                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2935                                 }
2936                         },
2937                         _ => panic!("Unexpected event"),
2938                 }
2939         }
2940         check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2941 }
2942
2943 #[test]
2944 fn test_htlc_on_chain_timeout() {
2945         // Test that in case of a unilateral close onchain, we detect the state of output and
2946         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2947         // broadcasting the right event to other nodes in payment path.
2948         // A ------------------> B ----------------------> C (timeout)
2949         //    B's commitment tx                 C's commitment tx
2950         //            \                                  \
2951         //         B's HTLC timeout tx               B's timeout tx
2952
2953         let chanmon_cfgs = create_chanmon_cfgs(3);
2954         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2955         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2956         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2957
2958         // Create some intial channels
2959         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2960         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2961
2962         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2963         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2964         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2965
2966         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2967
2968         // Broadcast legit commitment tx from C on B's chain
2969         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2970         check_spends!(commitment_tx[0], chan_2.3);
2971         nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2972         check_added_monitors!(nodes[2], 0);
2973         expect_pending_htlcs_forwardable!(nodes[2]);
2974         check_added_monitors!(nodes[2], 1);
2975
2976         let events = nodes[2].node.get_and_clear_pending_msg_events();
2977         assert_eq!(events.len(), 1);
2978         match events[0] {
2979                 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, .. } } => {
2980                         assert!(update_add_htlcs.is_empty());
2981                         assert!(!update_fail_htlcs.is_empty());
2982                         assert!(update_fulfill_htlcs.is_empty());
2983                         assert!(update_fail_malformed_htlcs.is_empty());
2984                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2985                 },
2986                 _ => panic!("Unexpected event"),
2987         };
2988         mine_transaction(&nodes[2], &commitment_tx[0]);
2989         check_closed_broadcast!(nodes[2], true);
2990         check_added_monitors!(nodes[2], 1);
2991         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2992         assert_eq!(node_txn.len(), 1);
2993         check_spends!(node_txn[0], chan_2.3);
2994         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2995
2996         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2997         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2998         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2999         mine_transaction(&nodes[1], &commitment_tx[0]);
3000         let timeout_tx;
3001         {
3002                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3003                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
3004                 assert_eq!(node_txn[0], node_txn[3]);
3005                 assert_eq!(node_txn[1], node_txn[4]);
3006
3007                 check_spends!(node_txn[2], commitment_tx[0]);
3008                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3009
3010                 check_spends!(node_txn[0], chan_2.3);
3011                 check_spends!(node_txn[1], node_txn[0]);
3012                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3013                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3014
3015                 timeout_tx = node_txn[2].clone();
3016                 node_txn.clear();
3017         }
3018
3019         mine_transaction(&nodes[1], &timeout_tx);
3020         check_added_monitors!(nodes[1], 1);
3021         check_closed_broadcast!(nodes[1], true);
3022         {
3023                 // B will rebroadcast a fee-bumped timeout transaction here.
3024                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3025                 assert_eq!(node_txn.len(), 1);
3026                 check_spends!(node_txn[0], commitment_tx[0]);
3027         }
3028
3029         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3030         {
3031                 // B will rebroadcast its own holder commitment transaction here...just because
3032                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3033                 assert_eq!(node_txn.len(), 1);
3034                 check_spends!(node_txn[0], chan_2.3);
3035         }
3036
3037         expect_pending_htlcs_forwardable!(nodes[1]);
3038         check_added_monitors!(nodes[1], 1);
3039         let events = nodes[1].node.get_and_clear_pending_msg_events();
3040         assert_eq!(events.len(), 1);
3041         match events[0] {
3042                 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, .. } } => {
3043                         assert!(update_add_htlcs.is_empty());
3044                         assert!(!update_fail_htlcs.is_empty());
3045                         assert!(update_fulfill_htlcs.is_empty());
3046                         assert!(update_fail_malformed_htlcs.is_empty());
3047                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3048                 },
3049                 _ => panic!("Unexpected event"),
3050         };
3051
3052         // Broadcast legit commitment tx from B on A's chain
3053         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3054         check_spends!(commitment_tx[0], chan_1.3);
3055
3056         mine_transaction(&nodes[0], &commitment_tx[0]);
3057
3058         check_closed_broadcast!(nodes[0], true);
3059         check_added_monitors!(nodes[0], 1);
3060         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3061         assert_eq!(node_txn.len(), 3);
3062         check_spends!(node_txn[0], commitment_tx[0]);
3063         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3064         check_spends!(node_txn[1], chan_1.3);
3065         check_spends!(node_txn[2], node_txn[1]);
3066         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3067         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3068 }
3069
3070 #[test]
3071 fn test_simple_commitment_revoked_fail_backward() {
3072         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3073         // and fail backward accordingly.
3074
3075         let chanmon_cfgs = create_chanmon_cfgs(3);
3076         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3077         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3078         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3079
3080         // Create some initial channels
3081         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3082         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3083
3084         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3085         // Get the will-be-revoked local txn from nodes[2]
3086         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3087         // Revoke the old state
3088         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3089
3090         let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3091
3092         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3093         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3094         check_added_monitors!(nodes[1], 1);
3095         check_closed_broadcast!(nodes[1], true);
3096
3097         expect_pending_htlcs_forwardable!(nodes[1]);
3098         check_added_monitors!(nodes[1], 1);
3099         let events = nodes[1].node.get_and_clear_pending_msg_events();
3100         assert_eq!(events.len(), 1);
3101         match events[0] {
3102                 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, .. } } => {
3103                         assert!(update_add_htlcs.is_empty());
3104                         assert_eq!(update_fail_htlcs.len(), 1);
3105                         assert!(update_fulfill_htlcs.is_empty());
3106                         assert!(update_fail_malformed_htlcs.is_empty());
3107                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3108
3109                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3110                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3111
3112                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3113                         assert_eq!(events.len(), 1);
3114                         match events[0] {
3115                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3116                                 _ => panic!("Unexpected event"),
3117                         }
3118                         expect_payment_failed!(nodes[0], payment_hash, false);
3119                 },
3120                 _ => panic!("Unexpected event"),
3121         }
3122 }
3123
3124 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3125         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3126         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3127         // commitment transaction anymore.
3128         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3129         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3130         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3131         // technically disallowed and we should probably handle it reasonably.
3132         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3133         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3134         // transactions:
3135         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3136         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3137         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3138         //   and once they revoke the previous commitment transaction (allowing us to send a new
3139         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3140         let chanmon_cfgs = create_chanmon_cfgs(3);
3141         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3142         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3143         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3144
3145         // Create some initial channels
3146         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3147         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3148
3149         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3150         // Get the will-be-revoked local txn from nodes[2]
3151         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3152         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3153         // Revoke the old state
3154         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3155
3156         let value = if use_dust {
3157                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3158                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3159                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3160         } else { 3000000 };
3161
3162         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3163         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3164         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3165
3166         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3167         expect_pending_htlcs_forwardable!(nodes[2]);
3168         check_added_monitors!(nodes[2], 1);
3169         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3170         assert!(updates.update_add_htlcs.is_empty());
3171         assert!(updates.update_fulfill_htlcs.is_empty());
3172         assert!(updates.update_fail_malformed_htlcs.is_empty());
3173         assert_eq!(updates.update_fail_htlcs.len(), 1);
3174         assert!(updates.update_fee.is_none());
3175         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3176         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3177         // Drop the last RAA from 3 -> 2
3178
3179         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3180         expect_pending_htlcs_forwardable!(nodes[2]);
3181         check_added_monitors!(nodes[2], 1);
3182         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3183         assert!(updates.update_add_htlcs.is_empty());
3184         assert!(updates.update_fulfill_htlcs.is_empty());
3185         assert!(updates.update_fail_malformed_htlcs.is_empty());
3186         assert_eq!(updates.update_fail_htlcs.len(), 1);
3187         assert!(updates.update_fee.is_none());
3188         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3189         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3190         check_added_monitors!(nodes[1], 1);
3191         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3192         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3193         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3194         check_added_monitors!(nodes[2], 1);
3195
3196         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3197         expect_pending_htlcs_forwardable!(nodes[2]);
3198         check_added_monitors!(nodes[2], 1);
3199         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3200         assert!(updates.update_add_htlcs.is_empty());
3201         assert!(updates.update_fulfill_htlcs.is_empty());
3202         assert!(updates.update_fail_malformed_htlcs.is_empty());
3203         assert_eq!(updates.update_fail_htlcs.len(), 1);
3204         assert!(updates.update_fee.is_none());
3205         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3206         // At this point first_payment_hash has dropped out of the latest two commitment
3207         // transactions that nodes[1] is tracking...
3208         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3209         check_added_monitors!(nodes[1], 1);
3210         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3211         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3212         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3213         check_added_monitors!(nodes[2], 1);
3214
3215         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3216         // on nodes[2]'s RAA.
3217         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3218         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3219         let logger = test_utils::TestLogger::new();
3220         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3221         nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3222         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3223         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3224         check_added_monitors!(nodes[1], 0);
3225
3226         if deliver_bs_raa {
3227                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3228                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3229                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3230                 check_added_monitors!(nodes[1], 1);
3231                 let events = nodes[1].node.get_and_clear_pending_events();
3232                 assert_eq!(events.len(), 1);
3233                 match events[0] {
3234                         Event::PendingHTLCsForwardable { .. } => { },
3235                         _ => panic!("Unexpected event"),
3236                 };
3237                 // Deliberately don't process the pending fail-back so they all fail back at once after
3238                 // block connection just like the !deliver_bs_raa case
3239         }
3240
3241         let mut failed_htlcs = HashSet::new();
3242         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3243
3244         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3245         check_added_monitors!(nodes[1], 1);
3246         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3247
3248         let events = nodes[1].node.get_and_clear_pending_events();
3249         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3250         match events[0] {
3251                 Event::PaymentFailed { ref payment_hash, .. } => {
3252                         assert_eq!(*payment_hash, fourth_payment_hash);
3253                 },
3254                 _ => panic!("Unexpected event"),
3255         }
3256         if !deliver_bs_raa {
3257                 match events[1] {
3258                         Event::PendingHTLCsForwardable { .. } => { },
3259                         _ => panic!("Unexpected event"),
3260                 };
3261         }
3262         nodes[1].node.process_pending_htlc_forwards();
3263         check_added_monitors!(nodes[1], 1);
3264
3265         let events = nodes[1].node.get_and_clear_pending_msg_events();
3266         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3267         match events[if deliver_bs_raa { 1 } else { 0 }] {
3268                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3269                 _ => panic!("Unexpected event"),
3270         }
3271         match events[if deliver_bs_raa { 2 } else { 1 }] {
3272                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3273                         assert_eq!(channel_id, chan_2.2);
3274                         assert_eq!(data.as_str(), "Commitment or closing transaction was confirmed on chain.");
3275                 },
3276                 _ => panic!("Unexpected event"),
3277         }
3278         if deliver_bs_raa {
3279                 match events[0] {
3280                         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, .. } } => {
3281                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3282                                 assert_eq!(update_add_htlcs.len(), 1);
3283                                 assert!(update_fulfill_htlcs.is_empty());
3284                                 assert!(update_fail_htlcs.is_empty());
3285                                 assert!(update_fail_malformed_htlcs.is_empty());
3286                         },
3287                         _ => panic!("Unexpected event"),
3288                 }
3289         }
3290         match events[if deliver_bs_raa { 3 } else { 2 }] {
3291                 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, .. } } => {
3292                         assert!(update_add_htlcs.is_empty());
3293                         assert_eq!(update_fail_htlcs.len(), 3);
3294                         assert!(update_fulfill_htlcs.is_empty());
3295                         assert!(update_fail_malformed_htlcs.is_empty());
3296                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3297
3298                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3299                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3300                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3301
3302                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3303
3304                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3305                         // If we delivered B's RAA we got an unknown preimage error, not something
3306                         // that we should update our routing table for.
3307                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3308                         for event in events {
3309                                 match event {
3310                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3311                                         _ => panic!("Unexpected event"),
3312                                 }
3313                         }
3314                         let events = nodes[0].node.get_and_clear_pending_events();
3315                         assert_eq!(events.len(), 3);
3316                         match events[0] {
3317                                 Event::PaymentFailed { ref payment_hash, .. } => {
3318                                         assert!(failed_htlcs.insert(payment_hash.0));
3319                                 },
3320                                 _ => panic!("Unexpected event"),
3321                         }
3322                         match events[1] {
3323                                 Event::PaymentFailed { ref payment_hash, .. } => {
3324                                         assert!(failed_htlcs.insert(payment_hash.0));
3325                                 },
3326                                 _ => panic!("Unexpected event"),
3327                         }
3328                         match events[2] {
3329                                 Event::PaymentFailed { ref payment_hash, .. } => {
3330                                         assert!(failed_htlcs.insert(payment_hash.0));
3331                                 },
3332                                 _ => panic!("Unexpected event"),
3333                         }
3334                 },
3335                 _ => panic!("Unexpected event"),
3336         }
3337
3338         assert!(failed_htlcs.contains(&first_payment_hash.0));
3339         assert!(failed_htlcs.contains(&second_payment_hash.0));
3340         assert!(failed_htlcs.contains(&third_payment_hash.0));
3341 }
3342
3343 #[test]
3344 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3345         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3346         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3347         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3348         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3349 }
3350
3351 #[test]
3352 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3353         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3354         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3355         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3356         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3357 }
3358
3359 #[test]
3360 fn fail_backward_pending_htlc_upon_channel_failure() {
3361         let chanmon_cfgs = create_chanmon_cfgs(2);
3362         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3363         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3364         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3365         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3366         let logger = test_utils::TestLogger::new();
3367
3368         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3369         {
3370                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3371                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3372                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3373                 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3374                 check_added_monitors!(nodes[0], 1);
3375
3376                 let payment_event = {
3377                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3378                         assert_eq!(events.len(), 1);
3379                         SendEvent::from_event(events.remove(0))
3380                 };
3381                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3382                 assert_eq!(payment_event.msgs.len(), 1);
3383         }
3384
3385         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3386         let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3387         {
3388                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3389                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3390                 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3391                 check_added_monitors!(nodes[0], 0);
3392
3393                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3394         }
3395
3396         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3397         {
3398                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3399
3400                 let secp_ctx = Secp256k1::new();
3401                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3402                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3403                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3404                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3405                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3406                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3407                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3408
3409                 // Send a 0-msat update_add_htlc to fail the channel.
3410                 let update_add_htlc = msgs::UpdateAddHTLC {
3411                         channel_id: chan.2,
3412                         htlc_id: 0,
3413                         amount_msat: 0,
3414                         payment_hash,
3415                         cltv_expiry,
3416                         onion_routing_packet,
3417                 };
3418                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3419         }
3420
3421         // Check that Alice fails backward the pending HTLC from the second payment.
3422         expect_payment_failed!(nodes[0], failed_payment_hash, true);
3423         check_closed_broadcast!(nodes[0], true);
3424         check_added_monitors!(nodes[0], 1);
3425 }
3426
3427 #[test]
3428 fn test_htlc_ignore_latest_remote_commitment() {
3429         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3430         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3431         let chanmon_cfgs = create_chanmon_cfgs(2);
3432         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3433         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3434         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3435         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3436
3437         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3438         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3439         check_closed_broadcast!(nodes[0], true);
3440         check_added_monitors!(nodes[0], 1);
3441
3442         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3443         assert_eq!(node_txn.len(), 2);
3444
3445         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3446         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3447         check_closed_broadcast!(nodes[1], true);
3448         check_added_monitors!(nodes[1], 1);
3449
3450         // Duplicate the connect_block call since this may happen due to other listeners
3451         // registering new transactions
3452         header.prev_blockhash = header.block_hash();
3453         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3454 }
3455
3456 #[test]
3457 fn test_force_close_fail_back() {
3458         // Check which HTLCs are failed-backwards on channel force-closure
3459         let chanmon_cfgs = create_chanmon_cfgs(3);
3460         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3461         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3462         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3463         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3464         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3465         let logger = test_utils::TestLogger::new();
3466
3467         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3468
3469         let mut payment_event = {
3470                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3471                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &Vec::new(), 1000000, 42, &logger).unwrap();
3472                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3473                 check_added_monitors!(nodes[0], 1);
3474
3475                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3476                 assert_eq!(events.len(), 1);
3477                 SendEvent::from_event(events.remove(0))
3478         };
3479
3480         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3481         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3482
3483         expect_pending_htlcs_forwardable!(nodes[1]);
3484
3485         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3486         assert_eq!(events_2.len(), 1);
3487         payment_event = SendEvent::from_event(events_2.remove(0));
3488         assert_eq!(payment_event.msgs.len(), 1);
3489
3490         check_added_monitors!(nodes[1], 1);
3491         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3492         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3493         check_added_monitors!(nodes[2], 1);
3494         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3495
3496         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3497         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3498         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3499
3500         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3501         check_closed_broadcast!(nodes[2], true);
3502         check_added_monitors!(nodes[2], 1);
3503         let tx = {
3504                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3505                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3506                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3507                 // back to nodes[1] upon timeout otherwise.
3508                 assert_eq!(node_txn.len(), 1);
3509                 node_txn.remove(0)
3510         };
3511
3512         mine_transaction(&nodes[1], &tx);
3513
3514         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3515         check_closed_broadcast!(nodes[1], true);
3516         check_added_monitors!(nodes[1], 1);
3517
3518         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3519         {
3520                 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3521                 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3522                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3523         }
3524         mine_transaction(&nodes[2], &tx);
3525         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3526         assert_eq!(node_txn.len(), 1);
3527         assert_eq!(node_txn[0].input.len(), 1);
3528         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3529         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3530         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3531
3532         check_spends!(node_txn[0], tx);
3533 }
3534
3535 #[test]
3536 fn test_simple_peer_disconnect() {
3537         // Test that we can reconnect when there are no lost messages
3538         let chanmon_cfgs = create_chanmon_cfgs(3);
3539         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3540         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3541         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3542         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3543         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3544
3545         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3546         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3547         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3548
3549         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3550         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3551         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3552         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3553
3554         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3555         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3556         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3557
3558         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3559         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3560         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3561         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3562
3563         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3564         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3565
3566         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3567         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3568
3569         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3570         {
3571                 let events = nodes[0].node.get_and_clear_pending_events();
3572                 assert_eq!(events.len(), 2);
3573                 match events[0] {
3574                         Event::PaymentSent { payment_preimage } => {
3575                                 assert_eq!(payment_preimage, payment_preimage_3);
3576                         },
3577                         _ => panic!("Unexpected event"),
3578                 }
3579                 match events[1] {
3580                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3581                                 assert_eq!(payment_hash, payment_hash_5);
3582                                 assert!(rejected_by_dest);
3583                         },
3584                         _ => panic!("Unexpected event"),
3585                 }
3586         }
3587
3588         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3589         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3590 }
3591
3592 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3593         // Test that we can reconnect when in-flight HTLC updates get dropped
3594         let chanmon_cfgs = create_chanmon_cfgs(2);
3595         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3596         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3597         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3598         if messages_delivered == 0 {
3599                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3600                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3601         } else {
3602                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3603         }
3604
3605         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3606
3607         let logger = test_utils::TestLogger::new();
3608         let payment_event = {
3609                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3610                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3611                         &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3612                         &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3613                 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3614                 check_added_monitors!(nodes[0], 1);
3615
3616                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3617                 assert_eq!(events.len(), 1);
3618                 SendEvent::from_event(events.remove(0))
3619         };
3620         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3621
3622         if messages_delivered < 2 {
3623                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3624         } else {
3625                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3626                 if messages_delivered >= 3 {
3627                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3628                         check_added_monitors!(nodes[1], 1);
3629                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3630
3631                         if messages_delivered >= 4 {
3632                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3633                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3634                                 check_added_monitors!(nodes[0], 1);
3635
3636                                 if messages_delivered >= 5 {
3637                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3638                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3639                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3640                                         check_added_monitors!(nodes[0], 1);
3641
3642                                         if messages_delivered >= 6 {
3643                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3644                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3645                                                 check_added_monitors!(nodes[1], 1);
3646                                         }
3647                                 }
3648                         }
3649                 }
3650         }
3651
3652         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3653         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3654         if messages_delivered < 3 {
3655                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3656                 // received on either side, both sides will need to resend them.
3657                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3658         } else if messages_delivered == 3 {
3659                 // nodes[0] still wants its RAA + commitment_signed
3660                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3661         } else if messages_delivered == 4 {
3662                 // nodes[0] still wants its commitment_signed
3663                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3664         } else if messages_delivered == 5 {
3665                 // nodes[1] still wants its final RAA
3666                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3667         } else if messages_delivered == 6 {
3668                 // Everything was delivered...
3669                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3670         }
3671
3672         let events_1 = nodes[1].node.get_and_clear_pending_events();
3673         assert_eq!(events_1.len(), 1);
3674         match events_1[0] {
3675                 Event::PendingHTLCsForwardable { .. } => { },
3676                 _ => panic!("Unexpected event"),
3677         };
3678
3679         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3680         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3681         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3682
3683         nodes[1].node.process_pending_htlc_forwards();
3684
3685         let events_2 = nodes[1].node.get_and_clear_pending_events();
3686         assert_eq!(events_2.len(), 1);
3687         match events_2[0] {
3688                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3689                         assert_eq!(payment_hash_1, *payment_hash);
3690                         assert_eq!(*payment_secret, None);
3691                         assert_eq!(amt, 1000000);
3692                 },
3693                 _ => panic!("Unexpected event"),
3694         }
3695
3696         nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3697         check_added_monitors!(nodes[1], 1);
3698
3699         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3700         assert_eq!(events_3.len(), 1);
3701         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3702                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3703                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3704                         assert!(updates.update_add_htlcs.is_empty());
3705                         assert!(updates.update_fail_htlcs.is_empty());
3706                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3707                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3708                         assert!(updates.update_fee.is_none());
3709                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3710                 },
3711                 _ => panic!("Unexpected event"),
3712         };
3713
3714         if messages_delivered >= 1 {
3715                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3716
3717                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3718                 assert_eq!(events_4.len(), 1);
3719                 match events_4[0] {
3720                         Event::PaymentSent { ref payment_preimage } => {
3721                                 assert_eq!(payment_preimage_1, *payment_preimage);
3722                         },
3723                         _ => panic!("Unexpected event"),
3724                 }
3725
3726                 if messages_delivered >= 2 {
3727                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3728                         check_added_monitors!(nodes[0], 1);
3729                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3730
3731                         if messages_delivered >= 3 {
3732                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3733                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3734                                 check_added_monitors!(nodes[1], 1);
3735
3736                                 if messages_delivered >= 4 {
3737                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3738                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3739                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3740                                         check_added_monitors!(nodes[1], 1);
3741
3742                                         if messages_delivered >= 5 {
3743                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3744                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3745                                                 check_added_monitors!(nodes[0], 1);
3746                                         }
3747                                 }
3748                         }
3749                 }
3750         }
3751
3752         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3753         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3754         if messages_delivered < 2 {
3755                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3756                 //TODO: Deduplicate PaymentSent events, then enable this if:
3757                 //if messages_delivered < 1 {
3758                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3759                         assert_eq!(events_4.len(), 1);
3760                         match events_4[0] {
3761                                 Event::PaymentSent { ref payment_preimage } => {
3762                                         assert_eq!(payment_preimage_1, *payment_preimage);
3763                                 },
3764                                 _ => panic!("Unexpected event"),
3765                         }
3766                 //}
3767         } else if messages_delivered == 2 {
3768                 // nodes[0] still wants its RAA + commitment_signed
3769                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3770         } else if messages_delivered == 3 {
3771                 // nodes[0] still wants its commitment_signed
3772                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3773         } else if messages_delivered == 4 {
3774                 // nodes[1] still wants its final RAA
3775                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3776         } else if messages_delivered == 5 {
3777                 // Everything was delivered...
3778                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3779         }
3780
3781         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3782         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3783         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3784
3785         // Channel should still work fine...
3786         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3787         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3788                 &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3789                 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3790         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3791         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3792 }
3793
3794 #[test]
3795 fn test_drop_messages_peer_disconnect_a() {
3796         do_test_drop_messages_peer_disconnect(0);
3797         do_test_drop_messages_peer_disconnect(1);
3798         do_test_drop_messages_peer_disconnect(2);
3799         do_test_drop_messages_peer_disconnect(3);
3800 }
3801
3802 #[test]
3803 fn test_drop_messages_peer_disconnect_b() {
3804         do_test_drop_messages_peer_disconnect(4);
3805         do_test_drop_messages_peer_disconnect(5);
3806         do_test_drop_messages_peer_disconnect(6);
3807 }
3808
3809 #[test]
3810 fn test_funding_peer_disconnect() {
3811         // Test that we can lock in our funding tx while disconnected
3812         let chanmon_cfgs = create_chanmon_cfgs(2);
3813         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3814         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3815         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3816         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3817
3818         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3819         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3820
3821         confirm_transaction(&nodes[0], &tx);
3822         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3823         assert_eq!(events_1.len(), 1);
3824         match events_1[0] {
3825                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3826                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3827                 },
3828                 _ => panic!("Unexpected event"),
3829         }
3830
3831         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3832
3833         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3834         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3835
3836         confirm_transaction(&nodes[1], &tx);
3837         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3838         assert_eq!(events_2.len(), 2);
3839         let funding_locked = match events_2[0] {
3840                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3841                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3842                         msg.clone()
3843                 },
3844                 _ => panic!("Unexpected event"),
3845         };
3846         let bs_announcement_sigs = match events_2[1] {
3847                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3848                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3849                         msg.clone()
3850                 },
3851                 _ => panic!("Unexpected event"),
3852         };
3853
3854         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3855
3856         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3857         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3858         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3859         assert_eq!(events_3.len(), 2);
3860         let as_announcement_sigs = match events_3[0] {
3861                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3862                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3863                         msg.clone()
3864                 },
3865                 _ => panic!("Unexpected event"),
3866         };
3867         let (as_announcement, as_update) = match events_3[1] {
3868                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3869                         (msg.clone(), update_msg.clone())
3870                 },
3871                 _ => panic!("Unexpected event"),
3872         };
3873
3874         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3875         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3876         assert_eq!(events_4.len(), 1);
3877         let (_, bs_update) = match events_4[0] {
3878                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3879                         (msg.clone(), update_msg.clone())
3880                 },
3881                 _ => panic!("Unexpected event"),
3882         };
3883
3884         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3885         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3886         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3887
3888         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3889         let logger = test_utils::TestLogger::new();
3890         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3891         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3892         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3893 }
3894
3895 #[test]
3896 fn test_drop_messages_peer_disconnect_dual_htlc() {
3897         // Test that we can handle reconnecting when both sides of a channel have pending
3898         // commitment_updates when we disconnect.
3899         let chanmon_cfgs = create_chanmon_cfgs(2);
3900         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3901         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3902         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3903         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3904         let logger = test_utils::TestLogger::new();
3905
3906         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3907
3908         // Now try to send a second payment which will fail to send
3909         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3910         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3911         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3912         nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3913         check_added_monitors!(nodes[0], 1);
3914
3915         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3916         assert_eq!(events_1.len(), 1);
3917         match events_1[0] {
3918                 MessageSendEvent::UpdateHTLCs { .. } => {},
3919                 _ => panic!("Unexpected event"),
3920         }
3921
3922         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3923         check_added_monitors!(nodes[1], 1);
3924
3925         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3926         assert_eq!(events_2.len(), 1);
3927         match events_2[0] {
3928                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
3929                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3930                         assert!(update_add_htlcs.is_empty());
3931                         assert_eq!(update_fulfill_htlcs.len(), 1);
3932                         assert!(update_fail_htlcs.is_empty());
3933                         assert!(update_fail_malformed_htlcs.is_empty());
3934                         assert!(update_fee.is_none());
3935
3936                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3937                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3938                         assert_eq!(events_3.len(), 1);
3939                         match events_3[0] {
3940                                 Event::PaymentSent { ref payment_preimage } => {
3941                                         assert_eq!(*payment_preimage, payment_preimage_1);
3942                                 },
3943                                 _ => panic!("Unexpected event"),
3944                         }
3945
3946                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3947                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3948                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3949                         check_added_monitors!(nodes[0], 1);
3950                 },
3951                 _ => panic!("Unexpected event"),
3952         }
3953
3954         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3955         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3956
3957         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3958         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3959         assert_eq!(reestablish_1.len(), 1);
3960         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3961         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3962         assert_eq!(reestablish_2.len(), 1);
3963
3964         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3965         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3966         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3967         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3968
3969         assert!(as_resp.0.is_none());
3970         assert!(bs_resp.0.is_none());
3971
3972         assert!(bs_resp.1.is_none());
3973         assert!(bs_resp.2.is_none());
3974
3975         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3976
3977         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3978         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3979         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3980         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3981         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3982         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3983         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3984         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3985         // No commitment_signed so get_event_msg's assert(len == 1) passes
3986         check_added_monitors!(nodes[1], 1);
3987
3988         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3989         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3990         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3991         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3992         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3993         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3994         assert!(bs_second_commitment_signed.update_fee.is_none());
3995         check_added_monitors!(nodes[1], 1);
3996
3997         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3998         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3999         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4000         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4001         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4002         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4003         assert!(as_commitment_signed.update_fee.is_none());
4004         check_added_monitors!(nodes[0], 1);
4005
4006         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4007         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4008         // No commitment_signed so get_event_msg's assert(len == 1) passes
4009         check_added_monitors!(nodes[0], 1);
4010
4011         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4012         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4013         // No commitment_signed so get_event_msg's assert(len == 1) passes
4014         check_added_monitors!(nodes[1], 1);
4015
4016         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4017         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4018         check_added_monitors!(nodes[1], 1);
4019
4020         expect_pending_htlcs_forwardable!(nodes[1]);
4021
4022         let events_5 = nodes[1].node.get_and_clear_pending_events();
4023         assert_eq!(events_5.len(), 1);
4024         match events_5[0] {
4025                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4026                         assert_eq!(payment_hash_2, *payment_hash);
4027                         assert_eq!(*payment_secret, None);
4028                 },
4029                 _ => panic!("Unexpected event"),
4030         }
4031
4032         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4033         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4034         check_added_monitors!(nodes[0], 1);
4035
4036         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4037 }
4038
4039 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4040         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4041         // to avoid our counterparty failing the channel.
4042         let chanmon_cfgs = create_chanmon_cfgs(2);
4043         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4044         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4045         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4046
4047         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4048         let logger = test_utils::TestLogger::new();
4049
4050         let our_payment_hash = if send_partial_mpp {
4051                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4052                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4053                 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4054                 let payment_secret = PaymentSecret([0xdb; 32]);
4055                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4056                 // indicates there are more HTLCs coming.
4057                 let cur_height = CHAN_CONFIRM_DEPTH + 1; // route_payment calls send_payment, which adds 1 to the current height. So we do the same here to match.
4058                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height).unwrap();
4059                 check_added_monitors!(nodes[0], 1);
4060                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4061                 assert_eq!(events.len(), 1);
4062                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4063                 // hop should *not* yet generate any PaymentReceived event(s).
4064                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4065                 our_payment_hash
4066         } else {
4067                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4068         };
4069
4070         let mut block = Block {
4071                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4072                 txdata: vec![],
4073         };
4074         connect_block(&nodes[0], &block);
4075         connect_block(&nodes[1], &block);
4076         for _ in CHAN_CONFIRM_DEPTH + 2 ..TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4077                 block.header.prev_blockhash = block.block_hash();
4078                 connect_block(&nodes[0], &block);
4079                 connect_block(&nodes[1], &block);
4080         }
4081
4082         expect_pending_htlcs_forwardable!(nodes[1]);
4083
4084         check_added_monitors!(nodes[1], 1);
4085         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4086         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4087         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4088         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4089         assert!(htlc_timeout_updates.update_fee.is_none());
4090
4091         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4092         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4093         // 100_000 msat as u64, followed by a height of TEST_FINAL_CLTV + 2 as u32
4094         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4095         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(TEST_FINAL_CLTV + 2));
4096         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4097 }
4098
4099 #[test]
4100 fn test_htlc_timeout() {
4101         do_test_htlc_timeout(true);
4102         do_test_htlc_timeout(false);
4103 }
4104
4105 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4106         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4107         let chanmon_cfgs = create_chanmon_cfgs(3);
4108         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4109         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4110         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4111         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4112         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4113
4114         // Make sure all nodes are at the same starting height
4115         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4116         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4117         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4118
4119         let logger = test_utils::TestLogger::new();
4120
4121         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4122         let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4123         {
4124                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4125                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4126                 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4127         }
4128         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4129         check_added_monitors!(nodes[1], 1);
4130
4131         // Now attempt to route a second payment, which should be placed in the holding cell
4132         let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4133         if forwarded_htlc {
4134                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4135                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4136                 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4137                 check_added_monitors!(nodes[0], 1);
4138                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4139                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4140                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4141                 expect_pending_htlcs_forwardable!(nodes[1]);
4142                 check_added_monitors!(nodes[1], 0);
4143         } else {
4144                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4145                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4146                 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4147                 check_added_monitors!(nodes[1], 0);
4148         }
4149
4150         connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4151         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4152         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4153         connect_blocks(&nodes[1], 1);
4154
4155         if forwarded_htlc {
4156                 expect_pending_htlcs_forwardable!(nodes[1]);
4157                 check_added_monitors!(nodes[1], 1);
4158                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4159                 assert_eq!(fail_commit.len(), 1);
4160                 match fail_commit[0] {
4161                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4162                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4163                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4164                         },
4165                         _ => unreachable!(),
4166                 }
4167                 expect_payment_failed!(nodes[0], second_payment_hash, false);
4168                 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4169                         match update {
4170                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4171                                 _ => panic!("Unexpected event"),
4172                         }
4173                 } else {
4174                         panic!("Unexpected event");
4175                 }
4176         } else {
4177                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4178         }
4179 }
4180
4181 #[test]
4182 fn test_holding_cell_htlc_add_timeouts() {
4183         do_test_holding_cell_htlc_add_timeouts(false);
4184         do_test_holding_cell_htlc_add_timeouts(true);
4185 }
4186
4187 #[test]
4188 fn test_invalid_channel_announcement() {
4189         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4190         let secp_ctx = Secp256k1::new();
4191         let chanmon_cfgs = create_chanmon_cfgs(2);
4192         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4193         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4194         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4195
4196         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4197
4198         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4199         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4200         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4201         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4202
4203         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 } );
4204
4205         let as_bitcoin_key = as_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4206         let bs_bitcoin_key = bs_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4207
4208         let as_network_key = nodes[0].node.get_our_node_id();
4209         let bs_network_key = nodes[1].node.get_our_node_id();
4210
4211         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4212
4213         let mut chan_announcement;
4214
4215         macro_rules! dummy_unsigned_msg {
4216                 () => {
4217                         msgs::UnsignedChannelAnnouncement {
4218                                 features: ChannelFeatures::known(),
4219                                 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4220                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4221                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4222                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4223                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4224                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4225                                 excess_data: Vec::new(),
4226                         };
4227                 }
4228         }
4229
4230         macro_rules! sign_msg {
4231                 ($unsigned_msg: expr) => {
4232                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4233                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_signer().inner.funding_key);
4234                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_signer().inner.funding_key);
4235                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4236                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4237                         chan_announcement = msgs::ChannelAnnouncement {
4238                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4239                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4240                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4241                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4242                                 contents: $unsigned_msg
4243                         }
4244                 }
4245         }
4246
4247         let unsigned_msg = dummy_unsigned_msg!();
4248         sign_msg!(unsigned_msg);
4249         assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4250         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 } );
4251
4252         // Configured with Network::Testnet
4253         let mut unsigned_msg = dummy_unsigned_msg!();
4254         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4255         sign_msg!(unsigned_msg);
4256         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4257
4258         let mut unsigned_msg = dummy_unsigned_msg!();
4259         unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4260         sign_msg!(unsigned_msg);
4261         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4262 }
4263
4264 #[test]
4265 fn test_no_txn_manager_serialize_deserialize() {
4266         let chanmon_cfgs = create_chanmon_cfgs(2);
4267         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4268         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4269         let logger: test_utils::TestLogger;
4270         let fee_estimator: test_utils::TestFeeEstimator;
4271         let persister: test_utils::TestPersister;
4272         let new_chain_monitor: test_utils::TestChainMonitor;
4273         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4274         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4275
4276         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4277
4278         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4279
4280         let nodes_0_serialized = nodes[0].node.encode();
4281         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4282         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4283
4284         logger = test_utils::TestLogger::new();
4285         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4286         persister = test_utils::TestPersister::new();
4287         let keys_manager = &chanmon_cfgs[0].keys_manager;
4288         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4289         nodes[0].chain_monitor = &new_chain_monitor;
4290         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4291         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4292                 &mut chan_0_monitor_read, keys_manager).unwrap();
4293         assert!(chan_0_monitor_read.is_empty());
4294
4295         let mut nodes_0_read = &nodes_0_serialized[..];
4296         let config = UserConfig::default();
4297         let (_, nodes_0_deserialized_tmp) = {
4298                 let mut channel_monitors = HashMap::new();
4299                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4300                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4301                         default_config: config,
4302                         keys_manager,
4303                         fee_estimator: &fee_estimator,
4304                         chain_monitor: nodes[0].chain_monitor,
4305                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4306                         logger: &logger,
4307                         channel_monitors,
4308                 }).unwrap()
4309         };
4310         nodes_0_deserialized = nodes_0_deserialized_tmp;
4311         assert!(nodes_0_read.is_empty());
4312
4313         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4314         nodes[0].node = &nodes_0_deserialized;
4315         assert_eq!(nodes[0].node.list_channels().len(), 1);
4316         check_added_monitors!(nodes[0], 1);
4317
4318         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4319         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4320         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4321         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4322
4323         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4324         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4325         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4326         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4327
4328         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4329         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4330         for node in nodes.iter() {
4331                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4332                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4333                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4334         }
4335
4336         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4337 }
4338
4339 #[test]
4340 fn test_manager_serialize_deserialize_events() {
4341         // This test makes sure the events field in ChannelManager survives de/serialization
4342         let chanmon_cfgs = create_chanmon_cfgs(2);
4343         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4344         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4345         let fee_estimator: test_utils::TestFeeEstimator;
4346         let persister: test_utils::TestPersister;
4347         let logger: test_utils::TestLogger;
4348         let new_chain_monitor: test_utils::TestChainMonitor;
4349         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4350         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4351
4352         // Start creating a channel, but stop right before broadcasting the funding transaction
4353         let channel_value = 100000;
4354         let push_msat = 10001;
4355         let a_flags = InitFeatures::known();
4356         let b_flags = InitFeatures::known();
4357         let node_a = nodes.remove(0);
4358         let node_b = nodes.remove(0);
4359         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4360         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()));
4361         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()));
4362
4363         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4364
4365         node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4366         check_added_monitors!(node_a, 0);
4367
4368         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()));
4369         {
4370                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4371                 assert_eq!(added_monitors.len(), 1);
4372                 assert_eq!(added_monitors[0].0, funding_output);
4373                 added_monitors.clear();
4374         }
4375
4376         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()));
4377         {
4378                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4379                 assert_eq!(added_monitors.len(), 1);
4380                 assert_eq!(added_monitors[0].0, funding_output);
4381                 added_monitors.clear();
4382         }
4383         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4384
4385         nodes.push(node_a);
4386         nodes.push(node_b);
4387
4388         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4389         let nodes_0_serialized = nodes[0].node.encode();
4390         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4391         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4392
4393         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4394         logger = test_utils::TestLogger::new();
4395         persister = test_utils::TestPersister::new();
4396         let keys_manager = &chanmon_cfgs[0].keys_manager;
4397         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4398         nodes[0].chain_monitor = &new_chain_monitor;
4399         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4400         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4401                 &mut chan_0_monitor_read, keys_manager).unwrap();
4402         assert!(chan_0_monitor_read.is_empty());
4403
4404         let mut nodes_0_read = &nodes_0_serialized[..];
4405         let config = UserConfig::default();
4406         let (_, nodes_0_deserialized_tmp) = {
4407                 let mut channel_monitors = HashMap::new();
4408                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4409                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4410                         default_config: config,
4411                         keys_manager,
4412                         fee_estimator: &fee_estimator,
4413                         chain_monitor: nodes[0].chain_monitor,
4414                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4415                         logger: &logger,
4416                         channel_monitors,
4417                 }).unwrap()
4418         };
4419         nodes_0_deserialized = nodes_0_deserialized_tmp;
4420         assert!(nodes_0_read.is_empty());
4421
4422         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4423
4424         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4425         nodes[0].node = &nodes_0_deserialized;
4426
4427         // After deserializing, make sure the funding_transaction is still held by the channel manager
4428         let events_4 = nodes[0].node.get_and_clear_pending_events();
4429         assert_eq!(events_4.len(), 0);
4430         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4431         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4432
4433         // Make sure the channel is functioning as though the de/serialization never happened
4434         assert_eq!(nodes[0].node.list_channels().len(), 1);
4435         check_added_monitors!(nodes[0], 1);
4436
4437         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4438         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4439         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4440         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4441
4442         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4443         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4444         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4445         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4446
4447         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4448         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4449         for node in nodes.iter() {
4450                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4451                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4452                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4453         }
4454
4455         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4456 }
4457
4458 #[test]
4459 fn test_simple_manager_serialize_deserialize() {
4460         let chanmon_cfgs = create_chanmon_cfgs(2);
4461         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4462         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4463         let logger: test_utils::TestLogger;
4464         let fee_estimator: test_utils::TestFeeEstimator;
4465         let persister: test_utils::TestPersister;
4466         let new_chain_monitor: test_utils::TestChainMonitor;
4467         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4468         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4469         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4470
4471         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4472         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4473
4474         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4475
4476         let nodes_0_serialized = nodes[0].node.encode();
4477         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4478         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4479
4480         logger = test_utils::TestLogger::new();
4481         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4482         persister = test_utils::TestPersister::new();
4483         let keys_manager = &chanmon_cfgs[0].keys_manager;
4484         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4485         nodes[0].chain_monitor = &new_chain_monitor;
4486         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4487         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4488                 &mut chan_0_monitor_read, keys_manager).unwrap();
4489         assert!(chan_0_monitor_read.is_empty());
4490
4491         let mut nodes_0_read = &nodes_0_serialized[..];
4492         let (_, nodes_0_deserialized_tmp) = {
4493                 let mut channel_monitors = HashMap::new();
4494                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4495                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4496                         default_config: UserConfig::default(),
4497                         keys_manager,
4498                         fee_estimator: &fee_estimator,
4499                         chain_monitor: nodes[0].chain_monitor,
4500                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4501                         logger: &logger,
4502                         channel_monitors,
4503                 }).unwrap()
4504         };
4505         nodes_0_deserialized = nodes_0_deserialized_tmp;
4506         assert!(nodes_0_read.is_empty());
4507
4508         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4509         nodes[0].node = &nodes_0_deserialized;
4510         check_added_monitors!(nodes[0], 1);
4511
4512         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4513
4514         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4515         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4516 }
4517
4518 #[test]
4519 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4520         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4521         let chanmon_cfgs = create_chanmon_cfgs(4);
4522         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4523         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4524         let logger: test_utils::TestLogger;
4525         let fee_estimator: test_utils::TestFeeEstimator;
4526         let persister: test_utils::TestPersister;
4527         let new_chain_monitor: test_utils::TestChainMonitor;
4528         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4529         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4530         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4531         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4532         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4533
4534         let mut node_0_stale_monitors_serialized = Vec::new();
4535         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4536                 let mut writer = test_utils::TestVecWriter(Vec::new());
4537                 monitor.1.write(&mut writer).unwrap();
4538                 node_0_stale_monitors_serialized.push(writer.0);
4539         }
4540
4541         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4542
4543         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4544         let nodes_0_serialized = nodes[0].node.encode();
4545
4546         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4547         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4548         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4549         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4550
4551         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4552         // nodes[3])
4553         let mut node_0_monitors_serialized = Vec::new();
4554         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4555                 let mut writer = test_utils::TestVecWriter(Vec::new());
4556                 monitor.1.write(&mut writer).unwrap();
4557                 node_0_monitors_serialized.push(writer.0);
4558         }
4559
4560         logger = test_utils::TestLogger::new();
4561         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4562         persister = test_utils::TestPersister::new();
4563         let keys_manager = &chanmon_cfgs[0].keys_manager;
4564         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4565         nodes[0].chain_monitor = &new_chain_monitor;
4566
4567
4568         let mut node_0_stale_monitors = Vec::new();
4569         for serialized in node_0_stale_monitors_serialized.iter() {
4570                 let mut read = &serialized[..];
4571                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4572                 assert!(read.is_empty());
4573                 node_0_stale_monitors.push(monitor);
4574         }
4575
4576         let mut node_0_monitors = Vec::new();
4577         for serialized in node_0_monitors_serialized.iter() {
4578                 let mut read = &serialized[..];
4579                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4580                 assert!(read.is_empty());
4581                 node_0_monitors.push(monitor);
4582         }
4583
4584         let mut nodes_0_read = &nodes_0_serialized[..];
4585         if let Err(msgs::DecodeError::InvalidValue) =
4586                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4587                 default_config: UserConfig::default(),
4588                 keys_manager,
4589                 fee_estimator: &fee_estimator,
4590                 chain_monitor: nodes[0].chain_monitor,
4591                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4592                 logger: &logger,
4593                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4594         }) { } else {
4595                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4596         };
4597
4598         let mut nodes_0_read = &nodes_0_serialized[..];
4599         let (_, nodes_0_deserialized_tmp) =
4600                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4601                 default_config: UserConfig::default(),
4602                 keys_manager,
4603                 fee_estimator: &fee_estimator,
4604                 chain_monitor: nodes[0].chain_monitor,
4605                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4606                 logger: &logger,
4607                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4608         }).unwrap();
4609         nodes_0_deserialized = nodes_0_deserialized_tmp;
4610         assert!(nodes_0_read.is_empty());
4611
4612         { // Channel close should result in a commitment tx and an HTLC tx
4613                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4614                 assert_eq!(txn.len(), 2);
4615                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4616                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4617         }
4618
4619         for monitor in node_0_monitors.drain(..) {
4620                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4621                 check_added_monitors!(nodes[0], 1);
4622         }
4623         nodes[0].node = &nodes_0_deserialized;
4624
4625         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4626         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4627         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4628         //... and we can even still claim the payment!
4629         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4630
4631         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4632         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4633         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4634         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4635         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4636         assert_eq!(msg_events.len(), 1);
4637         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4638                 match action {
4639                         &ErrorAction::SendErrorMessage { ref msg } => {
4640                                 assert_eq!(msg.channel_id, channel_id);
4641                         },
4642                         _ => panic!("Unexpected event!"),
4643                 }
4644         }
4645 }
4646
4647 macro_rules! check_spendable_outputs {
4648         ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4649                 {
4650                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4651                         let mut txn = Vec::new();
4652                         let mut all_outputs = Vec::new();
4653                         let secp_ctx = Secp256k1::new();
4654                         for event in events.drain(..) {
4655                                 match event {
4656                                         Event::SpendableOutputs { mut outputs } => {
4657                                                 for outp in outputs.drain(..) {
4658                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4659                                                         all_outputs.push(outp);
4660                                                 }
4661                                         },
4662                                         _ => panic!("Unexpected event"),
4663                                 };
4664                         }
4665                         if all_outputs.len() > 1 {
4666                                 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) {
4667                                         txn.push(tx);
4668                                 }
4669                         }
4670                         txn
4671                 }
4672         }
4673 }
4674
4675 #[test]
4676 fn test_claim_sizeable_push_msat() {
4677         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4678         let chanmon_cfgs = create_chanmon_cfgs(2);
4679         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4680         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4681         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4682
4683         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4684         nodes[1].node.force_close_channel(&chan.2).unwrap();
4685         check_closed_broadcast!(nodes[1], true);
4686         check_added_monitors!(nodes[1], 1);
4687         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4688         assert_eq!(node_txn.len(), 1);
4689         check_spends!(node_txn[0], chan.3);
4690         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
4691
4692         mine_transaction(&nodes[1], &node_txn[0]);
4693         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4694
4695         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4696         assert_eq!(spend_txn.len(), 1);
4697         check_spends!(spend_txn[0], node_txn[0]);
4698 }
4699
4700 #[test]
4701 fn test_claim_on_remote_sizeable_push_msat() {
4702         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4703         // to_remote output is encumbered by a P2WPKH
4704         let chanmon_cfgs = create_chanmon_cfgs(2);
4705         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4706         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4707         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4708
4709         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4710         nodes[0].node.force_close_channel(&chan.2).unwrap();
4711         check_closed_broadcast!(nodes[0], true);
4712         check_added_monitors!(nodes[0], 1);
4713
4714         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4715         assert_eq!(node_txn.len(), 1);
4716         check_spends!(node_txn[0], chan.3);
4717         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
4718
4719         mine_transaction(&nodes[1], &node_txn[0]);
4720         check_closed_broadcast!(nodes[1], true);
4721         check_added_monitors!(nodes[1], 1);
4722         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4723
4724         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4725         assert_eq!(spend_txn.len(), 1);
4726         check_spends!(spend_txn[0], node_txn[0]);
4727 }
4728
4729 #[test]
4730 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4731         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4732         // to_remote output is encumbered by a P2WPKH
4733
4734         let chanmon_cfgs = create_chanmon_cfgs(2);
4735         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4736         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4737         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4738
4739         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4740         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4741         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4742         assert_eq!(revoked_local_txn[0].input.len(), 1);
4743         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4744
4745         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4746         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4747         check_closed_broadcast!(nodes[1], true);
4748         check_added_monitors!(nodes[1], 1);
4749
4750         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4751         mine_transaction(&nodes[1], &node_txn[0]);
4752         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4753
4754         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4755         assert_eq!(spend_txn.len(), 3);
4756         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4757         check_spends!(spend_txn[1], node_txn[0]);
4758         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4759 }
4760
4761 #[test]
4762 fn test_static_spendable_outputs_preimage_tx() {
4763         let chanmon_cfgs = create_chanmon_cfgs(2);
4764         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4765         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4766         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4767
4768         // Create some initial channels
4769         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4770
4771         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4772
4773         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4774         assert_eq!(commitment_tx[0].input.len(), 1);
4775         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4776
4777         // Settle A's commitment tx on B's chain
4778         assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4779         check_added_monitors!(nodes[1], 1);
4780         mine_transaction(&nodes[1], &commitment_tx[0]);
4781         check_added_monitors!(nodes[1], 1);
4782         let events = nodes[1].node.get_and_clear_pending_msg_events();
4783         match events[0] {
4784                 MessageSendEvent::UpdateHTLCs { .. } => {},
4785                 _ => panic!("Unexpected event"),
4786         }
4787         match events[1] {
4788                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4789                 _ => panic!("Unexepected event"),
4790         }
4791
4792         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4793         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4794         assert_eq!(node_txn.len(), 3);
4795         check_spends!(node_txn[0], commitment_tx[0]);
4796         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4797         check_spends!(node_txn[1], chan_1.3);
4798         check_spends!(node_txn[2], node_txn[1]);
4799
4800         mine_transaction(&nodes[1], &node_txn[0]);
4801         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4802
4803         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4804         assert_eq!(spend_txn.len(), 1);
4805         check_spends!(spend_txn[0], node_txn[0]);
4806 }
4807
4808 #[test]
4809 fn test_static_spendable_outputs_timeout_tx() {
4810         let chanmon_cfgs = create_chanmon_cfgs(2);
4811         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4812         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4813         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4814
4815         // Create some initial channels
4816         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4817
4818         // Rebalance the network a bit by relaying one payment through all the channels ...
4819         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4820
4821         let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4822
4823         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4824         assert_eq!(commitment_tx[0].input.len(), 1);
4825         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4826
4827         // Settle A's commitment tx on B' chain
4828         mine_transaction(&nodes[1], &commitment_tx[0]);
4829         check_added_monitors!(nodes[1], 1);
4830         let events = nodes[1].node.get_and_clear_pending_msg_events();
4831         match events[0] {
4832                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4833                 _ => panic!("Unexpected event"),
4834         }
4835
4836         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4837         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4838         assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4839         check_spends!(node_txn[0],  commitment_tx[0].clone());
4840         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4841         check_spends!(node_txn[1], chan_1.3.clone());
4842         check_spends!(node_txn[2], node_txn[1]);
4843
4844         mine_transaction(&nodes[1], &node_txn[0]);
4845         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4846         expect_payment_failed!(nodes[1], our_payment_hash, true);
4847
4848         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4849         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4850         check_spends!(spend_txn[0], commitment_tx[0]);
4851         check_spends!(spend_txn[1], node_txn[0]);
4852         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4853 }
4854
4855 #[test]
4856 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4857         let chanmon_cfgs = create_chanmon_cfgs(2);
4858         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4859         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4860         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4861
4862         // Create some initial channels
4863         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4864
4865         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4866         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4867         assert_eq!(revoked_local_txn[0].input.len(), 1);
4868         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4869
4870         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4871
4872         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4873         check_closed_broadcast!(nodes[1], true);
4874         check_added_monitors!(nodes[1], 1);
4875
4876         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4877         assert_eq!(node_txn.len(), 2);
4878         assert_eq!(node_txn[0].input.len(), 2);
4879         check_spends!(node_txn[0], revoked_local_txn[0]);
4880
4881         mine_transaction(&nodes[1], &node_txn[0]);
4882         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4883
4884         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4885         assert_eq!(spend_txn.len(), 1);
4886         check_spends!(spend_txn[0], node_txn[0]);
4887 }
4888
4889 #[test]
4890 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4891         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4892         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4893         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4894         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4895         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4896
4897         // Create some initial channels
4898         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4899
4900         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4901         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4902         assert_eq!(revoked_local_txn[0].input.len(), 1);
4903         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4904
4905         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4906
4907         // A will generate HTLC-Timeout from revoked commitment tx
4908         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4909         check_closed_broadcast!(nodes[0], true);
4910         check_added_monitors!(nodes[0], 1);
4911
4912         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4913         assert_eq!(revoked_htlc_txn.len(), 2);
4914         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4915         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4916         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4917         check_spends!(revoked_htlc_txn[1], chan_1.3);
4918
4919         // B will generate justice tx from A's revoked commitment/HTLC tx
4920         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4921         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4922         check_closed_broadcast!(nodes[1], true);
4923         check_added_monitors!(nodes[1], 1);
4924
4925         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4926         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4927         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4928         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4929         // transactions next...
4930         assert_eq!(node_txn[0].input.len(), 3);
4931         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4932
4933         assert_eq!(node_txn[1].input.len(), 2);
4934         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4935         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4936                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4937         } else {
4938                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4939                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4940         }
4941
4942         assert_eq!(node_txn[2].input.len(), 1);
4943         check_spends!(node_txn[2], chan_1.3);
4944
4945         mine_transaction(&nodes[1], &node_txn[1]);
4946         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4947
4948         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4949         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4950         assert_eq!(spend_txn.len(), 1);
4951         assert_eq!(spend_txn[0].input.len(), 1);
4952         check_spends!(spend_txn[0], node_txn[1]);
4953 }
4954
4955 #[test]
4956 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4957         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4958         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4959         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4960         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4961         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4962
4963         // Create some initial channels
4964         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4965
4966         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4967         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4968         assert_eq!(revoked_local_txn[0].input.len(), 1);
4969         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4970
4971         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4972         assert_eq!(revoked_local_txn[0].output.len(), 2);
4973
4974         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4975
4976         // B will generate HTLC-Success from revoked commitment tx
4977         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4978         check_closed_broadcast!(nodes[1], true);
4979         check_added_monitors!(nodes[1], 1);
4980         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4981
4982         assert_eq!(revoked_htlc_txn.len(), 2);
4983         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4984         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4985         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4986
4987         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4988         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4989         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4990
4991         // A will generate justice tx from B's revoked commitment/HTLC tx
4992         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4993         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4994         check_closed_broadcast!(nodes[0], true);
4995         check_added_monitors!(nodes[0], 1);
4996
4997         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4998         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4999
5000         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5001         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5002         // transactions next...
5003         assert_eq!(node_txn[0].input.len(), 2);
5004         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5005         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5006                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5007         } else {
5008                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5009                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5010         }
5011
5012         assert_eq!(node_txn[1].input.len(), 1);
5013         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5014
5015         check_spends!(node_txn[2], chan_1.3);
5016
5017         mine_transaction(&nodes[0], &node_txn[1]);
5018         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5019
5020         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5021         // didn't try to generate any new transactions.
5022
5023         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5024         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5025         assert_eq!(spend_txn.len(), 3);
5026         assert_eq!(spend_txn[0].input.len(), 1);
5027         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5028         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5029         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5030         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5031 }
5032
5033 #[test]
5034 fn test_onchain_to_onchain_claim() {
5035         // Test that in case of channel closure, we detect the state of output and claim HTLC
5036         // on downstream peer's remote commitment tx.
5037         // First, have C claim an HTLC against its own latest commitment transaction.
5038         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5039         // channel.
5040         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5041         // gets broadcast.
5042
5043         let chanmon_cfgs = create_chanmon_cfgs(3);
5044         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5045         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5046         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5047
5048         // Create some initial channels
5049         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5050         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5051
5052         // Rebalance the network a bit by relaying one payment through all the channels ...
5053         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5054         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5055
5056         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5057         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5058         check_spends!(commitment_tx[0], chan_2.3);
5059         nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5060         check_added_monitors!(nodes[2], 1);
5061         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5062         assert!(updates.update_add_htlcs.is_empty());
5063         assert!(updates.update_fail_htlcs.is_empty());
5064         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5065         assert!(updates.update_fail_malformed_htlcs.is_empty());
5066
5067         mine_transaction(&nodes[2], &commitment_tx[0]);
5068         check_closed_broadcast!(nodes[2], true);
5069         check_added_monitors!(nodes[2], 1);
5070
5071         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5072         assert_eq!(c_txn.len(), 3);
5073         assert_eq!(c_txn[0], c_txn[2]);
5074         assert_eq!(commitment_tx[0], c_txn[1]);
5075         check_spends!(c_txn[1], chan_2.3);
5076         check_spends!(c_txn[2], c_txn[1]);
5077         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5078         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5079         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5080         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5081
5082         // 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
5083         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5084         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5085         {
5086                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5087                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5088                 assert_eq!(b_txn.len(), 3);
5089                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5090                 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5091                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5092                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5093                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5094                 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5095                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5096                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5097                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5098                 b_txn.clear();
5099         }
5100         check_added_monitors!(nodes[1], 1);
5101         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5102         assert_eq!(msg_events.len(), 3);
5103         check_added_monitors!(nodes[1], 1);
5104         match msg_events[0] {
5105                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5106                 _ => panic!("Unexpected event"),
5107         }
5108         match msg_events[1] {
5109                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5110                 _ => panic!("Unexpected event"),
5111         }
5112         match msg_events[2] {
5113                 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, .. } } => {
5114                         assert!(update_add_htlcs.is_empty());
5115                         assert!(update_fail_htlcs.is_empty());
5116                         assert_eq!(update_fulfill_htlcs.len(), 1);
5117                         assert!(update_fail_malformed_htlcs.is_empty());
5118                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5119                 },
5120                 _ => panic!("Unexpected event"),
5121         };
5122         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5123         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5124         mine_transaction(&nodes[1], &commitment_tx[0]);
5125         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5126         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5127         assert_eq!(b_txn.len(), 3);
5128         check_spends!(b_txn[1], chan_1.3);
5129         check_spends!(b_txn[2], b_txn[1]);
5130         check_spends!(b_txn[0], commitment_tx[0]);
5131         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5132         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5133         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5134
5135         check_closed_broadcast!(nodes[1], true);
5136         check_added_monitors!(nodes[1], 1);
5137 }
5138
5139 #[test]
5140 fn test_duplicate_payment_hash_one_failure_one_success() {
5141         // Topology : A --> B --> C
5142         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5143         let chanmon_cfgs = create_chanmon_cfgs(3);
5144         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5145         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5146         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5147
5148         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5149         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5150
5151         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5152         *nodes[0].network_payment_count.borrow_mut() -= 1;
5153         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5154
5155         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5156         assert_eq!(commitment_txn[0].input.len(), 1);
5157         check_spends!(commitment_txn[0], chan_2.3);
5158
5159         mine_transaction(&nodes[1], &commitment_txn[0]);
5160         check_closed_broadcast!(nodes[1], true);
5161         check_added_monitors!(nodes[1], 1);
5162
5163         let htlc_timeout_tx;
5164         { // Extract one of the two HTLC-Timeout transaction
5165                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5166                 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5167                 assert_eq!(node_txn.len(), 5);
5168                 check_spends!(node_txn[0], commitment_txn[0]);
5169                 assert_eq!(node_txn[0].input.len(), 1);
5170                 check_spends!(node_txn[1], commitment_txn[0]);
5171                 assert_eq!(node_txn[1].input.len(), 1);
5172                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5173                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5174                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5175                 check_spends!(node_txn[2], chan_2.3);
5176                 check_spends!(node_txn[3], node_txn[2]);
5177                 check_spends!(node_txn[4], node_txn[2]);
5178                 htlc_timeout_tx = node_txn[1].clone();
5179         }
5180
5181         nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5182         mine_transaction(&nodes[2], &commitment_txn[0]);
5183         check_added_monitors!(nodes[2], 3);
5184         let events = nodes[2].node.get_and_clear_pending_msg_events();
5185         match events[0] {
5186                 MessageSendEvent::UpdateHTLCs { .. } => {},
5187                 _ => panic!("Unexpected event"),
5188         }
5189         match events[1] {
5190                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5191                 _ => panic!("Unexepected event"),
5192         }
5193         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5194         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)
5195         check_spends!(htlc_success_txn[2], chan_2.3);
5196         check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5197         check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5198         assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5199         assert_eq!(htlc_success_txn[0].input.len(), 1);
5200         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5201         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5202         assert_eq!(htlc_success_txn[1].input.len(), 1);
5203         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5204         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5205         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5206         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5207
5208         mine_transaction(&nodes[1], &htlc_timeout_tx);
5209         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5210         expect_pending_htlcs_forwardable!(nodes[1]);
5211         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5212         assert!(htlc_updates.update_add_htlcs.is_empty());
5213         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5214         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5215         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5216         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5217         check_added_monitors!(nodes[1], 1);
5218
5219         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5220         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5221         {
5222                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5223                 let events = nodes[0].node.get_and_clear_pending_msg_events();
5224                 assert_eq!(events.len(), 1);
5225                 match events[0] {
5226                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
5227                         },
5228                         _ => { panic!("Unexpected event"); }
5229                 }
5230         }
5231         expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5232
5233         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5234         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5235         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5236         assert!(updates.update_add_htlcs.is_empty());
5237         assert!(updates.update_fail_htlcs.is_empty());
5238         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5239         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5240         assert!(updates.update_fail_malformed_htlcs.is_empty());
5241         check_added_monitors!(nodes[1], 1);
5242
5243         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5244         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5245
5246         let events = nodes[0].node.get_and_clear_pending_events();
5247         match events[0] {
5248                 Event::PaymentSent { ref payment_preimage } => {
5249                         assert_eq!(*payment_preimage, our_payment_preimage);
5250                 }
5251                 _ => panic!("Unexpected event"),
5252         }
5253 }
5254
5255 #[test]
5256 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5257         let chanmon_cfgs = create_chanmon_cfgs(2);
5258         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5259         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5260         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5261
5262         // Create some initial channels
5263         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5264
5265         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5266         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5267         assert_eq!(local_txn.len(), 1);
5268         assert_eq!(local_txn[0].input.len(), 1);
5269         check_spends!(local_txn[0], chan_1.3);
5270
5271         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5272         nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5273         check_added_monitors!(nodes[1], 1);
5274         mine_transaction(&nodes[1], &local_txn[0]);
5275         check_added_monitors!(nodes[1], 1);
5276         let events = nodes[1].node.get_and_clear_pending_msg_events();
5277         match events[0] {
5278                 MessageSendEvent::UpdateHTLCs { .. } => {},
5279                 _ => panic!("Unexpected event"),
5280         }
5281         match events[1] {
5282                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5283                 _ => panic!("Unexepected event"),
5284         }
5285         let node_tx = {
5286                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5287                 assert_eq!(node_txn.len(), 3);
5288                 assert_eq!(node_txn[0], node_txn[2]);
5289                 assert_eq!(node_txn[1], local_txn[0]);
5290                 assert_eq!(node_txn[0].input.len(), 1);
5291                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5292                 check_spends!(node_txn[0], local_txn[0]);
5293                 node_txn[0].clone()
5294         };
5295
5296         mine_transaction(&nodes[1], &node_tx);
5297         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5298
5299         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5300         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5301         assert_eq!(spend_txn.len(), 1);
5302         check_spends!(spend_txn[0], node_tx);
5303 }
5304
5305 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5306         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5307         // unrevoked commitment transaction.
5308         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5309         // a remote RAA before they could be failed backwards (and combinations thereof).
5310         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5311         // use the same payment hashes.
5312         // Thus, we use a six-node network:
5313         //
5314         // A \         / E
5315         //    - C - D -
5316         // B /         \ F
5317         // And test where C fails back to A/B when D announces its latest commitment transaction
5318         let chanmon_cfgs = create_chanmon_cfgs(6);
5319         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5320         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5321         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5322         let logger = test_utils::TestLogger::new();
5323
5324         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5325         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5326         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5327         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5328         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5329
5330         // Rebalance and check output sanity...
5331         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5332         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5333         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5334
5335         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5336         // 0th HTLC:
5337         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
5338         // 1st HTLC:
5339         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
5340         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5341         let our_node_id = &nodes[1].node.get_our_node_id();
5342         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5343         // 2nd HTLC:
5344         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
5345         // 3rd HTLC:
5346         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
5347         // 4th HTLC:
5348         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5349         // 5th HTLC:
5350         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5351         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5352         // 6th HTLC:
5353         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5354         // 7th HTLC:
5355         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5356
5357         // 8th HTLC:
5358         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5359         // 9th HTLC:
5360         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5361         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
5362
5363         // 10th HTLC:
5364         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
5365         // 11th HTLC:
5366         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5367         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5368
5369         // Double-check that six of the new HTLC were added
5370         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5371         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5372         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5373         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5374
5375         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5376         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5377         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5378         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5379         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5380         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5381         check_added_monitors!(nodes[4], 0);
5382         expect_pending_htlcs_forwardable!(nodes[4]);
5383         check_added_monitors!(nodes[4], 1);
5384
5385         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5386         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5387         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5388         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5389         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5390         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5391
5392         // Fail 3rd below-dust and 7th above-dust HTLCs
5393         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5394         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5395         check_added_monitors!(nodes[5], 0);
5396         expect_pending_htlcs_forwardable!(nodes[5]);
5397         check_added_monitors!(nodes[5], 1);
5398
5399         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5400         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5401         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5402         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5403
5404         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5405
5406         expect_pending_htlcs_forwardable!(nodes[3]);
5407         check_added_monitors!(nodes[3], 1);
5408         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5409         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5410         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5411         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5412         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5413         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5414         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5415         if deliver_last_raa {
5416                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5417         } else {
5418                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5419         }
5420
5421         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5422         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5423         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5424         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5425         //
5426         // We now broadcast the latest commitment transaction, which *should* result in failures for
5427         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5428         // the non-broadcast above-dust HTLCs.
5429         //
5430         // Alternatively, we may broadcast the previous commitment transaction, which should only
5431         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5432         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5433
5434         if announce_latest {
5435                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5436         } else {
5437                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5438         }
5439         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5440         check_closed_broadcast!(nodes[2], true);
5441         expect_pending_htlcs_forwardable!(nodes[2]);
5442         check_added_monitors!(nodes[2], 3);
5443
5444         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5445         assert_eq!(cs_msgs.len(), 2);
5446         let mut a_done = false;
5447         for msg in cs_msgs {
5448                 match msg {
5449                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5450                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5451                                 // should be failed-backwards here.
5452                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5453                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5454                                         for htlc in &updates.update_fail_htlcs {
5455                                                 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 });
5456                                         }
5457                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5458                                         assert!(!a_done);
5459                                         a_done = true;
5460                                         &nodes[0]
5461                                 } else {
5462                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5463                                         for htlc in &updates.update_fail_htlcs {
5464                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5465                                         }
5466                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5467                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5468                                         &nodes[1]
5469                                 };
5470                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5471                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5472                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5473                                 if announce_latest {
5474                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5475                                         if *node_id == nodes[0].node.get_our_node_id() {
5476                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5477                                         }
5478                                 }
5479                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5480                         },
5481                         _ => panic!("Unexpected event"),
5482                 }
5483         }
5484
5485         let as_events = nodes[0].node.get_and_clear_pending_events();
5486         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5487         let mut as_failds = HashSet::new();
5488         for event in as_events.iter() {
5489                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5490                         assert!(as_failds.insert(*payment_hash));
5491                         if *payment_hash != payment_hash_2 {
5492                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5493                         } else {
5494                                 assert!(!rejected_by_dest);
5495                         }
5496                 } else { panic!("Unexpected event"); }
5497         }
5498         assert!(as_failds.contains(&payment_hash_1));
5499         assert!(as_failds.contains(&payment_hash_2));
5500         if announce_latest {
5501                 assert!(as_failds.contains(&payment_hash_3));
5502                 assert!(as_failds.contains(&payment_hash_5));
5503         }
5504         assert!(as_failds.contains(&payment_hash_6));
5505
5506         let bs_events = nodes[1].node.get_and_clear_pending_events();
5507         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5508         let mut bs_failds = HashSet::new();
5509         for event in bs_events.iter() {
5510                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5511                         assert!(bs_failds.insert(*payment_hash));
5512                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5513                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5514                         } else {
5515                                 assert!(!rejected_by_dest);
5516                         }
5517                 } else { panic!("Unexpected event"); }
5518         }
5519         assert!(bs_failds.contains(&payment_hash_1));
5520         assert!(bs_failds.contains(&payment_hash_2));
5521         if announce_latest {
5522                 assert!(bs_failds.contains(&payment_hash_4));
5523         }
5524         assert!(bs_failds.contains(&payment_hash_5));
5525
5526         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5527         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5528         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5529         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5530         // PaymentFailureNetworkUpdates.
5531         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5532         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5533         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5534         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5535         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5536                 match event {
5537                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5538                         _ => panic!("Unexpected event"),
5539                 }
5540         }
5541 }
5542
5543 #[test]
5544 fn test_fail_backwards_latest_remote_announce_a() {
5545         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5546 }
5547
5548 #[test]
5549 fn test_fail_backwards_latest_remote_announce_b() {
5550         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5551 }
5552
5553 #[test]
5554 fn test_fail_backwards_previous_remote_announce() {
5555         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5556         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5557         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5558 }
5559
5560 #[test]
5561 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5562         let chanmon_cfgs = create_chanmon_cfgs(2);
5563         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5564         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5565         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5566
5567         // Create some initial channels
5568         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5569
5570         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5571         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5572         assert_eq!(local_txn[0].input.len(), 1);
5573         check_spends!(local_txn[0], chan_1.3);
5574
5575         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5576         mine_transaction(&nodes[0], &local_txn[0]);
5577         check_closed_broadcast!(nodes[0], true);
5578         check_added_monitors!(nodes[0], 1);
5579
5580         let htlc_timeout = {
5581                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5582                 assert_eq!(node_txn[0].input.len(), 1);
5583                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5584                 check_spends!(node_txn[0], local_txn[0]);
5585                 node_txn[0].clone()
5586         };
5587
5588         mine_transaction(&nodes[0], &htlc_timeout);
5589         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5590         expect_payment_failed!(nodes[0], our_payment_hash, true);
5591
5592         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5593         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5594         assert_eq!(spend_txn.len(), 3);
5595         check_spends!(spend_txn[0], local_txn[0]);
5596         check_spends!(spend_txn[1], htlc_timeout);
5597         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5598 }
5599
5600 #[test]
5601 fn test_key_derivation_params() {
5602         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5603         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5604         // let us re-derive the channel key set to then derive a delayed_payment_key.
5605
5606         let chanmon_cfgs = create_chanmon_cfgs(3);
5607
5608         // We manually create the node configuration to backup the seed.
5609         let seed = [42; 32];
5610         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5611         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);
5612         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 };
5613         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5614         node_cfgs.remove(0);
5615         node_cfgs.insert(0, node);
5616
5617         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5618         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5619
5620         // Create some initial channels
5621         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5622         // for node 0
5623         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5624         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5625         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5626
5627         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5628         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5629         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5630         assert_eq!(local_txn_1[0].input.len(), 1);
5631         check_spends!(local_txn_1[0], chan_1.3);
5632
5633         // We check funding pubkey are unique
5634         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]));
5635         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]));
5636         if from_0_funding_key_0 == from_1_funding_key_0
5637             || from_0_funding_key_0 == from_1_funding_key_1
5638             || from_0_funding_key_1 == from_1_funding_key_0
5639             || from_0_funding_key_1 == from_1_funding_key_1 {
5640                 panic!("Funding pubkeys aren't unique");
5641         }
5642
5643         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5644         mine_transaction(&nodes[0], &local_txn_1[0]);
5645         check_closed_broadcast!(nodes[0], true);
5646         check_added_monitors!(nodes[0], 1);
5647
5648         let htlc_timeout = {
5649                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5650                 assert_eq!(node_txn[0].input.len(), 1);
5651                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5652                 check_spends!(node_txn[0], local_txn_1[0]);
5653                 node_txn[0].clone()
5654         };
5655
5656         mine_transaction(&nodes[0], &htlc_timeout);
5657         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5658         expect_payment_failed!(nodes[0], our_payment_hash, true);
5659
5660         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5661         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5662         let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5663         assert_eq!(spend_txn.len(), 3);
5664         check_spends!(spend_txn[0], local_txn_1[0]);
5665         check_spends!(spend_txn[1], htlc_timeout);
5666         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5667 }
5668
5669 #[test]
5670 fn test_static_output_closing_tx() {
5671         let chanmon_cfgs = create_chanmon_cfgs(2);
5672         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5673         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5674         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5675
5676         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5677
5678         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5679         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5680
5681         mine_transaction(&nodes[0], &closing_tx);
5682         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5683
5684         let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5685         assert_eq!(spend_txn.len(), 1);
5686         check_spends!(spend_txn[0], closing_tx);
5687
5688         mine_transaction(&nodes[1], &closing_tx);
5689         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5690
5691         let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5692         assert_eq!(spend_txn.len(), 1);
5693         check_spends!(spend_txn[0], closing_tx);
5694 }
5695
5696 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5697         let chanmon_cfgs = create_chanmon_cfgs(2);
5698         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5699         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5700         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5701         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5702
5703         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5704
5705         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5706         // present in B's local commitment transaction, but none of A's commitment transactions.
5707         assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5708         check_added_monitors!(nodes[1], 1);
5709
5710         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5711         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5712         let events = nodes[0].node.get_and_clear_pending_events();
5713         assert_eq!(events.len(), 1);
5714         match events[0] {
5715                 Event::PaymentSent { payment_preimage } => {
5716                         assert_eq!(payment_preimage, our_payment_preimage);
5717                 },
5718                 _ => panic!("Unexpected event"),
5719         }
5720
5721         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5722         check_added_monitors!(nodes[0], 1);
5723         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5724         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5725         check_added_monitors!(nodes[1], 1);
5726
5727         let starting_block = nodes[1].best_block_info();
5728         let mut block = Block {
5729                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5730                 txdata: vec![],
5731         };
5732         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5733                 connect_block(&nodes[1], &block);
5734                 block.header.prev_blockhash = block.block_hash();
5735         }
5736         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5737         check_closed_broadcast!(nodes[1], true);
5738         check_added_monitors!(nodes[1], 1);
5739 }
5740
5741 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5742         let chanmon_cfgs = create_chanmon_cfgs(2);
5743         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5744         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5745         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5746         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5747         let logger = test_utils::TestLogger::new();
5748
5749         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5750         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5751         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV, &logger).unwrap();
5752         nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5753         check_added_monitors!(nodes[0], 1);
5754
5755         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5756
5757         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5758         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5759         // to "time out" the HTLC.
5760
5761         let starting_block = nodes[1].best_block_info();
5762         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5763
5764         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5765                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5766                 header.prev_blockhash = header.block_hash();
5767         }
5768         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5769         check_closed_broadcast!(nodes[0], true);
5770         check_added_monitors!(nodes[0], 1);
5771 }
5772
5773 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5774         let chanmon_cfgs = create_chanmon_cfgs(3);
5775         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5776         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5777         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5778         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5779
5780         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5781         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5782         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5783         // actually revoked.
5784         let htlc_value = if use_dust { 50000 } else { 3000000 };
5785         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5786         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5787         expect_pending_htlcs_forwardable!(nodes[1]);
5788         check_added_monitors!(nodes[1], 1);
5789
5790         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5791         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5792         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5793         check_added_monitors!(nodes[0], 1);
5794         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5795         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5796         check_added_monitors!(nodes[1], 1);
5797         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5798         check_added_monitors!(nodes[1], 1);
5799         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5800
5801         if check_revoke_no_close {
5802                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5803                 check_added_monitors!(nodes[0], 1);
5804         }
5805
5806         let starting_block = nodes[1].best_block_info();
5807         let mut block = Block {
5808                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5809                 txdata: vec![],
5810         };
5811         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5812                 connect_block(&nodes[0], &block);
5813                 block.header.prev_blockhash = block.block_hash();
5814         }
5815         if !check_revoke_no_close {
5816                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5817                 check_closed_broadcast!(nodes[0], true);
5818                 check_added_monitors!(nodes[0], 1);
5819         } else {
5820                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5821         }
5822 }
5823
5824 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5825 // There are only a few cases to test here:
5826 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5827 //    broadcastable commitment transactions result in channel closure,
5828 //  * its included in an unrevoked-but-previous remote commitment transaction,
5829 //  * its included in the latest remote or local commitment transactions.
5830 // We test each of the three possible commitment transactions individually and use both dust and
5831 // non-dust HTLCs.
5832 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5833 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5834 // tested for at least one of the cases in other tests.
5835 #[test]
5836 fn htlc_claim_single_commitment_only_a() {
5837         do_htlc_claim_local_commitment_only(true);
5838         do_htlc_claim_local_commitment_only(false);
5839
5840         do_htlc_claim_current_remote_commitment_only(true);
5841         do_htlc_claim_current_remote_commitment_only(false);
5842 }
5843
5844 #[test]
5845 fn htlc_claim_single_commitment_only_b() {
5846         do_htlc_claim_previous_remote_commitment_only(true, false);
5847         do_htlc_claim_previous_remote_commitment_only(false, false);
5848         do_htlc_claim_previous_remote_commitment_only(true, true);
5849         do_htlc_claim_previous_remote_commitment_only(false, true);
5850 }
5851
5852 #[test]
5853 #[should_panic]
5854 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5855         let chanmon_cfgs = create_chanmon_cfgs(2);
5856         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5857         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5858         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5859         //Force duplicate channel ids
5860         for node in nodes.iter() {
5861                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5862         }
5863
5864         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5865         let channel_value_satoshis=10000;
5866         let push_msat=10001;
5867         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5868         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5869         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5870
5871         //Create a second channel with a channel_id collision
5872         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5873 }
5874
5875 #[test]
5876 fn bolt2_open_channel_sending_node_checks_part2() {
5877         let chanmon_cfgs = create_chanmon_cfgs(2);
5878         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5879         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5880         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5881
5882         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5883         let channel_value_satoshis=2^24;
5884         let push_msat=10001;
5885         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5886
5887         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5888         let channel_value_satoshis=10000;
5889         // Test when push_msat is equal to 1000 * funding_satoshis.
5890         let push_msat=1000*channel_value_satoshis+1;
5891         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5892
5893         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5894         let channel_value_satoshis=10000;
5895         let push_msat=10001;
5896         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
5897         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5898         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5899
5900         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5901         // 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
5902         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5903
5904         // 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.
5905         assert!(BREAKDOWN_TIMEOUT>0);
5906         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5907
5908         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5909         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5910         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5911
5912         // 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.
5913         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5914         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5915         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5916         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5917         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5918 }
5919
5920 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5921 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5922 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5923 // is no longer affordable once it's freed.
5924 #[test]
5925 fn test_fail_holding_cell_htlc_upon_free() {
5926         let chanmon_cfgs = create_chanmon_cfgs(2);
5927         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5928         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5929         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5930         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5931         let logger = test_utils::TestLogger::new();
5932
5933         // First nodes[0] generates an update_fee, setting the channel's
5934         // pending_update_fee.
5935         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
5936         check_added_monitors!(nodes[0], 1);
5937
5938         let events = nodes[0].node.get_and_clear_pending_msg_events();
5939         assert_eq!(events.len(), 1);
5940         let (update_msg, commitment_signed) = match events[0] {
5941                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5942                         (update_fee.as_ref(), commitment_signed)
5943                 },
5944                 _ => panic!("Unexpected event"),
5945         };
5946
5947         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5948
5949         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5950         let channel_reserve = chan_stat.channel_reserve_msat;
5951         let feerate = get_feerate!(nodes[0], chan.2);
5952
5953         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5954         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5955         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5956         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5957         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
5958
5959         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5960         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5961         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5962         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5963
5964         // Flush the pending fee update.
5965         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5966         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5967         check_added_monitors!(nodes[1], 1);
5968         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5969         check_added_monitors!(nodes[0], 1);
5970
5971         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5972         // HTLC, but now that the fee has been raised the payment will now fail, causing
5973         // us to surface its failure to the user.
5974         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5975         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5976         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
5977         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);
5978         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5979
5980         // Check that the payment failed to be sent out.
5981         let events = nodes[0].node.get_and_clear_pending_events();
5982         assert_eq!(events.len(), 1);
5983         match &events[0] {
5984                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
5985                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5986                         assert_eq!(*rejected_by_dest, false);
5987                         assert_eq!(*error_code, None);
5988                         assert_eq!(*error_data, None);
5989                 },
5990                 _ => panic!("Unexpected event"),
5991         }
5992 }
5993
5994 // Test that if multiple HTLCs are released from the holding cell and one is
5995 // valid but the other is no longer valid upon release, the valid HTLC can be
5996 // successfully completed while the other one fails as expected.
5997 #[test]
5998 fn test_free_and_fail_holding_cell_htlcs() {
5999         let chanmon_cfgs = create_chanmon_cfgs(2);
6000         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6001         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6002         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6003         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6004         let logger = test_utils::TestLogger::new();
6005
6006         // First nodes[0] generates an update_fee, setting the channel's
6007         // pending_update_fee.
6008         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6009         check_added_monitors!(nodes[0], 1);
6010
6011         let events = nodes[0].node.get_and_clear_pending_msg_events();
6012         assert_eq!(events.len(), 1);
6013         let (update_msg, commitment_signed) = match events[0] {
6014                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6015                         (update_fee.as_ref(), commitment_signed)
6016                 },
6017                 _ => panic!("Unexpected event"),
6018         };
6019
6020         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6021
6022         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6023         let channel_reserve = chan_stat.channel_reserve_msat;
6024         let feerate = get_feerate!(nodes[0], chan.2);
6025
6026         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6027         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6028         let amt_1 = 20000;
6029         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6030         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6031         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6032         let route_1 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], amt_1, TEST_FINAL_CLTV, &logger).unwrap();
6033         let route_2 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], amt_2, TEST_FINAL_CLTV, &logger).unwrap();
6034
6035         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6036         nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6037         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6038         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6039         nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6040         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6041         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6042
6043         // Flush the pending fee update.
6044         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6045         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6046         check_added_monitors!(nodes[1], 1);
6047         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6048         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6049         check_added_monitors!(nodes[0], 2);
6050
6051         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6052         // but now that the fee has been raised the second payment will now fail, causing us
6053         // to surface its failure to the user. The first payment should succeed.
6054         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6055         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6056         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6057         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);
6058         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6059
6060         // Check that the second payment failed to be sent out.
6061         let events = nodes[0].node.get_and_clear_pending_events();
6062         assert_eq!(events.len(), 1);
6063         match &events[0] {
6064                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6065                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6066                         assert_eq!(*rejected_by_dest, false);
6067                         assert_eq!(*error_code, None);
6068                         assert_eq!(*error_data, None);
6069                 },
6070                 _ => panic!("Unexpected event"),
6071         }
6072
6073         // Complete the first payment and the RAA from the fee update.
6074         let (payment_event, send_raa_event) = {
6075                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6076                 assert_eq!(msgs.len(), 2);
6077                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6078         };
6079         let raa = match send_raa_event {
6080                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6081                 _ => panic!("Unexpected event"),
6082         };
6083         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6084         check_added_monitors!(nodes[1], 1);
6085         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6086         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6087         let events = nodes[1].node.get_and_clear_pending_events();
6088         assert_eq!(events.len(), 1);
6089         match events[0] {
6090                 Event::PendingHTLCsForwardable { .. } => {},
6091                 _ => panic!("Unexpected event"),
6092         }
6093         nodes[1].node.process_pending_htlc_forwards();
6094         let events = nodes[1].node.get_and_clear_pending_events();
6095         assert_eq!(events.len(), 1);
6096         match events[0] {
6097                 Event::PaymentReceived { .. } => {},
6098                 _ => panic!("Unexpected event"),
6099         }
6100         nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6101         check_added_monitors!(nodes[1], 1);
6102         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6103         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6104         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6105         let events = nodes[0].node.get_and_clear_pending_events();
6106         assert_eq!(events.len(), 1);
6107         match events[0] {
6108                 Event::PaymentSent { ref payment_preimage } => {
6109                         assert_eq!(*payment_preimage, payment_preimage_1);
6110                 }
6111                 _ => panic!("Unexpected event"),
6112         }
6113 }
6114
6115 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6116 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6117 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6118 // once it's freed.
6119 #[test]
6120 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6121         let chanmon_cfgs = create_chanmon_cfgs(3);
6122         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6123         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6124         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6125         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6126         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6127         let logger = test_utils::TestLogger::new();
6128
6129         // First nodes[1] generates an update_fee, setting the channel's
6130         // pending_update_fee.
6131         nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6132         check_added_monitors!(nodes[1], 1);
6133
6134         let events = nodes[1].node.get_and_clear_pending_msg_events();
6135         assert_eq!(events.len(), 1);
6136         let (update_msg, commitment_signed) = match events[0] {
6137                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6138                         (update_fee.as_ref(), commitment_signed)
6139                 },
6140                 _ => panic!("Unexpected event"),
6141         };
6142
6143         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6144
6145         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6146         let channel_reserve = chan_stat.channel_reserve_msat;
6147         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6148
6149         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6150         let feemsat = 239;
6151         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6152         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6153         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6154         let payment_event = {
6155                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6156                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6157                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6158                 check_added_monitors!(nodes[0], 1);
6159
6160                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6161                 assert_eq!(events.len(), 1);
6162
6163                 SendEvent::from_event(events.remove(0))
6164         };
6165         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6166         check_added_monitors!(nodes[1], 0);
6167         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6168         expect_pending_htlcs_forwardable!(nodes[1]);
6169
6170         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6171         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6172
6173         // Flush the pending fee update.
6174         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6175         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6176         check_added_monitors!(nodes[2], 1);
6177         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6178         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6179         check_added_monitors!(nodes[1], 2);
6180
6181         // A final RAA message is generated to finalize the fee update.
6182         let events = nodes[1].node.get_and_clear_pending_msg_events();
6183         assert_eq!(events.len(), 1);
6184
6185         let raa_msg = match &events[0] {
6186                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6187                         msg.clone()
6188                 },
6189                 _ => panic!("Unexpected event"),
6190         };
6191
6192         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6193         check_added_monitors!(nodes[2], 1);
6194         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6195
6196         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6197         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6198         assert_eq!(process_htlc_forwards_event.len(), 1);
6199         match &process_htlc_forwards_event[0] {
6200                 &Event::PendingHTLCsForwardable { .. } => {},
6201                 _ => panic!("Unexpected event"),
6202         }
6203
6204         // In response, we call ChannelManager's process_pending_htlc_forwards
6205         nodes[1].node.process_pending_htlc_forwards();
6206         check_added_monitors!(nodes[1], 1);
6207
6208         // This causes the HTLC to be failed backwards.
6209         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6210         assert_eq!(fail_event.len(), 1);
6211         let (fail_msg, commitment_signed) = match &fail_event[0] {
6212                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6213                         assert_eq!(updates.update_add_htlcs.len(), 0);
6214                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6215                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6216                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6217                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6218                 },
6219                 _ => panic!("Unexpected event"),
6220         };
6221
6222         // Pass the failure messages back to nodes[0].
6223         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6224         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6225
6226         // Complete the HTLC failure+removal process.
6227         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6228         check_added_monitors!(nodes[0], 1);
6229         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6230         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6231         check_added_monitors!(nodes[1], 2);
6232         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6233         assert_eq!(final_raa_event.len(), 1);
6234         let raa = match &final_raa_event[0] {
6235                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6236                 _ => panic!("Unexpected event"),
6237         };
6238         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6239         let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6240         assert_eq!(fail_msg_event.len(), 1);
6241         match &fail_msg_event[0] {
6242                 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6243                 _ => panic!("Unexpected event"),
6244         }
6245         let failure_event = nodes[0].node.get_and_clear_pending_events();
6246         assert_eq!(failure_event.len(), 1);
6247         match &failure_event[0] {
6248                 &Event::PaymentFailed { rejected_by_dest, .. } => {
6249                         assert!(!rejected_by_dest);
6250                 },
6251                 _ => panic!("Unexpected event"),
6252         }
6253         check_added_monitors!(nodes[0], 1);
6254 }
6255
6256 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6257 // 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.
6258 //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.
6259
6260 #[test]
6261 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6262         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6263         let chanmon_cfgs = create_chanmon_cfgs(2);
6264         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6265         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6266         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6267         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6268
6269         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6270         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6271         let logger = test_utils::TestLogger::new();
6272         let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6273         route.paths[0][0].fee_msat = 100;
6274
6275         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6276                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6277         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6278         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6279 }
6280
6281 #[test]
6282 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6283         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6284         let chanmon_cfgs = create_chanmon_cfgs(2);
6285         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6286         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6287         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6288         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6289         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6290
6291         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6292         let logger = test_utils::TestLogger::new();
6293         let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6294         route.paths[0][0].fee_msat = 0;
6295         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6296                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6297
6298         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6299         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6300 }
6301
6302 #[test]
6303 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6304         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6305         let chanmon_cfgs = create_chanmon_cfgs(2);
6306         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6307         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6308         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6309         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6310
6311         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6312         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6313         let logger = test_utils::TestLogger::new();
6314         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6315         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6316         check_added_monitors!(nodes[0], 1);
6317         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6318         updates.update_add_htlcs[0].amount_msat = 0;
6319
6320         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6321         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6322         check_closed_broadcast!(nodes[1], true).unwrap();
6323         check_added_monitors!(nodes[1], 1);
6324 }
6325
6326 #[test]
6327 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6328         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6329         //It is enforced when constructing a route.
6330         let chanmon_cfgs = create_chanmon_cfgs(2);
6331         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6332         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6333         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6334         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6335         let logger = test_utils::TestLogger::new();
6336
6337         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6338
6339         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6340         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 100000000, 500000001, &logger).unwrap();
6341         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6342                 assert_eq!(err, &"Channel CLTV overflowed?"));
6343 }
6344
6345 #[test]
6346 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6347         //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.
6348         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6349         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6350         let chanmon_cfgs = create_chanmon_cfgs(2);
6351         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6352         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6353         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6354         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6355         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6356
6357         let logger = test_utils::TestLogger::new();
6358         for i in 0..max_accepted_htlcs {
6359                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6360                 let payment_event = {
6361                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6362                         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6363                         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6364                         check_added_monitors!(nodes[0], 1);
6365
6366                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6367                         assert_eq!(events.len(), 1);
6368                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6369                                 assert_eq!(htlcs[0].htlc_id, i);
6370                         } else {
6371                                 assert!(false);
6372                         }
6373                         SendEvent::from_event(events.remove(0))
6374                 };
6375                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6376                 check_added_monitors!(nodes[1], 0);
6377                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6378
6379                 expect_pending_htlcs_forwardable!(nodes[1]);
6380                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6381         }
6382         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6383         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6384         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6385         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6386                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6387
6388         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6389         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6390 }
6391
6392 #[test]
6393 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6394         //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.
6395         let chanmon_cfgs = create_chanmon_cfgs(2);
6396         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6397         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6398         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6399         let channel_value = 100000;
6400         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6401         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6402
6403         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6404
6405         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6406         // Manually create a route over our max in flight (which our router normally automatically
6407         // limits us to.
6408         let route = Route { paths: vec![vec![RouteHop {
6409            pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6410            short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6411            fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6412         }]] };
6413         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6414                 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)));
6415
6416         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6417         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);
6418
6419         send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6420 }
6421
6422 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6423 #[test]
6424 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6425         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6426         let chanmon_cfgs = create_chanmon_cfgs(2);
6427         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6428         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6429         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6430         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6431         let htlc_minimum_msat: u64;
6432         {
6433                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6434                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6435                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6436         }
6437
6438         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6439         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6440         let logger = test_utils::TestLogger::new();
6441         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], htlc_minimum_msat, TEST_FINAL_CLTV, &logger).unwrap();
6442         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6443         check_added_monitors!(nodes[0], 1);
6444         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6445         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6446         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6447         assert!(nodes[1].node.list_channels().is_empty());
6448         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6449         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()));
6450         check_added_monitors!(nodes[1], 1);
6451 }
6452
6453 #[test]
6454 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6455         //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
6456         let chanmon_cfgs = create_chanmon_cfgs(2);
6457         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6458         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6459         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6460         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6461         let logger = test_utils::TestLogger::new();
6462
6463         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6464         let channel_reserve = chan_stat.channel_reserve_msat;
6465         let feerate = get_feerate!(nodes[0], chan.2);
6466         // The 2* and +1 are for the fee spike reserve.
6467         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6468
6469         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6470         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6471         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6472         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6473         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6474         check_added_monitors!(nodes[0], 1);
6475         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6476
6477         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6478         // at this time channel-initiatee receivers are not required to enforce that senders
6479         // respect the fee_spike_reserve.
6480         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6481         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6482
6483         assert!(nodes[1].node.list_channels().is_empty());
6484         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6485         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6486         check_added_monitors!(nodes[1], 1);
6487 }
6488
6489 #[test]
6490 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6491         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6492         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6493         let chanmon_cfgs = create_chanmon_cfgs(2);
6494         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6495         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6496         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6497         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6498         let logger = test_utils::TestLogger::new();
6499
6500         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6501         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6502
6503         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6504         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 3999999, TEST_FINAL_CLTV, &logger).unwrap();
6505
6506         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6507         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6508         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6509         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6510
6511         let mut msg = msgs::UpdateAddHTLC {
6512                 channel_id: chan.2,
6513                 htlc_id: 0,
6514                 amount_msat: 1000,
6515                 payment_hash: our_payment_hash,
6516                 cltv_expiry: htlc_cltv,
6517                 onion_routing_packet: onion_packet.clone(),
6518         };
6519
6520         for i in 0..super::channel::OUR_MAX_HTLCS {
6521                 msg.htlc_id = i as u64;
6522                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6523         }
6524         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6525         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6526
6527         assert!(nodes[1].node.list_channels().is_empty());
6528         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6529         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6530         check_added_monitors!(nodes[1], 1);
6531 }
6532
6533 #[test]
6534 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6535         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6536         let chanmon_cfgs = create_chanmon_cfgs(2);
6537         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6538         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6539         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6540         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6541         let logger = test_utils::TestLogger::new();
6542
6543         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6544         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6545         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6546         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6547         check_added_monitors!(nodes[0], 1);
6548         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6549         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6550         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6551
6552         assert!(nodes[1].node.list_channels().is_empty());
6553         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6554         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6555         check_added_monitors!(nodes[1], 1);
6556 }
6557
6558 #[test]
6559 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6560         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6561         let chanmon_cfgs = create_chanmon_cfgs(2);
6562         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6563         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6564         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6565         let logger = test_utils::TestLogger::new();
6566
6567         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6568         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6569         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6570         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6571         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6572         check_added_monitors!(nodes[0], 1);
6573         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6574         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6575         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6576
6577         assert!(nodes[1].node.list_channels().is_empty());
6578         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6579         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6580         check_added_monitors!(nodes[1], 1);
6581 }
6582
6583 #[test]
6584 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6585         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6586         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6587         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6588         let chanmon_cfgs = create_chanmon_cfgs(2);
6589         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6590         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6591         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6592         let logger = test_utils::TestLogger::new();
6593
6594         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6595         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6596         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6597         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6598         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6599         check_added_monitors!(nodes[0], 1);
6600         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6601         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6602
6603         //Disconnect and Reconnect
6604         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6605         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6606         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6607         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6608         assert_eq!(reestablish_1.len(), 1);
6609         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6610         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6611         assert_eq!(reestablish_2.len(), 1);
6612         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6613         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6614         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6615         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6616
6617         //Resend HTLC
6618         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6619         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6620         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6621         check_added_monitors!(nodes[1], 1);
6622         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6623
6624         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6625
6626         assert!(nodes[1].node.list_channels().is_empty());
6627         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6628         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6629         check_added_monitors!(nodes[1], 1);
6630 }
6631
6632 #[test]
6633 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6634         //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.
6635
6636         let chanmon_cfgs = create_chanmon_cfgs(2);
6637         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6638         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6639         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6640         let logger = test_utils::TestLogger::new();
6641         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6642         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6643         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6644         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6645         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6646
6647         check_added_monitors!(nodes[0], 1);
6648         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6649         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6650
6651         let update_msg = msgs::UpdateFulfillHTLC{
6652                 channel_id: chan.2,
6653                 htlc_id: 0,
6654                 payment_preimage: our_payment_preimage,
6655         };
6656
6657         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6658
6659         assert!(nodes[0].node.list_channels().is_empty());
6660         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6661         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()));
6662         check_added_monitors!(nodes[0], 1);
6663 }
6664
6665 #[test]
6666 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6667         //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.
6668
6669         let chanmon_cfgs = create_chanmon_cfgs(2);
6670         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6671         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6672         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6673         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6674         let logger = test_utils::TestLogger::new();
6675
6676         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6677         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6678         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6679         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6680         check_added_monitors!(nodes[0], 1);
6681         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6682         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6683
6684         let update_msg = msgs::UpdateFailHTLC{
6685                 channel_id: chan.2,
6686                 htlc_id: 0,
6687                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6688         };
6689
6690         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6691
6692         assert!(nodes[0].node.list_channels().is_empty());
6693         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6694         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()));
6695         check_added_monitors!(nodes[0], 1);
6696 }
6697
6698 #[test]
6699 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6700         //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.
6701
6702         let chanmon_cfgs = create_chanmon_cfgs(2);
6703         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6704         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6705         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6706         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6707         let logger = test_utils::TestLogger::new();
6708
6709         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6710         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6711         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6712         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6713         check_added_monitors!(nodes[0], 1);
6714         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6715         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6716         let update_msg = msgs::UpdateFailMalformedHTLC{
6717                 channel_id: chan.2,
6718                 htlc_id: 0,
6719                 sha256_of_onion: [1; 32],
6720                 failure_code: 0x8000,
6721         };
6722
6723         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6724
6725         assert!(nodes[0].node.list_channels().is_empty());
6726         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6727         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()));
6728         check_added_monitors!(nodes[0], 1);
6729 }
6730
6731 #[test]
6732 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6733         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6734
6735         let chanmon_cfgs = create_chanmon_cfgs(2);
6736         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6737         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6738         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6739         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6740
6741         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6742
6743         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6744         check_added_monitors!(nodes[1], 1);
6745
6746         let events = nodes[1].node.get_and_clear_pending_msg_events();
6747         assert_eq!(events.len(), 1);
6748         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6749                 match events[0] {
6750                         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, .. } } => {
6751                                 assert!(update_add_htlcs.is_empty());
6752                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6753                                 assert!(update_fail_htlcs.is_empty());
6754                                 assert!(update_fail_malformed_htlcs.is_empty());
6755                                 assert!(update_fee.is_none());
6756                                 update_fulfill_htlcs[0].clone()
6757                         },
6758                         _ => panic!("Unexpected event"),
6759                 }
6760         };
6761
6762         update_fulfill_msg.htlc_id = 1;
6763
6764         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6765
6766         assert!(nodes[0].node.list_channels().is_empty());
6767         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6768         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6769         check_added_monitors!(nodes[0], 1);
6770 }
6771
6772 #[test]
6773 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6774         //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.
6775
6776         let chanmon_cfgs = create_chanmon_cfgs(2);
6777         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6778         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6779         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6780         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6781
6782         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6783
6784         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6785         check_added_monitors!(nodes[1], 1);
6786
6787         let events = nodes[1].node.get_and_clear_pending_msg_events();
6788         assert_eq!(events.len(), 1);
6789         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6790                 match events[0] {
6791                         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, .. } } => {
6792                                 assert!(update_add_htlcs.is_empty());
6793                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6794                                 assert!(update_fail_htlcs.is_empty());
6795                                 assert!(update_fail_malformed_htlcs.is_empty());
6796                                 assert!(update_fee.is_none());
6797                                 update_fulfill_htlcs[0].clone()
6798                         },
6799                         _ => panic!("Unexpected event"),
6800                 }
6801         };
6802
6803         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6804
6805         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6806
6807         assert!(nodes[0].node.list_channels().is_empty());
6808         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6809         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6810         check_added_monitors!(nodes[0], 1);
6811 }
6812
6813 #[test]
6814 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6815         //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.
6816
6817         let chanmon_cfgs = create_chanmon_cfgs(2);
6818         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6819         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6820         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6821         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6822         let logger = test_utils::TestLogger::new();
6823
6824         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6825         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6826         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6827         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6828         check_added_monitors!(nodes[0], 1);
6829
6830         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6831         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6832
6833         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6834         check_added_monitors!(nodes[1], 0);
6835         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6836
6837         let events = nodes[1].node.get_and_clear_pending_msg_events();
6838
6839         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6840                 match events[0] {
6841                         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, .. } } => {
6842                                 assert!(update_add_htlcs.is_empty());
6843                                 assert!(update_fulfill_htlcs.is_empty());
6844                                 assert!(update_fail_htlcs.is_empty());
6845                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6846                                 assert!(update_fee.is_none());
6847                                 update_fail_malformed_htlcs[0].clone()
6848                         },
6849                         _ => panic!("Unexpected event"),
6850                 }
6851         };
6852         update_msg.failure_code &= !0x8000;
6853         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6854
6855         assert!(nodes[0].node.list_channels().is_empty());
6856         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6857         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6858         check_added_monitors!(nodes[0], 1);
6859 }
6860
6861 #[test]
6862 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6863         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6864         //    * 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.
6865
6866         let chanmon_cfgs = create_chanmon_cfgs(3);
6867         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6868         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6869         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6870         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6871         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6872         let logger = test_utils::TestLogger::new();
6873
6874         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6875
6876         //First hop
6877         let mut payment_event = {
6878                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6879                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
6880                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6881                 check_added_monitors!(nodes[0], 1);
6882                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6883                 assert_eq!(events.len(), 1);
6884                 SendEvent::from_event(events.remove(0))
6885         };
6886         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6887         check_added_monitors!(nodes[1], 0);
6888         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6889         expect_pending_htlcs_forwardable!(nodes[1]);
6890         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6891         assert_eq!(events_2.len(), 1);
6892         check_added_monitors!(nodes[1], 1);
6893         payment_event = SendEvent::from_event(events_2.remove(0));
6894         assert_eq!(payment_event.msgs.len(), 1);
6895
6896         //Second Hop
6897         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6898         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6899         check_added_monitors!(nodes[2], 0);
6900         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6901
6902         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6903         assert_eq!(events_3.len(), 1);
6904         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6905                 match events_3[0] {
6906                         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 } } => {
6907                                 assert!(update_add_htlcs.is_empty());
6908                                 assert!(update_fulfill_htlcs.is_empty());
6909                                 assert!(update_fail_htlcs.is_empty());
6910                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6911                                 assert!(update_fee.is_none());
6912                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6913                         },
6914                         _ => panic!("Unexpected event"),
6915                 }
6916         };
6917
6918         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6919
6920         check_added_monitors!(nodes[1], 0);
6921         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6922         expect_pending_htlcs_forwardable!(nodes[1]);
6923         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6924         assert_eq!(events_4.len(), 1);
6925
6926         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6927         match events_4[0] {
6928                 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, .. } } => {
6929                         assert!(update_add_htlcs.is_empty());
6930                         assert!(update_fulfill_htlcs.is_empty());
6931                         assert_eq!(update_fail_htlcs.len(), 1);
6932                         assert!(update_fail_malformed_htlcs.is_empty());
6933                         assert!(update_fee.is_none());
6934                 },
6935                 _ => panic!("Unexpected event"),
6936         };
6937
6938         check_added_monitors!(nodes[1], 1);
6939 }
6940
6941 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6942         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6943         // 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
6944         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6945
6946         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6947         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6948         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6949         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6950         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6951         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6952
6953         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6954
6955         // We route 2 dust-HTLCs between A and B
6956         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6957         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6958         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6959
6960         // Cache one local commitment tx as previous
6961         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6962
6963         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6964         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
6965         check_added_monitors!(nodes[1], 0);
6966         expect_pending_htlcs_forwardable!(nodes[1]);
6967         check_added_monitors!(nodes[1], 1);
6968
6969         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6970         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6971         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6972         check_added_monitors!(nodes[0], 1);
6973
6974         // Cache one local commitment tx as lastest
6975         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6976
6977         let events = nodes[0].node.get_and_clear_pending_msg_events();
6978         match events[0] {
6979                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6980                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6981                 },
6982                 _ => panic!("Unexpected event"),
6983         }
6984         match events[1] {
6985                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6986                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6987                 },
6988                 _ => panic!("Unexpected event"),
6989         }
6990
6991         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6992         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6993         if announce_latest {
6994                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6995         } else {
6996                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6997         }
6998
6999         check_closed_broadcast!(nodes[0], true);
7000         check_added_monitors!(nodes[0], 1);
7001
7002         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7003         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7004         let events = nodes[0].node.get_and_clear_pending_events();
7005         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7006         assert_eq!(events.len(), 2);
7007         let mut first_failed = false;
7008         for event in events {
7009                 match event {
7010                         Event::PaymentFailed { payment_hash, .. } => {
7011                                 if payment_hash == payment_hash_1 {
7012                                         assert!(!first_failed);
7013                                         first_failed = true;
7014                                 } else {
7015                                         assert_eq!(payment_hash, payment_hash_2);
7016                                 }
7017                         }
7018                         _ => panic!("Unexpected event"),
7019                 }
7020         }
7021 }
7022
7023 #[test]
7024 fn test_failure_delay_dust_htlc_local_commitment() {
7025         do_test_failure_delay_dust_htlc_local_commitment(true);
7026         do_test_failure_delay_dust_htlc_local_commitment(false);
7027 }
7028
7029 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7030         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7031         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7032         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7033         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7034         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7035         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7036
7037         let chanmon_cfgs = create_chanmon_cfgs(3);
7038         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7039         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7040         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7041         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7042
7043         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7044
7045         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7046         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7047
7048         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7049         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7050
7051         // We revoked bs_commitment_tx
7052         if revoked {
7053                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7054                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7055         }
7056
7057         let mut timeout_tx = Vec::new();
7058         if local {
7059                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7060                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7061                 check_closed_broadcast!(nodes[0], true);
7062                 check_added_monitors!(nodes[0], 1);
7063                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7064                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7065                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7066                 expect_payment_failed!(nodes[0], dust_hash, true);
7067                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7068                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7069                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7070                 mine_transaction(&nodes[0], &timeout_tx[0]);
7071                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7072                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7073         } else {
7074                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7075                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7076                 check_closed_broadcast!(nodes[0], true);
7077                 check_added_monitors!(nodes[0], 1);
7078                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7079                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7080                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7081                 if !revoked {
7082                         expect_payment_failed!(nodes[0], dust_hash, true);
7083                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7084                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7085                         mine_transaction(&nodes[0], &timeout_tx[0]);
7086                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7087                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7088                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7089                 } else {
7090                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7091                         // commitment tx
7092                         let events = nodes[0].node.get_and_clear_pending_events();
7093                         assert_eq!(events.len(), 2);
7094                         let first;
7095                         match events[0] {
7096                                 Event::PaymentFailed { payment_hash, .. } => {
7097                                         if payment_hash == dust_hash { first = true; }
7098                                         else { first = false; }
7099                                 },
7100                                 _ => panic!("Unexpected event"),
7101                         }
7102                         match events[1] {
7103                                 Event::PaymentFailed { payment_hash, .. } => {
7104                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7105                                         else { assert_eq!(payment_hash, dust_hash); }
7106                                 },
7107                                 _ => panic!("Unexpected event"),
7108                         }
7109                 }
7110         }
7111 }
7112
7113 #[test]
7114 fn test_sweep_outbound_htlc_failure_update() {
7115         do_test_sweep_outbound_htlc_failure_update(false, true);
7116         do_test_sweep_outbound_htlc_failure_update(false, false);
7117         do_test_sweep_outbound_htlc_failure_update(true, false);
7118 }
7119
7120 #[test]
7121 fn test_upfront_shutdown_script() {
7122         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7123         // enforce it at shutdown message
7124
7125         let mut config = UserConfig::default();
7126         config.channel_options.announced_channel = true;
7127         config.peer_channel_config_limits.force_announced_channel_preference = false;
7128         config.channel_options.commit_upfront_shutdown_pubkey = false;
7129         let user_cfgs = [None, Some(config), None];
7130         let chanmon_cfgs = create_chanmon_cfgs(3);
7131         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7132         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7133         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7134
7135         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7136         let flags = InitFeatures::known();
7137         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7138         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7139         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7140         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7141         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
7142         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7143     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()));
7144         check_added_monitors!(nodes[2], 1);
7145
7146         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7147         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7148         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7149         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7150         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7151         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7152         let events = nodes[2].node.get_and_clear_pending_msg_events();
7153         assert_eq!(events.len(), 1);
7154         match events[0] {
7155                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7156                 _ => panic!("Unexpected event"),
7157         }
7158
7159         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7160         let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7161         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7162         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7163         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7164         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7165         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
7166         let events = nodes[1].node.get_and_clear_pending_msg_events();
7167         assert_eq!(events.len(), 1);
7168         match events[0] {
7169                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7170                 _ => panic!("Unexpected event"),
7171         }
7172
7173         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7174         // channel smoothly, opt-out is from channel initiator here
7175         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7176         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7177         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7178         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7179         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7180         let events = nodes[0].node.get_and_clear_pending_msg_events();
7181         assert_eq!(events.len(), 1);
7182         match events[0] {
7183                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7184                 _ => panic!("Unexpected event"),
7185         }
7186
7187         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7188         //// channel smoothly
7189         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7190         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7191         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7192         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7193         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7194         let events = nodes[0].node.get_and_clear_pending_msg_events();
7195         assert_eq!(events.len(), 2);
7196         match events[0] {
7197                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7198                 _ => panic!("Unexpected event"),
7199         }
7200         match events[1] {
7201                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7202                 _ => panic!("Unexpected event"),
7203         }
7204 }
7205
7206 #[test]
7207 fn test_upfront_shutdown_script_unsupport_segwit() {
7208         // We test that channel is closed early
7209         // if a segwit program is passed as upfront shutdown script,
7210         // but the peer does not support segwit.
7211         let chanmon_cfgs = create_chanmon_cfgs(2);
7212         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7213         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7214         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7215
7216         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
7217
7218         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7219         open_channel.shutdown_scriptpubkey = Present(Builder::new().push_int(16)
7220                 .push_slice(&[0, 0])
7221                 .into_script());
7222
7223         let features = InitFeatures::known().clear_shutdown_anysegwit();
7224         nodes[0].node.handle_open_channel(&nodes[0].node.get_our_node_id(), features, &open_channel);
7225
7226         let events = nodes[0].node.get_and_clear_pending_msg_events();
7227         assert_eq!(events.len(), 1);
7228         match events[0] {
7229                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7230                         assert_eq!(node_id, nodes[0].node.get_our_node_id());
7231                         assert!(regex::Regex::new(r"Peer is signaling upfront_shutdown but has provided a non-accepted scriptpubkey format. script: (\([A-Fa-f0-9]+\))").unwrap().is_match(&*msg.data));
7232                 },
7233                 _ => panic!("Unexpected event"),
7234         }
7235 }
7236
7237 #[test]
7238 fn test_shutdown_script_any_segwit_allowed() {
7239         let mut config = UserConfig::default();
7240         config.channel_options.announced_channel = true;
7241         config.peer_channel_config_limits.force_announced_channel_preference = false;
7242         config.channel_options.commit_upfront_shutdown_pubkey = false;
7243         let user_cfgs = [None, Some(config), None];
7244         let chanmon_cfgs = create_chanmon_cfgs(3);
7245         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7246         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7247         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7248
7249         //// We test if the remote peer accepts opt_shutdown_anysegwit, a witness program can be used on shutdown
7250         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7251         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7252         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7253         node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7254                 .push_slice(&[0, 0])
7255                 .into_script();
7256         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7257         let events = nodes[0].node.get_and_clear_pending_msg_events();
7258         assert_eq!(events.len(), 2);
7259         match events[0] {
7260                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7261                 _ => panic!("Unexpected event"),
7262         }
7263         match events[1] {
7264                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7265                 _ => panic!("Unexpected event"),
7266         }
7267 }
7268
7269 #[test]
7270 fn test_shutdown_script_any_segwit_not_allowed() {
7271         let mut config = UserConfig::default();
7272         config.channel_options.announced_channel = true;
7273         config.peer_channel_config_limits.force_announced_channel_preference = false;
7274         config.channel_options.commit_upfront_shutdown_pubkey = false;
7275         let user_cfgs = [None, Some(config), None];
7276         let chanmon_cfgs = create_chanmon_cfgs(3);
7277         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7278         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7279         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7280
7281         //// We test that if the remote peer does not accept opt_shutdown_anysegwit, the witness program cannot be used on shutdown
7282         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7283         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7284         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7285         // Make an any segwit version script
7286         node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7287                 .push_slice(&[0, 0])
7288                 .into_script();
7289         let flags_no = InitFeatures::known().clear_shutdown_anysegwit();
7290         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &flags_no, &node_0_shutdown);
7291         let events = nodes[0].node.get_and_clear_pending_msg_events();
7292         assert_eq!(events.len(), 2);
7293         match events[1] {
7294                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7295                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7296                         assert_eq!(msg.data, "Got a nonstandard scriptpubkey (60020000) from remote peer".to_owned())
7297                 },
7298                 _ => panic!("Unexpected event"),
7299         }
7300         check_added_monitors!(nodes[0], 1);
7301 }
7302
7303 #[test]
7304 fn test_shutdown_script_segwit_but_not_anysegwit() {
7305         let mut config = UserConfig::default();
7306         config.channel_options.announced_channel = true;
7307         config.peer_channel_config_limits.force_announced_channel_preference = false;
7308         config.channel_options.commit_upfront_shutdown_pubkey = false;
7309         let user_cfgs = [None, Some(config), None];
7310         let chanmon_cfgs = create_chanmon_cfgs(3);
7311         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7312         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7313         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7314
7315         //// We test that if shutdown any segwit is supported and we send a witness script with 0 version, this is not accepted
7316         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7317         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7318         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7319         // Make a segwit script that is not a valid as any segwit
7320         node_0_shutdown.scriptpubkey = Builder::new().push_int(0)
7321                 .push_slice(&[0, 0])
7322                 .into_script();
7323         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7324         let events = nodes[0].node.get_and_clear_pending_msg_events();
7325         assert_eq!(events.len(), 2);
7326         match events[1] {
7327                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7328                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7329                         assert_eq!(msg.data, "Got a nonstandard scriptpubkey (00020000) from remote peer".to_owned())
7330                 },
7331                 _ => panic!("Unexpected event"),
7332         }
7333         check_added_monitors!(nodes[0], 1);
7334 }
7335
7336 #[test]
7337 fn test_user_configurable_csv_delay() {
7338         // We test our channel constructors yield errors when we pass them absurd csv delay
7339
7340         let mut low_our_to_self_config = UserConfig::default();
7341         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7342         let mut high_their_to_self_config = UserConfig::default();
7343         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7344         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7345         let chanmon_cfgs = create_chanmon_cfgs(2);
7346         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7347         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7348         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7349
7350         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7351         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) {
7352                 match error {
7353                         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())); },
7354                         _ => panic!("Unexpected event"),
7355                 }
7356         } else { assert!(false) }
7357
7358         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7359         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7360         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7361         open_channel.to_self_delay = 200;
7362         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) {
7363                 match error {
7364                         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()));  },
7365                         _ => panic!("Unexpected event"),
7366                 }
7367         } else { assert!(false); }
7368
7369         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7370         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7371         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()));
7372         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7373         accept_channel.to_self_delay = 200;
7374         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7375         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7376                 match action {
7377                         &ErrorAction::SendErrorMessage { ref msg } => {
7378                                 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()));
7379                         },
7380                         _ => { assert!(false); }
7381                 }
7382         } else { assert!(false); }
7383
7384         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7385         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7386         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7387         open_channel.to_self_delay = 200;
7388         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) {
7389                 match error {
7390                         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())); },
7391                         _ => panic!("Unexpected event"),
7392                 }
7393         } else { assert!(false); }
7394 }
7395
7396 #[test]
7397 fn test_data_loss_protect() {
7398         // We want to be sure that :
7399         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7400         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7401         // * we close channel in case of detecting other being fallen behind
7402         // * we are able to claim our own outputs thanks to to_remote being static
7403         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7404         let persister;
7405         let logger;
7406         let fee_estimator;
7407         let tx_broadcaster;
7408         let chain_source;
7409         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7410         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7411         // during signing due to revoked tx
7412         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7413         let keys_manager = &chanmon_cfgs[0].keys_manager;
7414         let monitor;
7415         let node_state_0;
7416         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7417         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7418         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7419
7420         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7421
7422         // Cache node A state before any channel update
7423         let previous_node_state = nodes[0].node.encode();
7424         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7425         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7426
7427         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7428         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7429
7430         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7431         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7432
7433         // Restore node A from previous state
7434         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7435         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7436         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7437         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7438         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7439         persister = test_utils::TestPersister::new();
7440         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7441         node_state_0 = {
7442                 let mut channel_monitors = HashMap::new();
7443                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7444                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
7445                         keys_manager: keys_manager,
7446                         fee_estimator: &fee_estimator,
7447                         chain_monitor: &monitor,
7448                         logger: &logger,
7449                         tx_broadcaster: &tx_broadcaster,
7450                         default_config: UserConfig::default(),
7451                         channel_monitors,
7452                 }).unwrap().1
7453         };
7454         nodes[0].node = &node_state_0;
7455         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7456         nodes[0].chain_monitor = &monitor;
7457         nodes[0].chain_source = &chain_source;
7458
7459         check_added_monitors!(nodes[0], 1);
7460
7461         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7462         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7463
7464         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7465
7466         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7467         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7468         check_added_monitors!(nodes[0], 1);
7469
7470         {
7471                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7472                 assert_eq!(node_txn.len(), 0);
7473         }
7474
7475         let mut reestablish_1 = Vec::with_capacity(1);
7476         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7477                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7478                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7479                         reestablish_1.push(msg.clone());
7480                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7481                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7482                         match action {
7483                                 &ErrorAction::SendErrorMessage { ref msg } => {
7484                                         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");
7485                                 },
7486                                 _ => panic!("Unexpected event!"),
7487                         }
7488                 } else {
7489                         panic!("Unexpected event")
7490                 }
7491         }
7492
7493         // Check we close channel detecting A is fallen-behind
7494         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7495         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7496         check_added_monitors!(nodes[1], 1);
7497
7498
7499         // Check A is able to claim to_remote output
7500         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7501         assert_eq!(node_txn.len(), 1);
7502         check_spends!(node_txn[0], chan.3);
7503         assert_eq!(node_txn[0].output.len(), 2);
7504         mine_transaction(&nodes[0], &node_txn[0]);
7505         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7506         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 1000000);
7507         assert_eq!(spend_txn.len(), 1);
7508         check_spends!(spend_txn[0], node_txn[0]);
7509 }
7510
7511 #[test]
7512 fn test_check_htlc_underpaying() {
7513         // Send payment through A -> B but A is maliciously
7514         // sending a probe payment (i.e less than expected value0
7515         // to B, B should refuse payment.
7516
7517         let chanmon_cfgs = create_chanmon_cfgs(2);
7518         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7519         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7520         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7521
7522         // Create some initial channels
7523         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7524
7525         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7526
7527         // Node 3 is expecting payment of 100_000 but receive 10_000,
7528         // fail htlc like we didn't know the preimage.
7529         nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7530         nodes[1].node.process_pending_htlc_forwards();
7531
7532         let events = nodes[1].node.get_and_clear_pending_msg_events();
7533         assert_eq!(events.len(), 1);
7534         let (update_fail_htlc, commitment_signed) = match events[0] {
7535                 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 } } => {
7536                         assert!(update_add_htlcs.is_empty());
7537                         assert!(update_fulfill_htlcs.is_empty());
7538                         assert_eq!(update_fail_htlcs.len(), 1);
7539                         assert!(update_fail_malformed_htlcs.is_empty());
7540                         assert!(update_fee.is_none());
7541                         (update_fail_htlcs[0].clone(), commitment_signed)
7542                 },
7543                 _ => panic!("Unexpected event"),
7544         };
7545         check_added_monitors!(nodes[1], 1);
7546
7547         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7548         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7549
7550         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7551         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7552         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7553         expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7554         nodes[1].node.get_and_clear_pending_events();
7555 }
7556
7557 #[test]
7558 fn test_announce_disable_channels() {
7559         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7560         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7561
7562         let chanmon_cfgs = create_chanmon_cfgs(2);
7563         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7564         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7565         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7566
7567         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7568         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7569         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7570
7571         // Disconnect peers
7572         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7573         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7574
7575         nodes[0].node.timer_tick_occurred(); // dirty -> stagged
7576         nodes[0].node.timer_tick_occurred(); // staged -> fresh
7577         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7578         assert_eq!(msg_events.len(), 3);
7579         for e in msg_events {
7580                 match e {
7581                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7582                                 let short_id = msg.contents.short_channel_id;
7583                                 // Check generated channel_update match list in PendingChannelUpdate
7584                                 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7585                                         panic!("Generated ChannelUpdate for wrong chan!");
7586                                 }
7587                         },
7588                         _ => panic!("Unexpected event"),
7589                 }
7590         }
7591         // Reconnect peers
7592         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7593         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7594         assert_eq!(reestablish_1.len(), 3);
7595         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7596         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7597         assert_eq!(reestablish_2.len(), 3);
7598
7599         // Reestablish chan_1
7600         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7601         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7602         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7603         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7604         // Reestablish chan_2
7605         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7606         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7607         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7608         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7609         // Reestablish chan_3
7610         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7611         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7612         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7613         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7614
7615         nodes[0].node.timer_tick_occurred();
7616         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7617 }
7618
7619 #[test]
7620 fn test_bump_penalty_txn_on_revoked_commitment() {
7621         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7622         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7623
7624         let chanmon_cfgs = create_chanmon_cfgs(2);
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         let logger = test_utils::TestLogger::new();
7631
7632         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7633         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7634         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 3000000, 30, &logger).unwrap();
7635         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7636
7637         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7638         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7639         assert_eq!(revoked_txn[0].output.len(), 4);
7640         assert_eq!(revoked_txn[0].input.len(), 1);
7641         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7642         let revoked_txid = revoked_txn[0].txid();
7643
7644         let mut penalty_sum = 0;
7645         for outp in revoked_txn[0].output.iter() {
7646                 if outp.script_pubkey.is_v0_p2wsh() {
7647                         penalty_sum += outp.value;
7648                 }
7649         }
7650
7651         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7652         let header_114 = connect_blocks(&nodes[1], 14);
7653
7654         // Actually revoke tx by claiming a HTLC
7655         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7656         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7657         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7658         check_added_monitors!(nodes[1], 1);
7659
7660         // One or more justice tx should have been broadcast, check it
7661         let penalty_1;
7662         let feerate_1;
7663         {
7664                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7665                 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7666                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7667                 assert_eq!(node_txn[0].output.len(), 1);
7668                 check_spends!(node_txn[0], revoked_txn[0]);
7669                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7670                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7671                 penalty_1 = node_txn[0].txid();
7672                 node_txn.clear();
7673         };
7674
7675         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7676         connect_blocks(&nodes[1], 15);
7677         let mut penalty_2 = penalty_1;
7678         let mut feerate_2 = 0;
7679         {
7680                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7681                 assert_eq!(node_txn.len(), 1);
7682                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7683                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7684                         assert_eq!(node_txn[0].output.len(), 1);
7685                         check_spends!(node_txn[0], revoked_txn[0]);
7686                         penalty_2 = node_txn[0].txid();
7687                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7688                         assert_ne!(penalty_2, penalty_1);
7689                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7690                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7691                         // Verify 25% bump heuristic
7692                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7693                         node_txn.clear();
7694                 }
7695         }
7696         assert_ne!(feerate_2, 0);
7697
7698         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7699         connect_blocks(&nodes[1], 1);
7700         let penalty_3;
7701         let mut feerate_3 = 0;
7702         {
7703                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7704                 assert_eq!(node_txn.len(), 1);
7705                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7706                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7707                         assert_eq!(node_txn[0].output.len(), 1);
7708                         check_spends!(node_txn[0], revoked_txn[0]);
7709                         penalty_3 = node_txn[0].txid();
7710                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7711                         assert_ne!(penalty_3, penalty_2);
7712                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7713                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7714                         // Verify 25% bump heuristic
7715                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7716                         node_txn.clear();
7717                 }
7718         }
7719         assert_ne!(feerate_3, 0);
7720
7721         nodes[1].node.get_and_clear_pending_events();
7722         nodes[1].node.get_and_clear_pending_msg_events();
7723 }
7724
7725 #[test]
7726 fn test_bump_penalty_txn_on_revoked_htlcs() {
7727         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7728         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7729
7730         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7731         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7732         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7733         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7734         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7735
7736         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7737         // Lock HTLC in both directions
7738         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7739         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7740
7741         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7742         assert_eq!(revoked_local_txn[0].input.len(), 1);
7743         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7744
7745         // Revoke local commitment tx
7746         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7747
7748         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7749         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7750         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7751         check_closed_broadcast!(nodes[1], true);
7752         check_added_monitors!(nodes[1], 1);
7753
7754         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7755         assert_eq!(revoked_htlc_txn.len(), 4);
7756         if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7757                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7758                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7759                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7760                 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7761                 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7762                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7763         } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7764                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7765                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7766                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7767                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7768                 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7769                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7770         }
7771
7772         // Broadcast set of revoked txn on A
7773         let hash_128 = connect_blocks(&nodes[0], 40);
7774         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7775         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7776         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7777         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7778         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7779         let first;
7780         let feerate_1;
7781         let penalty_txn;
7782         {
7783                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7784                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7785                 // Verify claim tx are spending revoked HTLC txn
7786
7787                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7788                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7789                 // which are included in the same block (they are broadcasted because we scan the
7790                 // transactions linearly and generate claims as we go, they likely should be removed in the
7791                 // future).
7792                 assert_eq!(node_txn[0].input.len(), 1);
7793                 check_spends!(node_txn[0], revoked_local_txn[0]);
7794                 assert_eq!(node_txn[1].input.len(), 1);
7795                 check_spends!(node_txn[1], revoked_local_txn[0]);
7796                 assert_eq!(node_txn[2].input.len(), 1);
7797                 check_spends!(node_txn[2], revoked_local_txn[0]);
7798
7799                 // Each of the three justice transactions claim a separate (single) output of the three
7800                 // available, which we check here:
7801                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7802                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7803                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7804
7805                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7806                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7807
7808                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7809                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7810                 // a remote commitment tx has already been confirmed).
7811                 check_spends!(node_txn[3], chan.3);
7812
7813                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7814                 // output, checked above).
7815                 assert_eq!(node_txn[4].input.len(), 2);
7816                 assert_eq!(node_txn[4].output.len(), 1);
7817                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7818
7819                 first = node_txn[4].txid();
7820                 // Store both feerates for later comparison
7821                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7822                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7823                 penalty_txn = vec![node_txn[2].clone()];
7824                 node_txn.clear();
7825         }
7826
7827         // Connect one more block to see if bumped penalty are issued for HTLC txn
7828         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7829         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7830         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7831         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7832         {
7833                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7834                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7835
7836                 check_spends!(node_txn[0], revoked_local_txn[0]);
7837                 check_spends!(node_txn[1], revoked_local_txn[0]);
7838                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7839                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7840                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7841                 } else {
7842                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7843                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7844                 }
7845
7846                 node_txn.clear();
7847         };
7848
7849         // Few more blocks to confirm penalty txn
7850         connect_blocks(&nodes[0], 4);
7851         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7852         let header_144 = connect_blocks(&nodes[0], 9);
7853         let node_txn = {
7854                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7855                 assert_eq!(node_txn.len(), 1);
7856
7857                 assert_eq!(node_txn[0].input.len(), 2);
7858                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7859                 // Verify bumped tx is different and 25% bump heuristic
7860                 assert_ne!(first, node_txn[0].txid());
7861                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7862                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7863                 assert!(feerate_2 * 100 > feerate_1 * 125);
7864                 let txn = vec![node_txn[0].clone()];
7865                 node_txn.clear();
7866                 txn
7867         };
7868         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7869         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7870         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7871         connect_blocks(&nodes[0], 20);
7872         {
7873                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7874                 // We verify than no new transaction has been broadcast because previously
7875                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7876                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7877                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7878                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7879                 // up bumped justice generation.
7880                 assert_eq!(node_txn.len(), 0);
7881                 node_txn.clear();
7882         }
7883         check_closed_broadcast!(nodes[0], true);
7884         check_added_monitors!(nodes[0], 1);
7885 }
7886
7887 #[test]
7888 fn test_bump_penalty_txn_on_remote_commitment() {
7889         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7890         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7891
7892         // Create 2 HTLCs
7893         // Provide preimage for one
7894         // Check aggregation
7895
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 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7903         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7904
7905         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7906         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7907         assert_eq!(remote_txn[0].output.len(), 4);
7908         assert_eq!(remote_txn[0].input.len(), 1);
7909         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7910
7911         // Claim a HTLC without revocation (provide B monitor with preimage)
7912         nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7913         mine_transaction(&nodes[1], &remote_txn[0]);
7914         check_added_monitors!(nodes[1], 2);
7915
7916         // One or more claim tx should have been broadcast, check it
7917         let timeout;
7918         let preimage;
7919         let feerate_timeout;
7920         let feerate_preimage;
7921         {
7922                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7923                 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7924                 assert_eq!(node_txn[0].input.len(), 1);
7925                 assert_eq!(node_txn[1].input.len(), 1);
7926                 check_spends!(node_txn[0], remote_txn[0]);
7927                 check_spends!(node_txn[1], remote_txn[0]);
7928                 check_spends!(node_txn[2], chan.3);
7929                 check_spends!(node_txn[3], node_txn[2]);
7930                 check_spends!(node_txn[4], node_txn[2]);
7931                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7932                         timeout = node_txn[0].txid();
7933                         let index = node_txn[0].input[0].previous_output.vout;
7934                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7935                         feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7936
7937                         preimage = node_txn[1].txid();
7938                         let index = node_txn[1].input[0].previous_output.vout;
7939                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7940                         feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7941                 } else {
7942                         timeout = node_txn[1].txid();
7943                         let index = node_txn[1].input[0].previous_output.vout;
7944                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7945                         feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7946
7947                         preimage = node_txn[0].txid();
7948                         let index = node_txn[0].input[0].previous_output.vout;
7949                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7950                         feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7951                 }
7952                 node_txn.clear();
7953         };
7954         assert_ne!(feerate_timeout, 0);
7955         assert_ne!(feerate_preimage, 0);
7956
7957         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7958         connect_blocks(&nodes[1], 15);
7959         {
7960                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7961                 assert_eq!(node_txn.len(), 2);
7962                 assert_eq!(node_txn[0].input.len(), 1);
7963                 assert_eq!(node_txn[1].input.len(), 1);
7964                 check_spends!(node_txn[0], remote_txn[0]);
7965                 check_spends!(node_txn[1], remote_txn[0]);
7966                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7967                         let index = node_txn[0].input[0].previous_output.vout;
7968                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7969                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7970                         assert!(new_feerate * 100 > feerate_timeout * 125);
7971                         assert_ne!(timeout, node_txn[0].txid());
7972
7973                         let index = node_txn[1].input[0].previous_output.vout;
7974                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7975                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7976                         assert!(new_feerate * 100 > feerate_preimage * 125);
7977                         assert_ne!(preimage, node_txn[1].txid());
7978                 } else {
7979                         let index = node_txn[1].input[0].previous_output.vout;
7980                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7981                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7982                         assert!(new_feerate * 100 > feerate_timeout * 125);
7983                         assert_ne!(timeout, node_txn[1].txid());
7984
7985                         let index = node_txn[0].input[0].previous_output.vout;
7986                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7987                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7988                         assert!(new_feerate * 100 > feerate_preimage * 125);
7989                         assert_ne!(preimage, node_txn[0].txid());
7990                 }
7991                 node_txn.clear();
7992         }
7993
7994         nodes[1].node.get_and_clear_pending_events();
7995         nodes[1].node.get_and_clear_pending_msg_events();
7996 }
7997
7998 #[test]
7999 fn test_counterparty_raa_skip_no_crash() {
8000         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8001         // commitment transaction, we would have happily carried on and provided them the next
8002         // commitment transaction based on one RAA forward. This would probably eventually have led to
8003         // channel closure, but it would not have resulted in funds loss. Still, our
8004         // EnforcingSigner would have paniced as it doesn't like jumps into the future. Here, we
8005         // check simply that the channel is closed in response to such an RAA, but don't check whether
8006         // we decide to punish our counterparty for revoking their funds (as we don't currently
8007         // implement that).
8008         let chanmon_cfgs = create_chanmon_cfgs(2);
8009         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8010         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8011         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8012         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8013
8014         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8015         let keys = &guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8016         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8017         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8018         // Must revoke without gaps
8019         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8020         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8021                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8022
8023         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8024                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8025         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8026         check_added_monitors!(nodes[1], 1);
8027 }
8028
8029 #[test]
8030 fn test_bump_txn_sanitize_tracking_maps() {
8031         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8032         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8033
8034         let chanmon_cfgs = create_chanmon_cfgs(2);
8035         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8036         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8037         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8038
8039         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8040         // Lock HTLC in both directions
8041         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8042         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8043
8044         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8045         assert_eq!(revoked_local_txn[0].input.len(), 1);
8046         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8047
8048         // Revoke local commitment tx
8049         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8050
8051         // Broadcast set of revoked txn on A
8052         connect_blocks(&nodes[0], 52 - CHAN_CONFIRM_DEPTH);
8053         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8054         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8055
8056         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8057         check_closed_broadcast!(nodes[0], true);
8058         check_added_monitors!(nodes[0], 1);
8059         let penalty_txn = {
8060                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8061                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8062                 check_spends!(node_txn[0], revoked_local_txn[0]);
8063                 check_spends!(node_txn[1], revoked_local_txn[0]);
8064                 check_spends!(node_txn[2], revoked_local_txn[0]);
8065                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8066                 node_txn.clear();
8067                 penalty_txn
8068         };
8069         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8070         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8071         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8072         {
8073                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8074                 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8075                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8076                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8077                 }
8078         }
8079 }
8080
8081 #[test]
8082 fn test_override_channel_config() {
8083         let chanmon_cfgs = create_chanmon_cfgs(2);
8084         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8085         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8086         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8087
8088         // Node0 initiates a channel to node1 using the override config.
8089         let mut override_config = UserConfig::default();
8090         override_config.own_channel_config.our_to_self_delay = 200;
8091
8092         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8093
8094         // Assert the channel created by node0 is using the override config.
8095         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8096         assert_eq!(res.channel_flags, 0);
8097         assert_eq!(res.to_self_delay, 200);
8098 }
8099
8100 #[test]
8101 fn test_override_0msat_htlc_minimum() {
8102         let mut zero_config = UserConfig::default();
8103         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8104         let chanmon_cfgs = create_chanmon_cfgs(2);
8105         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8106         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8107         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8108
8109         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8110         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8111         assert_eq!(res.htlc_minimum_msat, 1);
8112
8113         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8114         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8115         assert_eq!(res.htlc_minimum_msat, 1);
8116 }
8117
8118 #[test]
8119 fn test_simple_payment_secret() {
8120         // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8121         // features, however.
8122         let chanmon_cfgs = create_chanmon_cfgs(3);
8123         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8124         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8125         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8126
8127         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8128         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8129         let logger = test_utils::TestLogger::new();
8130
8131         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8132         let payment_secret = PaymentSecret([0xdb; 32]);
8133         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8134         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8135         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8136         // Claiming with all the correct values but the wrong secret should result in nothing...
8137         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8138         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8139         // ...but with the right secret we should be able to claim all the way back
8140         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8141 }
8142
8143 #[test]
8144 fn test_simple_mpp() {
8145         // Simple test of sending a multi-path payment.
8146         let chanmon_cfgs = create_chanmon_cfgs(4);
8147         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8148         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8149         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8150
8151         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8152         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8153         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8154         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8155         let logger = test_utils::TestLogger::new();
8156
8157         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8158         let payment_secret = PaymentSecret([0xdb; 32]);
8159         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8160         let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3].node.get_our_node_id(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8161         let path = route.paths[0].clone();
8162         route.paths.push(path);
8163         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8164         route.paths[0][0].short_channel_id = chan_1_id;
8165         route.paths[0][1].short_channel_id = chan_3_id;
8166         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8167         route.paths[1][0].short_channel_id = chan_2_id;
8168         route.paths[1][1].short_channel_id = chan_4_id;
8169         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8170         // Claiming with all the correct values but the wrong secret should result in nothing...
8171         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8172         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8173         // ...but with the right secret we should be able to claim all the way back
8174         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8175 }
8176
8177 #[test]
8178 fn test_update_err_monitor_lockdown() {
8179         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8180         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8181         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8182         //
8183         // This scenario may happen in a watchtower setup, where watchtower process a block height
8184         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8185         // commitment at same time.
8186
8187         let chanmon_cfgs = create_chanmon_cfgs(2);
8188         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8189         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8190         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8191
8192         // Create some initial channel
8193         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8194         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8195
8196         // Rebalance the network to generate htlc in the two directions
8197         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8198
8199         // Route a HTLC from node 0 to node 1 (but don't settle)
8200         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8201
8202         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8203         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8204         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8205         let persister = test_utils::TestPersister::new();
8206         let watchtower = {
8207                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8208                 let monitor = monitors.get(&outpoint).unwrap();
8209                 let mut w = test_utils::TestVecWriter(Vec::new());
8210                 monitor.write(&mut w).unwrap();
8211                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8212                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8213                 assert!(new_monitor == *monitor);
8214                 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);
8215                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8216                 watchtower
8217         };
8218         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8219         watchtower.chain_monitor.block_connected(&header, &[], 200);
8220
8221         // Try to update ChannelMonitor
8222         assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8223         check_added_monitors!(nodes[1], 1);
8224         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8225         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8226         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8227         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8228                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8229                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8230                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8231                 } else { assert!(false); }
8232         } else { assert!(false); };
8233         // Our local monitor is in-sync and hasn't processed yet timeout
8234         check_added_monitors!(nodes[0], 1);
8235         let events = nodes[0].node.get_and_clear_pending_events();
8236         assert_eq!(events.len(), 1);
8237 }
8238
8239 #[test]
8240 fn test_concurrent_monitor_claim() {
8241         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8242         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8243         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8244         // state N+1 confirms. Alice claims output from state N+1.
8245
8246         let chanmon_cfgs = create_chanmon_cfgs(2);
8247         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8248         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8249         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8250
8251         // Create some initial channel
8252         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8253         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8254
8255         // Rebalance the network to generate htlc in the two directions
8256         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8257
8258         // Route a HTLC from node 0 to node 1 (but don't settle)
8259         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8260
8261         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8262         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8263         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8264         let persister = test_utils::TestPersister::new();
8265         let watchtower_alice = {
8266                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8267                 let monitor = monitors.get(&outpoint).unwrap();
8268                 let mut w = test_utils::TestVecWriter(Vec::new());
8269                 monitor.write(&mut w).unwrap();
8270                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8271                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8272                 assert!(new_monitor == *monitor);
8273                 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);
8274                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8275                 watchtower
8276         };
8277         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8278         watchtower_alice.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8279
8280         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8281         {
8282                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8283                 assert_eq!(txn.len(), 2);
8284                 txn.clear();
8285         }
8286
8287         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8288         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8289         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8290         let persister = test_utils::TestPersister::new();
8291         let watchtower_bob = {
8292                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8293                 let monitor = monitors.get(&outpoint).unwrap();
8294                 let mut w = test_utils::TestVecWriter(Vec::new());
8295                 monitor.write(&mut w).unwrap();
8296                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8297                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8298                 assert!(new_monitor == *monitor);
8299                 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);
8300                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8301                 watchtower
8302         };
8303         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8304         watchtower_bob.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8305
8306         // Route another payment to generate another update with still previous HTLC pending
8307         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8308         {
8309                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8310                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 3000000 , TEST_FINAL_CLTV, &logger).unwrap();
8311                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8312         }
8313         check_added_monitors!(nodes[1], 1);
8314
8315         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8316         assert_eq!(updates.update_add_htlcs.len(), 1);
8317         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8318         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8319                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8320                         // Watchtower Alice should already have seen the block and reject the update
8321                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8322                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8323                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8324                 } else { assert!(false); }
8325         } else { assert!(false); };
8326         // Our local monitor is in-sync and hasn't processed yet timeout
8327         check_added_monitors!(nodes[0], 1);
8328
8329         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8330         watchtower_bob.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8331
8332         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8333         let bob_state_y;
8334         {
8335                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8336                 assert_eq!(txn.len(), 2);
8337                 bob_state_y = txn[0].clone();
8338                 txn.clear();
8339         };
8340
8341         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8342         watchtower_alice.chain_monitor.block_connected(&header, &vec![(0, &bob_state_y)], CHAN_CONFIRM_DEPTH + 2 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8343         {
8344                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8345                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8346                 // the onchain detection of the HTLC output
8347                 assert_eq!(htlc_txn.len(), 2);
8348                 check_spends!(htlc_txn[0], bob_state_y);
8349                 check_spends!(htlc_txn[1], bob_state_y);
8350         }
8351 }
8352
8353 #[test]
8354 fn test_pre_lockin_no_chan_closed_update() {
8355         // Test that if a peer closes a channel in response to a funding_created message we don't
8356         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8357         // message).
8358         //
8359         // Doing so would imply a channel monitor update before the initial channel monitor
8360         // registration, violating our API guarantees.
8361         //
8362         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8363         // then opening a second channel with the same funding output as the first (which is not
8364         // rejected because the first channel does not exist in the ChannelManager) and closing it
8365         // before receiving funding_signed.
8366         let chanmon_cfgs = create_chanmon_cfgs(2);
8367         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8368         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8369         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8370
8371         // Create an initial channel
8372         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8373         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8374         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8375         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8376         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8377
8378         // Move the first channel through the funding flow...
8379         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8380
8381         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8382         check_added_monitors!(nodes[0], 0);
8383
8384         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8385         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8386         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8387         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8388 }
8389
8390 #[test]
8391 fn test_htlc_no_detection() {
8392         // This test is a mutation to underscore the detection logic bug we had
8393         // before #653. HTLC value routed is above the remaining balance, thus
8394         // inverting HTLC and `to_remote` output. HTLC will come second and
8395         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8396         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8397         // outputs order detection for correct spending children filtring.
8398
8399         let chanmon_cfgs = create_chanmon_cfgs(2);
8400         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8401         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8402         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8403
8404         // Create some initial channels
8405         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8406
8407         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000, 1_000_000);
8408         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8409         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8410         assert_eq!(local_txn[0].input.len(), 1);
8411         assert_eq!(local_txn[0].output.len(), 3);
8412         check_spends!(local_txn[0], chan_1.3);
8413
8414         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8415         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8416         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8417         // We deliberately connect the local tx twice as this should provoke a failure calling
8418         // this test before #653 fix.
8419         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &Block { header, txdata: vec![local_txn[0].clone()] }, nodes[0].best_block_info().1 + 1);
8420         check_closed_broadcast!(nodes[0], true);
8421         check_added_monitors!(nodes[0], 1);
8422
8423         let htlc_timeout = {
8424                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8425                 assert_eq!(node_txn[0].input.len(), 1);
8426                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8427                 check_spends!(node_txn[0], local_txn[0]);
8428                 node_txn[0].clone()
8429         };
8430
8431         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8432         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8433         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8434         expect_payment_failed!(nodes[0], our_payment_hash, true);
8435 }
8436
8437 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8438         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8439         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8440         // Carol, Alice would be the upstream node, and Carol the downstream.)
8441         //
8442         // Steps of the test:
8443         // 1) Alice sends a HTLC to Carol through Bob.
8444         // 2) Carol doesn't settle the HTLC.
8445         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8446         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8447         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8448         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8449         // 5) Carol release the preimage to Bob off-chain.
8450         // 6) Bob claims the offered output on the broadcasted commitment.
8451         let chanmon_cfgs = create_chanmon_cfgs(3);
8452         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8453         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8454         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8455
8456         // Create some initial channels
8457         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8458         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8459
8460         // Steps (1) and (2):
8461         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8462         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8463
8464         // Check that Alice's commitment transaction now contains an output for this HTLC.
8465         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8466         check_spends!(alice_txn[0], chan_ab.3);
8467         assert_eq!(alice_txn[0].output.len(), 2);
8468         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8469         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8470         assert_eq!(alice_txn.len(), 2);
8471
8472         // Steps (3) and (4):
8473         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8474         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8475         let mut force_closing_node = 0; // Alice force-closes
8476         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8477         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8478         check_closed_broadcast!(nodes[force_closing_node], true);
8479         check_added_monitors!(nodes[force_closing_node], 1);
8480         if go_onchain_before_fulfill {
8481                 let txn_to_broadcast = match broadcast_alice {
8482                         true => alice_txn.clone(),
8483                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8484                 };
8485                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8486                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8487                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8488                 if broadcast_alice {
8489                         check_closed_broadcast!(nodes[1], true);
8490                         check_added_monitors!(nodes[1], 1);
8491                 }
8492                 assert_eq!(bob_txn.len(), 1);
8493                 check_spends!(bob_txn[0], chan_ab.3);
8494         }
8495
8496         // Step (5):
8497         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8498         // process of removing the HTLC from their commitment transactions.
8499         assert!(nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000));
8500         check_added_monitors!(nodes[2], 1);
8501         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8502         assert!(carol_updates.update_add_htlcs.is_empty());
8503         assert!(carol_updates.update_fail_htlcs.is_empty());
8504         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8505         assert!(carol_updates.update_fee.is_none());
8506         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8507
8508         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8509         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8510         if !go_onchain_before_fulfill && broadcast_alice {
8511                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8512                 assert_eq!(events.len(), 1);
8513                 match events[0] {
8514                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8515                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8516                         },
8517                         _ => panic!("Unexpected event"),
8518                 };
8519         }
8520         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8521         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8522         // Carol<->Bob's updated commitment transaction info.
8523         check_added_monitors!(nodes[1], 2);
8524
8525         let events = nodes[1].node.get_and_clear_pending_msg_events();
8526         assert_eq!(events.len(), 2);
8527         let bob_revocation = match events[0] {
8528                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8529                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8530                         (*msg).clone()
8531                 },
8532                 _ => panic!("Unexpected event"),
8533         };
8534         let bob_updates = match events[1] {
8535                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8536                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8537                         (*updates).clone()
8538                 },
8539                 _ => panic!("Unexpected event"),
8540         };
8541
8542         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8543         check_added_monitors!(nodes[2], 1);
8544         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8545         check_added_monitors!(nodes[2], 1);
8546
8547         let events = nodes[2].node.get_and_clear_pending_msg_events();
8548         assert_eq!(events.len(), 1);
8549         let carol_revocation = match events[0] {
8550                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8551                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8552                         (*msg).clone()
8553                 },
8554                 _ => panic!("Unexpected event"),
8555         };
8556         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8557         check_added_monitors!(nodes[1], 1);
8558
8559         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8560         // here's where we put said channel's commitment tx on-chain.
8561         let mut txn_to_broadcast = alice_txn.clone();
8562         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8563         if !go_onchain_before_fulfill {
8564                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8565                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8566                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8567                 if broadcast_alice {
8568                         check_closed_broadcast!(nodes[1], true);
8569                         check_added_monitors!(nodes[1], 1);
8570                 }
8571                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8572                 if broadcast_alice {
8573                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8574                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8575                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8576                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8577                         // broadcasted.
8578                         assert_eq!(bob_txn.len(), 3);
8579                         check_spends!(bob_txn[1], chan_ab.3);
8580                 } else {
8581                         assert_eq!(bob_txn.len(), 2);
8582                         check_spends!(bob_txn[0], chan_ab.3);
8583                 }
8584         }
8585
8586         // Step (6):
8587         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8588         // broadcasted commitment transaction.
8589         {
8590                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8591                 if go_onchain_before_fulfill {
8592                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8593                         assert_eq!(bob_txn.len(), 2);
8594                 }
8595                 let script_weight = match broadcast_alice {
8596                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8597                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8598                 };
8599                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8600                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8601                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8602                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8603                 if broadcast_alice && !go_onchain_before_fulfill {
8604                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8605                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8606                 } else {
8607                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8608                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8609                 }
8610         }
8611 }
8612
8613 #[test]
8614 fn test_onchain_htlc_settlement_after_close() {
8615         do_test_onchain_htlc_settlement_after_close(true, true);
8616         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8617         do_test_onchain_htlc_settlement_after_close(true, false);
8618         do_test_onchain_htlc_settlement_after_close(false, false);
8619 }
8620
8621 #[test]
8622 fn test_duplicate_chan_id() {
8623         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8624         // already open we reject it and keep the old channel.
8625         //
8626         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8627         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8628         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8629         // updating logic for the existing channel.
8630         let chanmon_cfgs = create_chanmon_cfgs(2);
8631         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8632         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8633         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8634
8635         // Create an initial channel
8636         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8637         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8638         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8639         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()));
8640
8641         // Try to create a second channel with the same temporary_channel_id as the first and check
8642         // that it is rejected.
8643         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8644         {
8645                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8646                 assert_eq!(events.len(), 1);
8647                 match events[0] {
8648                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8649                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8650                                 // first (valid) and second (invalid) channels are closed, given they both have
8651                                 // the same non-temporary channel_id. However, currently we do not, so we just
8652                                 // move forward with it.
8653                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8654                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8655                         },
8656                         _ => panic!("Unexpected event"),
8657                 }
8658         }
8659
8660         // Move the first channel through the funding flow...
8661         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8662
8663         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8664         check_added_monitors!(nodes[0], 0);
8665
8666         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8667         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8668         {
8669                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8670                 assert_eq!(added_monitors.len(), 1);
8671                 assert_eq!(added_monitors[0].0, funding_output);
8672                 added_monitors.clear();
8673         }
8674         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8675
8676         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8677         let channel_id = funding_outpoint.to_channel_id();
8678
8679         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8680         // temporary one).
8681
8682         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8683         // Technically this is allowed by the spec, but we don't support it and there's little reason
8684         // to. Still, it shouldn't cause any other issues.
8685         open_chan_msg.temporary_channel_id = channel_id;
8686         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8687         {
8688                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8689                 assert_eq!(events.len(), 1);
8690                 match events[0] {
8691                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8692                                 // Technically, at this point, nodes[1] would be justified in thinking both
8693                                 // channels are closed, but currently we do not, so we just move forward with it.
8694                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8695                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8696                         },
8697                         _ => panic!("Unexpected event"),
8698                 }
8699         }
8700
8701         // Now try to create a second channel which has a duplicate funding output.
8702         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8703         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8704         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8705         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()));
8706         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8707
8708         let funding_created = {
8709                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8710                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8711                 let logger = test_utils::TestLogger::new();
8712                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8713         };
8714         check_added_monitors!(nodes[0], 0);
8715         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8716         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8717         // still needs to be cleared here.
8718         check_added_monitors!(nodes[1], 1);
8719
8720         // ...still, nodes[1] will reject the duplicate channel.
8721         {
8722                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8723                 assert_eq!(events.len(), 1);
8724                 match events[0] {
8725                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8726                                 // Technically, at this point, nodes[1] would be justified in thinking both
8727                                 // channels are closed, but currently we do not, so we just move forward with it.
8728                                 assert_eq!(msg.channel_id, channel_id);
8729                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8730                         },
8731                         _ => panic!("Unexpected event"),
8732                 }
8733         }
8734
8735         // finally, finish creating the original channel and send a payment over it to make sure
8736         // everything is functional.
8737         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8738         {
8739                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8740                 assert_eq!(added_monitors.len(), 1);
8741                 assert_eq!(added_monitors[0].0, funding_output);
8742                 added_monitors.clear();
8743         }
8744
8745         let events_4 = nodes[0].node.get_and_clear_pending_events();
8746         assert_eq!(events_4.len(), 0);
8747         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8748         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
8749
8750         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8751         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8752         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8753         send_payment(&nodes[0], &[&nodes[1]], 8000000, 8_000_000);
8754 }
8755
8756 #[test]
8757 fn test_error_chans_closed() {
8758         // Test that we properly handle error messages, closing appropriate channels.
8759         //
8760         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8761         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8762         // we can test various edge cases around it to ensure we don't regress.
8763         let chanmon_cfgs = create_chanmon_cfgs(3);
8764         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8765         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8766         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8767
8768         // Create some initial channels
8769         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8770         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8771         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8772
8773         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8774         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8775         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8776
8777         // Closing a channel from a different peer has no effect
8778         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8779         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8780
8781         // Closing one channel doesn't impact others
8782         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8783         check_added_monitors!(nodes[0], 1);
8784         check_closed_broadcast!(nodes[0], false);
8785         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8786         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8787         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);
8788         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);
8789
8790         // A null channel ID should close all channels
8791         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8792         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8793         check_added_monitors!(nodes[0], 2);
8794         let events = nodes[0].node.get_and_clear_pending_msg_events();
8795         assert_eq!(events.len(), 2);
8796         match events[0] {
8797                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8798                         assert_eq!(msg.contents.flags & 2, 2);
8799                 },
8800                 _ => panic!("Unexpected event"),
8801         }
8802         match events[1] {
8803                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8804                         assert_eq!(msg.contents.flags & 2, 2);
8805                 },
8806                 _ => panic!("Unexpected event"),
8807         }
8808         // Note that at this point users of a standard PeerHandler will end up calling
8809         // peer_disconnected with no_connection_possible set to false, duplicating the
8810         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8811         // users with their own peer handling logic. We duplicate the call here, however.
8812         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8813         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8814
8815         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8816         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8817         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8818 }