]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/functional_tests.rs
Merge pull request #1045 from TheBlueMatt/2021-08-chanmon-ser-upgradability
[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::{Confirm, Listen, 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::{PaymentPreimage, PaymentSecret, PaymentHash};
21 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA};
23 use ln::channel::{Channel, ChannelError};
24 use ln::{chan_utils, onion_utils};
25 use ln::chan_utils::HTLC_SUCCESS_TX_WEIGHT;
26 use routing::router::{Route, RouteHop, RouteHint, RouteHintHop, get_route, get_keysend_route};
27 use routing::network_graph::RoutingFees;
28 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
29 use ln::msgs;
30 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
31 use ln::script::ShutdownScript;
32 use util::enforcing_trait_impls::EnforcingSigner;
33 use util::{byte_utils, test_utils};
34 use util::test_utils::OnGetShutdownScriptpubkey;
35 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose};
36 use util::errors::APIError;
37 use util::ser::{Writeable, ReadableArgs};
38 use util::config::UserConfig;
39
40 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
41 use bitcoin::hash_types::{Txid, BlockHash};
42 use bitcoin::blockdata::block::{Block, BlockHeader};
43 use bitcoin::blockdata::script::Builder;
44 use bitcoin::blockdata::opcodes;
45 use bitcoin::blockdata::constants::genesis_block;
46 use bitcoin::network::constants::Network;
47
48 use bitcoin::hashes::sha256::Hash as Sha256;
49 use bitcoin::hashes::Hash;
50
51 use bitcoin::secp256k1::{Secp256k1, Message};
52 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
53
54 use regex;
55
56 use io;
57 use prelude::*;
58 use alloc::collections::BTreeSet;
59 use core::default::Default;
60 use core::num::NonZeroU8;
61 use sync::{Arc, Mutex};
62
63 use ln::functional_test_utils::*;
64 use ln::chan_utils::CommitmentTransaction;
65 use ln::msgs::OptionalField::Present;
66
67 #[test]
68 fn test_insane_channel_opens() {
69         // Stand up a network of 2 nodes
70         let chanmon_cfgs = create_chanmon_cfgs(2);
71         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
73         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
74
75         // Instantiate channel parameters where we push the maximum msats given our
76         // funding satoshis
77         let channel_value_sat = 31337; // same as funding satoshis
78         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
79         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
80
81         // Have node0 initiate a channel to node1 with aforementioned parameters
82         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
83
84         // Extract the channel open message from node0 to node1
85         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
86
87         // Test helper that asserts we get the correct error string given a mutator
88         // that supposedly makes the channel open message insane
89         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
90                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
91                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
92                 assert_eq!(msg_events.len(), 1);
93                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
94                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
95                         match action {
96                                 &ErrorAction::SendErrorMessage { .. } => {
97                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
98                                 },
99                                 _ => panic!("unexpected event!"),
100                         }
101                 } else { assert!(false); }
102         };
103
104         use ln::channel::MAX_FUNDING_SATOSHIS;
105         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
106
107         // Test all mutations that would make the channel open message insane
108         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 });
109
110         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
111
112         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 });
113
114         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
115
116         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 });
117
118         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 });
119
120         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 });
121
122         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
123
124         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
125 }
126
127 #[test]
128 fn test_async_inbound_update_fee() {
129         let chanmon_cfgs = create_chanmon_cfgs(2);
130         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
131         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
132         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
133         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
134         let logger = test_utils::TestLogger::new();
135
136         // balancing
137         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
138
139         // A                                        B
140         // update_fee                            ->
141         // send (1) commitment_signed            -.
142         //                                       <- update_add_htlc/commitment_signed
143         // send (2) RAA (awaiting remote revoke) -.
144         // (1) commitment_signed is delivered    ->
145         //                                       .- send (3) RAA (awaiting remote revoke)
146         // (2) RAA is delivered                  ->
147         //                                       .- send (4) commitment_signed
148         //                                       <- (3) RAA is delivered
149         // send (5) commitment_signed            -.
150         //                                       <- (4) commitment_signed is delivered
151         // send (6) RAA                          -.
152         // (5) commitment_signed is delivered    ->
153         //                                       <- RAA
154         // (6) RAA is delivered                  ->
155
156         // First nodes[0] generates an update_fee
157         {
158                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
159                 *feerate_lock += 20;
160         }
161         nodes[0].node.timer_tick_occurred();
162         check_added_monitors!(nodes[0], 1);
163
164         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
165         assert_eq!(events_0.len(), 1);
166         let (update_msg, commitment_signed) = match events_0[0] { // (1)
167                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
168                         (update_fee.as_ref(), commitment_signed)
169                 },
170                 _ => panic!("Unexpected event"),
171         };
172
173         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
174
175         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
176         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[0]);
177         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
178         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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &Some(our_payment_secret)).unwrap();
179         check_added_monitors!(nodes[1], 1);
180
181         let payment_event = {
182                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
183                 assert_eq!(events_1.len(), 1);
184                 SendEvent::from_event(events_1.remove(0))
185         };
186         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
187         assert_eq!(payment_event.msgs.len(), 1);
188
189         // ...now when the messages get delivered everyone should be happy
190         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
191         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
192         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
193         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
194         check_added_monitors!(nodes[0], 1);
195
196         // deliver(1), generate (3):
197         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
198         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
199         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
200         check_added_monitors!(nodes[1], 1);
201
202         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
203         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
204         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
205         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
206         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
207         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
208         assert!(bs_update.update_fee.is_none()); // (4)
209         check_added_monitors!(nodes[1], 1);
210
211         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
212         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
213         assert!(as_update.update_add_htlcs.is_empty()); // (5)
214         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
215         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
216         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
217         assert!(as_update.update_fee.is_none()); // (5)
218         check_added_monitors!(nodes[0], 1);
219
220         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
221         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
222         // only (6) so get_event_msg's assert(len == 1) passes
223         check_added_monitors!(nodes[0], 1);
224
225         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
226         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
227         check_added_monitors!(nodes[1], 1);
228
229         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
230         check_added_monitors!(nodes[0], 1);
231
232         let events_2 = nodes[0].node.get_and_clear_pending_events();
233         assert_eq!(events_2.len(), 1);
234         match events_2[0] {
235                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
236                 _ => panic!("Unexpected event"),
237         }
238
239         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
240         check_added_monitors!(nodes[1], 1);
241 }
242
243 #[test]
244 fn test_update_fee_unordered_raa() {
245         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
246         // crash in an earlier version of the update_fee patch)
247         let chanmon_cfgs = create_chanmon_cfgs(2);
248         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
249         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
250         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
251         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
252         let logger = test_utils::TestLogger::new();
253
254         // balancing
255         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
256
257         // First nodes[0] generates an update_fee
258         {
259                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
260                 *feerate_lock += 20;
261         }
262         nodes[0].node.timer_tick_occurred();
263         check_added_monitors!(nodes[0], 1);
264
265         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
266         assert_eq!(events_0.len(), 1);
267         let update_msg = match events_0[0] { // (1)
268                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
269                         update_fee.as_ref()
270                 },
271                 _ => panic!("Unexpected event"),
272         };
273
274         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
275
276         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
277         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[0]);
278         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
279         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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &Some(our_payment_secret)).unwrap();
280         check_added_monitors!(nodes[1], 1);
281
282         let payment_event = {
283                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
284                 assert_eq!(events_1.len(), 1);
285                 SendEvent::from_event(events_1.remove(0))
286         };
287         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
288         assert_eq!(payment_event.msgs.len(), 1);
289
290         // ...now when the messages get delivered everyone should be happy
291         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
292         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
293         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
294         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
295         check_added_monitors!(nodes[0], 1);
296
297         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
298         check_added_monitors!(nodes[1], 1);
299
300         // We can't continue, sadly, because our (1) now has a bogus signature
301 }
302
303 #[test]
304 fn test_multi_flight_update_fee() {
305         let chanmon_cfgs = create_chanmon_cfgs(2);
306         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
307         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
308         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
309         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
310
311         // A                                        B
312         // update_fee/commitment_signed          ->
313         //                                       .- send (1) RAA and (2) commitment_signed
314         // update_fee (never committed)          ->
315         // (3) update_fee                        ->
316         // We have to manually generate the above update_fee, it is allowed by the protocol but we
317         // don't track which updates correspond to which revoke_and_ack responses so we're in
318         // AwaitingRAA mode and will not generate the update_fee yet.
319         //                                       <- (1) RAA delivered
320         // (3) is generated and send (4) CS      -.
321         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
322         // know the per_commitment_point to use for it.
323         //                                       <- (2) commitment_signed delivered
324         // revoke_and_ack                        ->
325         //                                          B should send no response here
326         // (4) commitment_signed delivered       ->
327         //                                       <- RAA/commitment_signed delivered
328         // revoke_and_ack                        ->
329
330         // First nodes[0] generates an update_fee
331         let initial_feerate;
332         {
333                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
334                 initial_feerate = *feerate_lock;
335                 *feerate_lock = initial_feerate + 20;
336         }
337         nodes[0].node.timer_tick_occurred();
338         check_added_monitors!(nodes[0], 1);
339
340         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
341         assert_eq!(events_0.len(), 1);
342         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
343                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
344                         (update_fee.as_ref().unwrap(), commitment_signed)
345                 },
346                 _ => panic!("Unexpected event"),
347         };
348
349         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
350         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
351         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
352         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
353         check_added_monitors!(nodes[1], 1);
354
355         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
356         // transaction:
357         {
358                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
359                 *feerate_lock = initial_feerate + 40;
360         }
361         nodes[0].node.timer_tick_occurred();
362         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
363         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
364
365         // Create the (3) update_fee message that nodes[0] will generate before it does...
366         let mut update_msg_2 = msgs::UpdateFee {
367                 channel_id: update_msg_1.channel_id.clone(),
368                 feerate_per_kw: (initial_feerate + 30) as u32,
369         };
370
371         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
372
373         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
374         // Deliver (3)
375         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
376
377         // Deliver (1), generating (3) and (4)
378         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
379         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
380         check_added_monitors!(nodes[0], 1);
381         assert!(as_second_update.update_add_htlcs.is_empty());
382         assert!(as_second_update.update_fulfill_htlcs.is_empty());
383         assert!(as_second_update.update_fail_htlcs.is_empty());
384         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
385         // Check that the update_fee newly generated matches what we delivered:
386         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
387         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
388
389         // Deliver (2) commitment_signed
390         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
391         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
392         check_added_monitors!(nodes[0], 1);
393         // No commitment_signed so get_event_msg's assert(len == 1) passes
394
395         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
396         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
397         check_added_monitors!(nodes[1], 1);
398
399         // Delever (4)
400         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
401         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
402         check_added_monitors!(nodes[1], 1);
403
404         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
405         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
406         check_added_monitors!(nodes[0], 1);
407
408         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
409         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
410         // No commitment_signed so get_event_msg's assert(len == 1) passes
411         check_added_monitors!(nodes[0], 1);
412
413         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
414         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
415         check_added_monitors!(nodes[1], 1);
416 }
417
418 fn do_test_1_conf_open(connect_style: ConnectStyle) {
419         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
420         // tests that we properly send one in that case.
421         let mut alice_config = UserConfig::default();
422         alice_config.own_channel_config.minimum_depth = 1;
423         alice_config.channel_options.announced_channel = true;
424         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
425         let mut bob_config = UserConfig::default();
426         bob_config.own_channel_config.minimum_depth = 1;
427         bob_config.channel_options.announced_channel = true;
428         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
429         let chanmon_cfgs = create_chanmon_cfgs(2);
430         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
431         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
432         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
433         *nodes[0].connect_style.borrow_mut() = connect_style;
434
435         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
436         mine_transaction(&nodes[1], &tx);
437         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()));
438
439         mine_transaction(&nodes[0], &tx);
440         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
441         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
442
443         for node in nodes {
444                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
445                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
446                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
447         }
448 }
449 #[test]
450 fn test_1_conf_open() {
451         do_test_1_conf_open(ConnectStyle::BestBlockFirst);
452         do_test_1_conf_open(ConnectStyle::TransactionsFirst);
453         do_test_1_conf_open(ConnectStyle::FullBlockViaListen);
454 }
455
456 fn do_test_sanity_on_in_flight_opens(steps: u8) {
457         // Previously, we had issues deserializing channels when we hadn't connected the first block
458         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
459         // serialization round-trips and simply do steps towards opening a channel and then drop the
460         // Node objects.
461
462         let chanmon_cfgs = create_chanmon_cfgs(2);
463         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
464         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
465         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
466
467         if steps & 0b1000_0000 != 0{
468                 let block = Block {
469                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
470                         txdata: vec![],
471                 };
472                 connect_block(&nodes[0], &block);
473                 connect_block(&nodes[1], &block);
474         }
475
476         if steps & 0x0f == 0 { return; }
477         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
478         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
479
480         if steps & 0x0f == 1 { return; }
481         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
482         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
483
484         if steps & 0x0f == 2 { return; }
485         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
486
487         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
488
489         if steps & 0x0f == 3 { return; }
490         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
491         check_added_monitors!(nodes[0], 0);
492         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
493
494         if steps & 0x0f == 4 { return; }
495         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
496         {
497                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
498                 assert_eq!(added_monitors.len(), 1);
499                 assert_eq!(added_monitors[0].0, funding_output);
500                 added_monitors.clear();
501         }
502         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
503
504         if steps & 0x0f == 5 { return; }
505         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
506         {
507                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
508                 assert_eq!(added_monitors.len(), 1);
509                 assert_eq!(added_monitors[0].0, funding_output);
510                 added_monitors.clear();
511         }
512
513         let events_4 = nodes[0].node.get_and_clear_pending_events();
514         assert_eq!(events_4.len(), 0);
515
516         if steps & 0x0f == 6 { return; }
517         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
518
519         if steps & 0x0f == 7 { return; }
520         confirm_transaction_at(&nodes[0], &tx, 2);
521         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
522         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
523 }
524
525 #[test]
526 fn test_sanity_on_in_flight_opens() {
527         do_test_sanity_on_in_flight_opens(0);
528         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
529         do_test_sanity_on_in_flight_opens(1);
530         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
531         do_test_sanity_on_in_flight_opens(2);
532         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
533         do_test_sanity_on_in_flight_opens(3);
534         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
535         do_test_sanity_on_in_flight_opens(4);
536         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
537         do_test_sanity_on_in_flight_opens(5);
538         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
539         do_test_sanity_on_in_flight_opens(6);
540         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
541         do_test_sanity_on_in_flight_opens(7);
542         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
543         do_test_sanity_on_in_flight_opens(8);
544         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
545 }
546
547 #[test]
548 fn test_update_fee_vanilla() {
549         let chanmon_cfgs = create_chanmon_cfgs(2);
550         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
551         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
552         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
553         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
554
555         {
556                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
557                 *feerate_lock += 25;
558         }
559         nodes[0].node.timer_tick_occurred();
560         check_added_monitors!(nodes[0], 1);
561
562         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
563         assert_eq!(events_0.len(), 1);
564         let (update_msg, commitment_signed) = match events_0[0] {
565                         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 } } => {
566                         (update_fee.as_ref(), commitment_signed)
567                 },
568                 _ => panic!("Unexpected event"),
569         };
570         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
571
572         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
573         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
574         check_added_monitors!(nodes[1], 1);
575
576         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
577         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
578         check_added_monitors!(nodes[0], 1);
579
580         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
581         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
582         // No commitment_signed so get_event_msg's assert(len == 1) passes
583         check_added_monitors!(nodes[0], 1);
584
585         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
586         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
587         check_added_monitors!(nodes[1], 1);
588 }
589
590 #[test]
591 fn test_update_fee_that_funder_cannot_afford() {
592         let chanmon_cfgs = create_chanmon_cfgs(2);
593         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
594         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
595         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
596         let channel_value = 1888;
597         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
598         let channel_id = chan.2;
599
600         let feerate = 260;
601         {
602                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
603                 *feerate_lock = feerate;
604         }
605         nodes[0].node.timer_tick_occurred();
606         check_added_monitors!(nodes[0], 1);
607         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
608
609         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
610
611         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
612
613         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
614         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
615         {
616                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
617
618                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
619                 let num_htlcs = commitment_tx.output.len() - 2;
620                 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
621                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
622                 actual_fee = channel_value - actual_fee;
623                 assert_eq!(total_fee, actual_fee);
624         }
625
626         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
627         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
628         {
629                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
630                 *feerate_lock = feerate + 2;
631         }
632         nodes[0].node.timer_tick_occurred();
633         check_added_monitors!(nodes[0], 1);
634
635         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
636
637         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
638
639         //While producing the commitment_signed response after handling a received update_fee request the
640         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
641         //Should produce and error.
642         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
643         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
644         check_added_monitors!(nodes[1], 1);
645         check_closed_broadcast!(nodes[1], true);
646 }
647
648 #[test]
649 fn test_update_fee_with_fundee_update_add_htlc() {
650         let chanmon_cfgs = create_chanmon_cfgs(2);
651         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
652         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
653         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
654         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
655         let logger = test_utils::TestLogger::new();
656
657         // balancing
658         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
659
660         {
661                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
662                 *feerate_lock += 20;
663         }
664         nodes[0].node.timer_tick_occurred();
665         check_added_monitors!(nodes[0], 1);
666
667         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
668         assert_eq!(events_0.len(), 1);
669         let (update_msg, commitment_signed) = match events_0[0] {
670                         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 } } => {
671                         (update_fee.as_ref(), commitment_signed)
672                 },
673                 _ => panic!("Unexpected event"),
674         };
675         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
676         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
677         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
678         check_added_monitors!(nodes[1], 1);
679
680         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[0]);
681         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
682         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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 800000, TEST_FINAL_CLTV, &logger).unwrap();
683
684         // nothing happens since node[1] is in AwaitingRemoteRevoke
685         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
686         {
687                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
688                 assert_eq!(added_monitors.len(), 0);
689                 added_monitors.clear();
690         }
691         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
692         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
693         // node[1] has nothing to do
694
695         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
696         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
697         check_added_monitors!(nodes[0], 1);
698
699         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
700         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
701         // No commitment_signed so get_event_msg's assert(len == 1) passes
702         check_added_monitors!(nodes[0], 1);
703         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
704         check_added_monitors!(nodes[1], 1);
705         // AwaitingRemoteRevoke ends here
706
707         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
708         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
709         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
710         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
711         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
712         assert_eq!(commitment_update.update_fee.is_none(), true);
713
714         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
715         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
716         check_added_monitors!(nodes[0], 1);
717         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
718
719         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
720         check_added_monitors!(nodes[1], 1);
721         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
722
723         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
724         check_added_monitors!(nodes[1], 1);
725         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
726         // No commitment_signed so get_event_msg's assert(len == 1) passes
727
728         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
729         check_added_monitors!(nodes[0], 1);
730         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
731
732         expect_pending_htlcs_forwardable!(nodes[0]);
733
734         let events = nodes[0].node.get_and_clear_pending_events();
735         assert_eq!(events.len(), 1);
736         match events[0] {
737                 Event::PaymentReceived { .. } => { },
738                 _ => panic!("Unexpected event"),
739         };
740
741         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
742
743         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
744         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
745         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
746 }
747
748 #[test]
749 fn test_update_fee() {
750         let chanmon_cfgs = create_chanmon_cfgs(2);
751         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
752         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
753         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
754         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
755         let channel_id = chan.2;
756
757         // A                                        B
758         // (1) update_fee/commitment_signed      ->
759         //                                       <- (2) revoke_and_ack
760         //                                       .- send (3) commitment_signed
761         // (4) update_fee/commitment_signed      ->
762         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
763         //                                       <- (3) commitment_signed delivered
764         // send (6) revoke_and_ack               -.
765         //                                       <- (5) deliver revoke_and_ack
766         // (6) deliver revoke_and_ack            ->
767         //                                       .- send (7) commitment_signed in response to (4)
768         //                                       <- (7) deliver commitment_signed
769         // revoke_and_ack                        ->
770
771         // Create and deliver (1)...
772         let feerate;
773         {
774                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
775                 feerate = *feerate_lock;
776                 *feerate_lock = feerate + 20;
777         }
778         nodes[0].node.timer_tick_occurred();
779         check_added_monitors!(nodes[0], 1);
780
781         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
782         assert_eq!(events_0.len(), 1);
783         let (update_msg, commitment_signed) = match events_0[0] {
784                         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 } } => {
785                         (update_fee.as_ref(), commitment_signed)
786                 },
787                 _ => panic!("Unexpected event"),
788         };
789         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
790
791         // Generate (2) and (3):
792         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
793         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
794         check_added_monitors!(nodes[1], 1);
795
796         // Deliver (2):
797         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
798         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
799         check_added_monitors!(nodes[0], 1);
800
801         // Create and deliver (4)...
802         {
803                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
804                 *feerate_lock = feerate + 30;
805         }
806         nodes[0].node.timer_tick_occurred();
807         check_added_monitors!(nodes[0], 1);
808         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
809         assert_eq!(events_0.len(), 1);
810         let (update_msg, commitment_signed) = match events_0[0] {
811                         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 } } => {
812                         (update_fee.as_ref(), commitment_signed)
813                 },
814                 _ => panic!("Unexpected event"),
815         };
816
817         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
818         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
819         check_added_monitors!(nodes[1], 1);
820         // ... creating (5)
821         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
822         // No commitment_signed so get_event_msg's assert(len == 1) passes
823
824         // Handle (3), creating (6):
825         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
826         check_added_monitors!(nodes[0], 1);
827         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
828         // No commitment_signed so get_event_msg's assert(len == 1) passes
829
830         // Deliver (5):
831         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
832         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
833         check_added_monitors!(nodes[0], 1);
834
835         // Deliver (6), creating (7):
836         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
837         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
838         assert!(commitment_update.update_add_htlcs.is_empty());
839         assert!(commitment_update.update_fulfill_htlcs.is_empty());
840         assert!(commitment_update.update_fail_htlcs.is_empty());
841         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
842         assert!(commitment_update.update_fee.is_none());
843         check_added_monitors!(nodes[1], 1);
844
845         // Deliver (7)
846         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
847         check_added_monitors!(nodes[0], 1);
848         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
849         // No commitment_signed so get_event_msg's assert(len == 1) passes
850
851         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
852         check_added_monitors!(nodes[1], 1);
853         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
854
855         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
856         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
857         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
858 }
859
860 #[test]
861 fn pre_funding_lock_shutdown_test() {
862         // Test sending a shutdown prior to funding_locked after funding generation
863         let chanmon_cfgs = create_chanmon_cfgs(2);
864         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
865         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
866         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
867         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
868         mine_transaction(&nodes[0], &tx);
869         mine_transaction(&nodes[1], &tx);
870
871         nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
872         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
873         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
874         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
875         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
876
877         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
878         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
879         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
880         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
881         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
882         assert!(node_0_none.is_none());
883
884         assert!(nodes[0].node.list_channels().is_empty());
885         assert!(nodes[1].node.list_channels().is_empty());
886 }
887
888 #[test]
889 fn updates_shutdown_wait() {
890         // Test sending a shutdown with outstanding updates pending
891         let chanmon_cfgs = create_chanmon_cfgs(3);
892         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
893         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
894         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
895         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
896         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
897         let logger = test_utils::TestLogger::new();
898
899         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
900
901         nodes[0].node.close_channel(&chan_1.2).unwrap();
902         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
903         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
904         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
905         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
906
907         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
908         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
909
910         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[0]);
911
912         let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
913         let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
914         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(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
915         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(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
916         unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable {..}, {});
917         unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable {..}, {});
918
919         assert!(nodes[2].node.claim_funds(our_payment_preimage));
920         check_added_monitors!(nodes[2], 1);
921         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
922         assert!(updates.update_add_htlcs.is_empty());
923         assert!(updates.update_fail_htlcs.is_empty());
924         assert!(updates.update_fail_malformed_htlcs.is_empty());
925         assert!(updates.update_fee.is_none());
926         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
927         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
928         expect_payment_forwarded!(nodes[1], Some(1000), false);
929         check_added_monitors!(nodes[1], 1);
930         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
931         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
932
933         assert!(updates_2.update_add_htlcs.is_empty());
934         assert!(updates_2.update_fail_htlcs.is_empty());
935         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
936         assert!(updates_2.update_fee.is_none());
937         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
938         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
939         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
940
941         let events = nodes[0].node.get_and_clear_pending_events();
942         assert_eq!(events.len(), 1);
943         match events[0] {
944                 Event::PaymentSent { ref payment_preimage } => {
945                         assert_eq!(our_payment_preimage, *payment_preimage);
946                 },
947                 _ => panic!("Unexpected event"),
948         }
949
950         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
951         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
952         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
953         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
954         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
955         assert!(node_0_none.is_none());
956
957         assert!(nodes[0].node.list_channels().is_empty());
958
959         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
960         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
961         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
962         assert!(nodes[1].node.list_channels().is_empty());
963         assert!(nodes[2].node.list_channels().is_empty());
964 }
965
966 #[test]
967 fn htlc_fail_async_shutdown() {
968         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
969         let chanmon_cfgs = create_chanmon_cfgs(3);
970         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
971         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
972         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
973         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
974         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
975         let logger = test_utils::TestLogger::new();
976
977         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
978         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
979         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(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
980         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
981         check_added_monitors!(nodes[0], 1);
982         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
983         assert_eq!(updates.update_add_htlcs.len(), 1);
984         assert!(updates.update_fulfill_htlcs.is_empty());
985         assert!(updates.update_fail_htlcs.is_empty());
986         assert!(updates.update_fail_malformed_htlcs.is_empty());
987         assert!(updates.update_fee.is_none());
988
989         nodes[1].node.close_channel(&chan_1.2).unwrap();
990         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
991         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
992         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
993
994         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
995         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
996         check_added_monitors!(nodes[1], 1);
997         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
998         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
999
1000         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1001         assert!(updates_2.update_add_htlcs.is_empty());
1002         assert!(updates_2.update_fulfill_htlcs.is_empty());
1003         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
1004         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1005         assert!(updates_2.update_fee.is_none());
1006
1007         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
1008         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1009
1010         expect_payment_failed!(nodes[0], our_payment_hash, false);
1011
1012         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1013         assert_eq!(msg_events.len(), 2);
1014         let node_0_closing_signed = match msg_events[0] {
1015                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1016                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
1017                         (*msg).clone()
1018                 },
1019                 _ => panic!("Unexpected event"),
1020         };
1021         match msg_events[1] {
1022                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1023                         assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
1024                 },
1025                 _ => panic!("Unexpected event"),
1026         }
1027
1028         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1029         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1030         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1031         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1032         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1033         assert!(node_0_none.is_none());
1034
1035         assert!(nodes[0].node.list_channels().is_empty());
1036
1037         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1038         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1039         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1040         assert!(nodes[1].node.list_channels().is_empty());
1041         assert!(nodes[2].node.list_channels().is_empty());
1042 }
1043
1044 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1045         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1046         // messages delivered prior to disconnect
1047         let chanmon_cfgs = create_chanmon_cfgs(3);
1048         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1049         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1050         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1051         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1052         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1053
1054         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1055
1056         nodes[1].node.close_channel(&chan_1.2).unwrap();
1057         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1058         if recv_count > 0 {
1059                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
1060                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1061                 if recv_count > 1 {
1062                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
1063                 }
1064         }
1065
1066         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1067         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1068
1069         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1070         let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1071         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1072         let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1073
1074         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1075         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1076         assert!(node_1_shutdown == node_1_2nd_shutdown);
1077
1078         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1079         let node_0_2nd_shutdown = if recv_count > 0 {
1080                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1081                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1082                 node_0_2nd_shutdown
1083         } else {
1084                 let node_0_chan_update = get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
1085                 assert_eq!(node_0_chan_update.contents.flags & 2, 0); // "disabled" flag must not be set as we just reconnected.
1086                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1087                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1088         };
1089         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_2nd_shutdown);
1090
1091         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1092         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1093
1094         assert!(nodes[2].node.claim_funds(our_payment_preimage));
1095         check_added_monitors!(nodes[2], 1);
1096         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1097         assert!(updates.update_add_htlcs.is_empty());
1098         assert!(updates.update_fail_htlcs.is_empty());
1099         assert!(updates.update_fail_malformed_htlcs.is_empty());
1100         assert!(updates.update_fee.is_none());
1101         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1102         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1103         expect_payment_forwarded!(nodes[1], Some(1000), false);
1104         check_added_monitors!(nodes[1], 1);
1105         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1106         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1107
1108         assert!(updates_2.update_add_htlcs.is_empty());
1109         assert!(updates_2.update_fail_htlcs.is_empty());
1110         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1111         assert!(updates_2.update_fee.is_none());
1112         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1113         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1114         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1115
1116         let events = nodes[0].node.get_and_clear_pending_events();
1117         assert_eq!(events.len(), 1);
1118         match events[0] {
1119                 Event::PaymentSent { ref payment_preimage } => {
1120                         assert_eq!(our_payment_preimage, *payment_preimage);
1121                 },
1122                 _ => panic!("Unexpected event"),
1123         }
1124
1125         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1126         if recv_count > 0 {
1127                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1128                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1129                 assert!(node_1_closing_signed.is_some());
1130         }
1131
1132         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1133         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1134
1135         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1136         let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1137         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1138         if recv_count == 0 {
1139                 // If all closing_signeds weren't delivered we can just resume where we left off...
1140                 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1141
1142                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1143                 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1144                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1145
1146                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1147                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1148                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1149
1150                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_3rd_shutdown);
1151                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1152
1153                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_3rd_shutdown);
1154                 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1155                 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1156
1157                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1158                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1159                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1160                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1161                 assert!(node_0_none.is_none());
1162         } else {
1163                 // If one node, however, received + responded with an identical closing_signed we end
1164                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1165                 // There isn't really anything better we can do simply, but in the future we might
1166                 // explore storing a set of recently-closed channels that got disconnected during
1167                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1168                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1169                 // transaction.
1170                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1171
1172                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1173                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1174                 assert_eq!(msg_events.len(), 1);
1175                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1176                         match action {
1177                                 &ErrorAction::SendErrorMessage { ref msg } => {
1178                                         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1179                                         assert_eq!(msg.channel_id, chan_1.2);
1180                                 },
1181                                 _ => panic!("Unexpected event!"),
1182                         }
1183                 } else { panic!("Needed SendErrorMessage close"); }
1184
1185                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1186                 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1187                 // closing_signed so we do it ourselves
1188                 check_closed_broadcast!(nodes[0], false);
1189                 check_added_monitors!(nodes[0], 1);
1190         }
1191
1192         assert!(nodes[0].node.list_channels().is_empty());
1193
1194         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1195         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1196         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1197         assert!(nodes[1].node.list_channels().is_empty());
1198         assert!(nodes[2].node.list_channels().is_empty());
1199 }
1200
1201 #[test]
1202 fn test_shutdown_rebroadcast() {
1203         do_test_shutdown_rebroadcast(0);
1204         do_test_shutdown_rebroadcast(1);
1205         do_test_shutdown_rebroadcast(2);
1206 }
1207
1208 #[test]
1209 fn fake_network_test() {
1210         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1211         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1212         let chanmon_cfgs = create_chanmon_cfgs(4);
1213         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1214         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1215         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1216
1217         // Create some initial channels
1218         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1219         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1220         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1221
1222         // Rebalance the network a bit by relaying one payment through all the channels...
1223         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1224         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1225         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1226         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1227
1228         // Send some more payments
1229         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1230         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1231         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1232
1233         // Test failure packets
1234         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1235         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1236
1237         // Add a new channel that skips 3
1238         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1239
1240         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1241         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1242         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1243         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1244         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1245         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1246         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1247
1248         // Do some rebalance loop payments, simultaneously
1249         let mut hops = Vec::with_capacity(3);
1250         hops.push(RouteHop {
1251                 pubkey: nodes[2].node.get_our_node_id(),
1252                 node_features: NodeFeatures::empty(),
1253                 short_channel_id: chan_2.0.contents.short_channel_id,
1254                 channel_features: ChannelFeatures::empty(),
1255                 fee_msat: 0,
1256                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1257         });
1258         hops.push(RouteHop {
1259                 pubkey: nodes[3].node.get_our_node_id(),
1260                 node_features: NodeFeatures::empty(),
1261                 short_channel_id: chan_3.0.contents.short_channel_id,
1262                 channel_features: ChannelFeatures::empty(),
1263                 fee_msat: 0,
1264                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1265         });
1266         hops.push(RouteHop {
1267                 pubkey: nodes[1].node.get_our_node_id(),
1268                 node_features: NodeFeatures::known(),
1269                 short_channel_id: chan_4.0.contents.short_channel_id,
1270                 channel_features: ChannelFeatures::known(),
1271                 fee_msat: 1000000,
1272                 cltv_expiry_delta: TEST_FINAL_CLTV,
1273         });
1274         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;
1275         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;
1276         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1277
1278         let mut hops = Vec::with_capacity(3);
1279         hops.push(RouteHop {
1280                 pubkey: nodes[3].node.get_our_node_id(),
1281                 node_features: NodeFeatures::empty(),
1282                 short_channel_id: chan_4.0.contents.short_channel_id,
1283                 channel_features: ChannelFeatures::empty(),
1284                 fee_msat: 0,
1285                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1286         });
1287         hops.push(RouteHop {
1288                 pubkey: nodes[2].node.get_our_node_id(),
1289                 node_features: NodeFeatures::empty(),
1290                 short_channel_id: chan_3.0.contents.short_channel_id,
1291                 channel_features: ChannelFeatures::empty(),
1292                 fee_msat: 0,
1293                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1294         });
1295         hops.push(RouteHop {
1296                 pubkey: nodes[1].node.get_our_node_id(),
1297                 node_features: NodeFeatures::known(),
1298                 short_channel_id: chan_2.0.contents.short_channel_id,
1299                 channel_features: ChannelFeatures::known(),
1300                 fee_msat: 1000000,
1301                 cltv_expiry_delta: TEST_FINAL_CLTV,
1302         });
1303         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;
1304         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;
1305         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1306
1307         // Claim the rebalances...
1308         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1309         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1310
1311         // Add a duplicate new channel from 2 to 4
1312         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1313
1314         // Send some payments across both channels
1315         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1316         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1317         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1318
1319
1320         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1321         let events = nodes[0].node.get_and_clear_pending_msg_events();
1322         assert_eq!(events.len(), 0);
1323         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);
1324
1325         //TODO: Test that routes work again here as we've been notified that the channel is full
1326
1327         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1328         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1329         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1330
1331         // Close down the channels...
1332         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1333         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1334         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1335         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1336         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1337 }
1338
1339 #[test]
1340 fn holding_cell_htlc_counting() {
1341         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1342         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1343         // commitment dance rounds.
1344         let chanmon_cfgs = create_chanmon_cfgs(3);
1345         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1346         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1347         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1348         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1349         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1350         let logger = test_utils::TestLogger::new();
1351
1352         let mut payments = Vec::new();
1353         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1354                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
1355                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1356                 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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1357                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1358                 payments.push((payment_preimage, payment_hash));
1359         }
1360         check_added_monitors!(nodes[1], 1);
1361
1362         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1363         assert_eq!(events.len(), 1);
1364         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1365         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1366
1367         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1368         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1369         // another HTLC.
1370         let (_, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[2]);
1371         {
1372                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1373                 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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1374                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1375                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1376                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1377                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1378         }
1379
1380         // This should also be true if we try to forward a payment.
1381         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[2]);
1382         {
1383                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1384                 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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1385                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1386                 check_added_monitors!(nodes[0], 1);
1387         }
1388
1389         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1390         assert_eq!(events.len(), 1);
1391         let payment_event = SendEvent::from_event(events.pop().unwrap());
1392         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1393
1394         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1395         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1396         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1397         // fails), the second will process the resulting failure and fail the HTLC backward.
1398         expect_pending_htlcs_forwardable!(nodes[1]);
1399         expect_pending_htlcs_forwardable!(nodes[1]);
1400         check_added_monitors!(nodes[1], 1);
1401
1402         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1403         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1404         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1405
1406         expect_payment_failure_chan_update!(nodes[0], chan_2.0.contents.short_channel_id, false);
1407         expect_payment_failed!(nodes[0], payment_hash_2, false);
1408
1409         // Now forward all the pending HTLCs and claim them back
1410         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1411         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1412         check_added_monitors!(nodes[2], 1);
1413
1414         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1415         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1416         check_added_monitors!(nodes[1], 1);
1417         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1418
1419         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1420         check_added_monitors!(nodes[1], 1);
1421         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1422
1423         for ref update in as_updates.update_add_htlcs.iter() {
1424                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1425         }
1426         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1427         check_added_monitors!(nodes[2], 1);
1428         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1429         check_added_monitors!(nodes[2], 1);
1430         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1431
1432         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1433         check_added_monitors!(nodes[1], 1);
1434         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1435         check_added_monitors!(nodes[1], 1);
1436         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1437
1438         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1439         check_added_monitors!(nodes[2], 1);
1440
1441         expect_pending_htlcs_forwardable!(nodes[2]);
1442
1443         let events = nodes[2].node.get_and_clear_pending_events();
1444         assert_eq!(events.len(), payments.len());
1445         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1446                 match event {
1447                         &Event::PaymentReceived { ref payment_hash, .. } => {
1448                                 assert_eq!(*payment_hash, *hash);
1449                         },
1450                         _ => panic!("Unexpected event"),
1451                 };
1452         }
1453
1454         for (preimage, _) in payments.drain(..) {
1455                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1456         }
1457
1458         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1459 }
1460
1461 #[test]
1462 fn duplicate_htlc_test() {
1463         // Test that we accept duplicate payment_hash HTLCs across the network and that
1464         // claiming/failing them are all separate and don't affect each other
1465         let chanmon_cfgs = create_chanmon_cfgs(6);
1466         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1467         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1468         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1469
1470         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1471         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1472         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1473         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1474         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1475         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1476
1477         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1478
1479         *nodes[0].network_payment_count.borrow_mut() -= 1;
1480         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1481
1482         *nodes[0].network_payment_count.borrow_mut() -= 1;
1483         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1484
1485         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1486         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1487         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1488 }
1489
1490 #[test]
1491 fn test_duplicate_htlc_different_direction_onchain() {
1492         // Test that ChannelMonitor doesn't generate 2 preimage txn
1493         // when we have 2 HTLCs with same preimage that go across a node
1494         // in opposite directions, even with the same payment secret.
1495         let chanmon_cfgs = create_chanmon_cfgs(2);
1496         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1497         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1498         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1499
1500         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1501         let logger = test_utils::TestLogger::new();
1502
1503         // balancing
1504         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1505
1506         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1507
1508         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1509         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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 800_000, TEST_FINAL_CLTV, &logger).unwrap();
1510         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, 0).unwrap();
1511         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1512
1513         // Provide preimage to node 0 by claiming payment
1514         nodes[0].node.claim_funds(payment_preimage);
1515         check_added_monitors!(nodes[0], 1);
1516
1517         // Broadcast node 1 commitment txn
1518         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1519
1520         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1521         let mut has_both_htlcs = 0; // check htlcs match ones committed
1522         for outp in remote_txn[0].output.iter() {
1523                 if outp.value == 800_000 / 1000 {
1524                         has_both_htlcs += 1;
1525                 } else if outp.value == 900_000 / 1000 {
1526                         has_both_htlcs += 1;
1527                 }
1528         }
1529         assert_eq!(has_both_htlcs, 2);
1530
1531         mine_transaction(&nodes[0], &remote_txn[0]);
1532         check_added_monitors!(nodes[0], 1);
1533         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1534
1535         // Check we only broadcast 1 timeout tx
1536         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1537         assert_eq!(claim_txn.len(), 8);
1538         assert_eq!(claim_txn[1], claim_txn[4]);
1539         assert_eq!(claim_txn[2], claim_txn[5]);
1540         check_spends!(claim_txn[1], chan_1.3);
1541         check_spends!(claim_txn[2], claim_txn[1]);
1542         check_spends!(claim_txn[7], claim_txn[1]);
1543
1544         assert_eq!(claim_txn[0].input.len(), 1);
1545         assert_eq!(claim_txn[3].input.len(), 1);
1546         assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1547
1548         assert_eq!(claim_txn[0].input.len(), 1);
1549         assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1550         check_spends!(claim_txn[0], remote_txn[0]);
1551         assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1552         assert_eq!(claim_txn[6].input.len(), 1);
1553         assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1554         check_spends!(claim_txn[6], remote_txn[0]);
1555         assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1556
1557         let events = nodes[0].node.get_and_clear_pending_msg_events();
1558         assert_eq!(events.len(), 3);
1559         for e in events {
1560                 match e {
1561                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1562                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1563                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1564                                 assert_eq!(msg.data, "Commitment or closing transaction was confirmed on chain.");
1565                         },
1566                         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, .. } } => {
1567                                 assert!(update_add_htlcs.is_empty());
1568                                 assert!(update_fail_htlcs.is_empty());
1569                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1570                                 assert!(update_fail_malformed_htlcs.is_empty());
1571                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1572                         },
1573                         _ => panic!("Unexpected event"),
1574                 }
1575         }
1576 }
1577
1578 #[test]
1579 fn test_basic_channel_reserve() {
1580         let chanmon_cfgs = create_chanmon_cfgs(2);
1581         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1582         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1583         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1584         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1585         let logger = test_utils::TestLogger::new();
1586
1587         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1588         let channel_reserve = chan_stat.channel_reserve_msat;
1589
1590         // The 2* and +1 are for the fee spike reserve.
1591         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
1592         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1593         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1594         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1595         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(), Some(InvoiceFeatures::known()), None, &Vec::new(), max_can_send + 1, TEST_FINAL_CLTV, &logger).unwrap();
1596         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1597         match err {
1598                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1599                         match &fails[0] {
1600                                 &APIError::ChannelUnavailable{ref err} =>
1601                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1602                                 _ => panic!("Unexpected error variant"),
1603                         }
1604                 },
1605                 _ => panic!("Unexpected error variant"),
1606         }
1607         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1608         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);
1609
1610         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1611 }
1612
1613 #[test]
1614 fn test_fee_spike_violation_fails_htlc() {
1615         let chanmon_cfgs = create_chanmon_cfgs(2);
1616         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1617         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1618         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1619         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1620
1621         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1622         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1623         let secp_ctx = Secp256k1::new();
1624         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1625
1626         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1627
1628         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1629         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1630         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1631         let msg = msgs::UpdateAddHTLC {
1632                 channel_id: chan.2,
1633                 htlc_id: 0,
1634                 amount_msat: htlc_msat,
1635                 payment_hash: payment_hash,
1636                 cltv_expiry: htlc_cltv,
1637                 onion_routing_packet: onion_packet,
1638         };
1639
1640         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1641
1642         // Now manually create the commitment_signed message corresponding to the update_add
1643         // nodes[0] just sent. In the code for construction of this message, "local" refers
1644         // to the sender of the message, and "remote" refers to the receiver.
1645
1646         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1647
1648         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1649
1650         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1651         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1652         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point) = {
1653                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1654                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1655                 let chan_signer = local_chan.get_signer();
1656                 let pubkeys = chan_signer.pubkeys();
1657                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1658                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1659                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
1660         };
1661         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point) = {
1662                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1663                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1664                 let chan_signer = remote_chan.get_signer();
1665                 let pubkeys = chan_signer.pubkeys();
1666                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1667                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
1668         };
1669
1670         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1671         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1672                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1673
1674         // Build the remote commitment transaction so we can sign it, and then later use the
1675         // signature for the commitment_signed message.
1676         let local_chan_balance = 1313;
1677
1678         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1679                 offered: false,
1680                 amount_msat: 3460001,
1681                 cltv_expiry: htlc_cltv,
1682                 payment_hash,
1683                 transaction_output_index: Some(1),
1684         };
1685
1686         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1687
1688         let res = {
1689                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1690                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1691                 let local_chan_signer = local_chan.get_signer();
1692                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1693                         commitment_number,
1694                         95000,
1695                         local_chan_balance,
1696                         commit_tx_keys.clone(),
1697                         feerate_per_kw,
1698                         &mut vec![(accepted_htlc_info, ())],
1699                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1700                 );
1701                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1702         };
1703
1704         let commit_signed_msg = msgs::CommitmentSigned {
1705                 channel_id: chan.2,
1706                 signature: res.0,
1707                 htlc_signatures: res.1
1708         };
1709
1710         // Send the commitment_signed message to the nodes[1].
1711         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1712         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1713
1714         // Send the RAA to nodes[1].
1715         let raa_msg = msgs::RevokeAndACK {
1716                 channel_id: chan.2,
1717                 per_commitment_secret: local_secret,
1718                 next_per_commitment_point: next_local_point
1719         };
1720         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1721
1722         let events = nodes[1].node.get_and_clear_pending_msg_events();
1723         assert_eq!(events.len(), 1);
1724         // Make sure the HTLC failed in the way we expect.
1725         match events[0] {
1726                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1727                         assert_eq!(update_fail_htlcs.len(), 1);
1728                         update_fail_htlcs[0].clone()
1729                 },
1730                 _ => panic!("Unexpected event"),
1731         };
1732         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1733                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1734
1735         check_added_monitors!(nodes[1], 2);
1736 }
1737
1738 #[test]
1739 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1740         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1741         // Set the fee rate for the channel very high, to the point where the fundee
1742         // sending any above-dust amount would result in a channel reserve violation.
1743         // In this test we check that we would be prevented from sending an HTLC in
1744         // this situation.
1745         let feerate_per_kw = 253;
1746         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1747         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1748         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1749         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1750         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1751
1752         let mut push_amt = 100_000_000;
1753         push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT + COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
1754         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1755
1756         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1757
1758         // Sending exactly enough to hit the reserve amount should be accepted
1759         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1760
1761         // However one more HTLC should be significantly over the reserve amount and fail.
1762         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1763         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1764                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1765         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1766         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);
1767 }
1768
1769 #[test]
1770 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1771         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1772         // Set the fee rate for the channel very high, to the point where the funder
1773         // receiving 1 update_add_htlc would result in them closing the channel due
1774         // to channel reserve violation. This close could also happen if the fee went
1775         // up a more realistic amount, but many HTLCs were outstanding at the time of
1776         // the update_add_htlc.
1777         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1778         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1779         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1780         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1781         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1782         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1783
1784         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1785         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1786         let secp_ctx = Secp256k1::new();
1787         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1788         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1789         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1790         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &Some(payment_secret), cur_height, &None).unwrap();
1791         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1792         let msg = msgs::UpdateAddHTLC {
1793                 channel_id: chan.2,
1794                 htlc_id: 1,
1795                 amount_msat: htlc_msat + 1,
1796                 payment_hash: payment_hash,
1797                 cltv_expiry: htlc_cltv,
1798                 onion_routing_packet: onion_packet,
1799         };
1800
1801         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1802         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1803         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);
1804         assert_eq!(nodes[0].node.list_channels().len(), 0);
1805         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1806         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1807         check_added_monitors!(nodes[0], 1);
1808 }
1809
1810 #[test]
1811 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1812         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1813         // calculating our commitment transaction fee (this was previously broken).
1814         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1815         let feerate_per_kw = 253;
1816         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1817         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1818
1819         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1820         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1821         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1822
1823         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1824         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1825         // transaction fee with 0 HTLCs (183 sats)).
1826         let mut push_amt = 100_000_000;
1827         push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT) / 1000 * 1000;
1828         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1829         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1830
1831         let dust_amt = crate::ln::channel::MIN_DUST_LIMIT_SATOSHIS * 1000
1832                 + feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000 * 1000 - 1;
1833         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1834         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1835         // commitment transaction fee.
1836         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1837
1838         // One more than the dust amt should fail, however.
1839         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1840         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1841                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1842 }
1843
1844 #[test]
1845 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1846         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1847         // calculating our counterparty's commitment transaction fee (this was previously broken).
1848         let chanmon_cfgs = create_chanmon_cfgs(2);
1849         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1850         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1851         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1852         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1853
1854         let payment_amt = 46000; // Dust amount
1855         // In the previous code, these first four payments would succeed.
1856         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1857         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1858         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1859         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1860
1861         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1862         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1863         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1864         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1865         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1866         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1867
1868         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1869         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1870         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1871         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1872 }
1873
1874 #[test]
1875 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1876         let chanmon_cfgs = create_chanmon_cfgs(3);
1877         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1878         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1879         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1880         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1881         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1882
1883         let feemsat = 239;
1884         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1885         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1886         let feerate = get_feerate!(nodes[0], chan.2);
1887
1888         // Add a 2* and +1 for the fee spike reserve.
1889         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1890         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;
1891         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1892
1893         // Add a pending HTLC.
1894         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1895         let payment_event_1 = {
1896                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1897                 check_added_monitors!(nodes[0], 1);
1898
1899                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1900                 assert_eq!(events.len(), 1);
1901                 SendEvent::from_event(events.remove(0))
1902         };
1903         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1904
1905         // Attempt to trigger a channel reserve violation --> payment failure.
1906         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1907         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;
1908         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1909         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1910
1911         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1912         let secp_ctx = Secp256k1::new();
1913         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1914         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1915         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1916         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1917         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1918         let msg = msgs::UpdateAddHTLC {
1919                 channel_id: chan.2,
1920                 htlc_id: 1,
1921                 amount_msat: htlc_msat + 1,
1922                 payment_hash: our_payment_hash_1,
1923                 cltv_expiry: htlc_cltv,
1924                 onion_routing_packet: onion_packet,
1925         };
1926
1927         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1928         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1929         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1930         assert_eq!(nodes[1].node.list_channels().len(), 1);
1931         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1932         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1933         check_added_monitors!(nodes[1], 1);
1934 }
1935
1936 #[test]
1937 fn test_inbound_outbound_capacity_is_not_zero() {
1938         let chanmon_cfgs = create_chanmon_cfgs(2);
1939         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1940         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1941         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1942         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1943         let channels0 = node_chanmgrs[0].list_channels();
1944         let channels1 = node_chanmgrs[1].list_channels();
1945         assert_eq!(channels0.len(), 1);
1946         assert_eq!(channels1.len(), 1);
1947
1948         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1949         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1950         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1951
1952         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1953         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1954 }
1955
1956 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1957         (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1958 }
1959
1960 #[test]
1961 fn test_channel_reserve_holding_cell_htlcs() {
1962         let chanmon_cfgs = create_chanmon_cfgs(3);
1963         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1964         // When this test was written, the default base fee floated based on the HTLC count.
1965         // It is now fixed, so we simply set the fee to the expected value here.
1966         let mut config = test_default_channel_config();
1967         config.channel_options.forwarding_fee_base_msat = 239;
1968         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1969         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1970         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1971         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1972
1973         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1974         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1975
1976         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1977         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1978
1979         macro_rules! expect_forward {
1980                 ($node: expr) => {{
1981                         let mut events = $node.node.get_and_clear_pending_msg_events();
1982                         assert_eq!(events.len(), 1);
1983                         check_added_monitors!($node, 1);
1984                         let payment_event = SendEvent::from_event(events.remove(0));
1985                         payment_event
1986                 }}
1987         }
1988
1989         let feemsat = 239; // set above
1990         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1991         let feerate = get_feerate!(nodes[0], chan_1.2);
1992
1993         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1994
1995         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1996         {
1997                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1998                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1999                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
2000                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
2001                         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)));
2002                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2003                 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);
2004         }
2005
2006         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
2007         // nodes[0]'s wealth
2008         loop {
2009                 let amt_msat = recv_value_0 + total_fee_msat;
2010                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
2011                 // Also, ensure that each payment has enough to be over the dust limit to
2012                 // ensure it'll be included in each commit tx fee calculation.
2013                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2014                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
2015                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
2016                         break;
2017                 }
2018                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
2019
2020                 let (stat01_, stat11_, stat12_, stat22_) = (
2021                         get_channel_value_stat!(nodes[0], chan_1.2),
2022                         get_channel_value_stat!(nodes[1], chan_1.2),
2023                         get_channel_value_stat!(nodes[1], chan_2.2),
2024                         get_channel_value_stat!(nodes[2], chan_2.2),
2025                 );
2026
2027                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
2028                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
2029                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
2030                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
2031                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
2032         }
2033
2034         // adding pending output.
2035         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
2036         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2037         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2038         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2039         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2040         // cases where 1 msat over X amount will cause a payment failure, but anything less than
2041         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2042         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2043         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2044         // policy.
2045         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2046         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2047         let amt_msat_1 = recv_value_1 + total_fee_msat;
2048
2049         let (route_1, our_payment_hash_1, our_payment_preimage_1, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_1);
2050         let payment_event_1 = {
2051                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
2052                 check_added_monitors!(nodes[0], 1);
2053
2054                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2055                 assert_eq!(events.len(), 1);
2056                 SendEvent::from_event(events.remove(0))
2057         };
2058         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2059
2060         // channel reserve test with htlc pending output > 0
2061         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2062         {
2063                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
2064                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
2065                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2066                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2067         }
2068
2069         // split the rest to test holding cell
2070         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2071         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2072         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2073         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2074         {
2075                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2076                 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);
2077         }
2078
2079         // now see if they go through on both sides
2080         let (route_21, our_payment_hash_21, our_payment_preimage_21, our_payment_secret_21) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_21);
2081         // but this will stuck in the holding cell
2082         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
2083         check_added_monitors!(nodes[0], 0);
2084         let events = nodes[0].node.get_and_clear_pending_events();
2085         assert_eq!(events.len(), 0);
2086
2087         // test with outbound holding cell amount > 0
2088         {
2089                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
2090                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
2091                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2092                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2093                 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);
2094         }
2095
2096         let (route_22, our_payment_hash_22, our_payment_preimage_22, our_payment_secret_22) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
2097         // this will also stuck in the holding cell
2098         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
2099         check_added_monitors!(nodes[0], 0);
2100         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2101         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2102
2103         // flush the pending htlc
2104         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2105         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2106         check_added_monitors!(nodes[1], 1);
2107
2108         // the pending htlc should be promoted to committed
2109         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2110         check_added_monitors!(nodes[0], 1);
2111         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2112
2113         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2114         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2115         // No commitment_signed so get_event_msg's assert(len == 1) passes
2116         check_added_monitors!(nodes[0], 1);
2117
2118         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2119         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2120         check_added_monitors!(nodes[1], 1);
2121
2122         expect_pending_htlcs_forwardable!(nodes[1]);
2123
2124         let ref payment_event_11 = expect_forward!(nodes[1]);
2125         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2126         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2127
2128         expect_pending_htlcs_forwardable!(nodes[2]);
2129         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
2130
2131         // flush the htlcs in the holding cell
2132         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2133         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2134         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2135         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2136         expect_pending_htlcs_forwardable!(nodes[1]);
2137
2138         let ref payment_event_3 = expect_forward!(nodes[1]);
2139         assert_eq!(payment_event_3.msgs.len(), 2);
2140         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2141         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2142
2143         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2144         expect_pending_htlcs_forwardable!(nodes[2]);
2145
2146         let events = nodes[2].node.get_and_clear_pending_events();
2147         assert_eq!(events.len(), 2);
2148         match events[0] {
2149                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
2150                         assert_eq!(our_payment_hash_21, *payment_hash);
2151                         assert_eq!(recv_value_21, amt);
2152                         match &purpose {
2153                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2154                                         assert!(payment_preimage.is_none());
2155                                         assert_eq!(our_payment_secret_21, *payment_secret);
2156                                 },
2157                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2158                         }
2159                 },
2160                 _ => panic!("Unexpected event"),
2161         }
2162         match events[1] {
2163                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
2164                         assert_eq!(our_payment_hash_22, *payment_hash);
2165                         assert_eq!(recv_value_22, amt);
2166                         match &purpose {
2167                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2168                                         assert!(payment_preimage.is_none());
2169                                         assert_eq!(our_payment_secret_22, *payment_secret);
2170                                 },
2171                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2172                         }
2173                 },
2174                 _ => panic!("Unexpected event"),
2175         }
2176
2177         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2178         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2179         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2180
2181         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2182         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2183         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2184
2185         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2186         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);
2187         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2188         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2189         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2190
2191         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2192         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2193 }
2194
2195 #[test]
2196 fn channel_reserve_in_flight_removes() {
2197         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2198         // can send to its counterparty, but due to update ordering, the other side may not yet have
2199         // considered those HTLCs fully removed.
2200         // This tests that we don't count HTLCs which will not be included in the next remote
2201         // commitment transaction towards the reserve value (as it implies no commitment transaction
2202         // will be generated which violates the remote reserve value).
2203         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2204         // To test this we:
2205         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2206         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2207         //    you only consider the value of the first HTLC, it may not),
2208         //  * start routing a third HTLC from A to B,
2209         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2210         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2211         //  * deliver the first fulfill from B
2212         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2213         //    claim,
2214         //  * deliver A's response CS and RAA.
2215         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2216         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2217         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2218         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2219         let chanmon_cfgs = create_chanmon_cfgs(2);
2220         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2221         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2222         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2223         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2224         let logger = test_utils::TestLogger::new();
2225
2226         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2227         // Route the first two HTLCs.
2228         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2229         let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2230
2231         // Start routing the third HTLC (this is just used to get everyone in the right state).
2232         let (payment_preimage_3, payment_hash_3, payment_secret_3) = get_payment_preimage_hash!(nodes[1]);
2233         let send_1 = {
2234                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2235                 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(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
2236                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2237                 check_added_monitors!(nodes[0], 1);
2238                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2239                 assert_eq!(events.len(), 1);
2240                 SendEvent::from_event(events.remove(0))
2241         };
2242
2243         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2244         // initial fulfill/CS.
2245         assert!(nodes[1].node.claim_funds(payment_preimage_1));
2246         check_added_monitors!(nodes[1], 1);
2247         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2248
2249         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2250         // remove the second HTLC when we send the HTLC back from B to A.
2251         assert!(nodes[1].node.claim_funds(payment_preimage_2));
2252         check_added_monitors!(nodes[1], 1);
2253         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2254
2255         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2256         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2257         check_added_monitors!(nodes[0], 1);
2258         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2259         expect_payment_sent!(nodes[0], payment_preimage_1);
2260
2261         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2262         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2263         check_added_monitors!(nodes[1], 1);
2264         // B is already AwaitingRAA, so cant generate a CS here
2265         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2266
2267         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2268         check_added_monitors!(nodes[1], 1);
2269         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2270
2271         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2272         check_added_monitors!(nodes[0], 1);
2273         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2274
2275         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2276         check_added_monitors!(nodes[1], 1);
2277         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2278
2279         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2280         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2281         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2282         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2283         // on-chain as necessary).
2284         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2285         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2286         check_added_monitors!(nodes[0], 1);
2287         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2288         expect_payment_sent!(nodes[0], payment_preimage_2);
2289
2290         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2291         check_added_monitors!(nodes[1], 1);
2292         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2293
2294         expect_pending_htlcs_forwardable!(nodes[1]);
2295         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2296
2297         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2298         // resolve the second HTLC from A's point of view.
2299         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2300         check_added_monitors!(nodes[0], 1);
2301         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2302
2303         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2304         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2305         let (payment_preimage_4, payment_hash_4, payment_secret_4) = get_payment_preimage_hash!(nodes[0]);
2306         let send_2 = {
2307                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2308                 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(), Some(InvoiceFeatures::known()), None, &[], 10000, TEST_FINAL_CLTV, &logger).unwrap();
2309                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2310                 check_added_monitors!(nodes[1], 1);
2311                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2312                 assert_eq!(events.len(), 1);
2313                 SendEvent::from_event(events.remove(0))
2314         };
2315
2316         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2317         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2318         check_added_monitors!(nodes[0], 1);
2319         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2320
2321         // Now just resolve all the outstanding messages/HTLCs for completeness...
2322
2323         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2324         check_added_monitors!(nodes[1], 1);
2325         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2326
2327         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2328         check_added_monitors!(nodes[1], 1);
2329
2330         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2331         check_added_monitors!(nodes[0], 1);
2332         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2333
2334         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2335         check_added_monitors!(nodes[1], 1);
2336         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2337
2338         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2339         check_added_monitors!(nodes[0], 1);
2340
2341         expect_pending_htlcs_forwardable!(nodes[0]);
2342         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2343
2344         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2345         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2346 }
2347
2348 #[test]
2349 fn channel_monitor_network_test() {
2350         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2351         // tests that ChannelMonitor is able to recover from various states.
2352         let chanmon_cfgs = create_chanmon_cfgs(5);
2353         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2354         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2355         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2356
2357         // Create some initial channels
2358         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2359         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2360         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2361         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2362
2363         // Make sure all nodes are at the same starting height
2364         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2365         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2366         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2367         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2368         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2369
2370         // Rebalance the network a bit by relaying one payment through all the channels...
2371         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2372         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2373         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2374         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2375
2376         // Simple case with no pending HTLCs:
2377         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2378         check_added_monitors!(nodes[1], 1);
2379         check_closed_broadcast!(nodes[1], false);
2380         {
2381                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2382                 assert_eq!(node_txn.len(), 1);
2383                 mine_transaction(&nodes[0], &node_txn[0]);
2384                 check_added_monitors!(nodes[0], 1);
2385                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2386         }
2387         check_closed_broadcast!(nodes[0], true);
2388         assert_eq!(nodes[0].node.list_channels().len(), 0);
2389         assert_eq!(nodes[1].node.list_channels().len(), 1);
2390
2391         // One pending HTLC is discarded by the force-close:
2392         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2393
2394         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2395         // broadcasted until we reach the timelock time).
2396         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2397         check_closed_broadcast!(nodes[1], false);
2398         check_added_monitors!(nodes[1], 1);
2399         {
2400                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2401                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2402                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2403                 mine_transaction(&nodes[2], &node_txn[0]);
2404                 check_added_monitors!(nodes[2], 1);
2405                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2406         }
2407         check_closed_broadcast!(nodes[2], true);
2408         assert_eq!(nodes[1].node.list_channels().len(), 0);
2409         assert_eq!(nodes[2].node.list_channels().len(), 1);
2410
2411         macro_rules! claim_funds {
2412                 ($node: expr, $prev_node: expr, $preimage: expr) => {
2413                         {
2414                                 assert!($node.node.claim_funds($preimage));
2415                                 check_added_monitors!($node, 1);
2416
2417                                 let events = $node.node.get_and_clear_pending_msg_events();
2418                                 assert_eq!(events.len(), 1);
2419                                 match events[0] {
2420                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2421                                                 assert!(update_add_htlcs.is_empty());
2422                                                 assert!(update_fail_htlcs.is_empty());
2423                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2424                                         },
2425                                         _ => panic!("Unexpected event"),
2426                                 };
2427                         }
2428                 }
2429         }
2430
2431         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2432         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2433         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2434         check_added_monitors!(nodes[2], 1);
2435         check_closed_broadcast!(nodes[2], false);
2436         let node2_commitment_txid;
2437         {
2438                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2439                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2440                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2441                 node2_commitment_txid = node_txn[0].txid();
2442
2443                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2444                 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2445                 mine_transaction(&nodes[3], &node_txn[0]);
2446                 check_added_monitors!(nodes[3], 1);
2447                 check_preimage_claim(&nodes[3], &node_txn);
2448         }
2449         check_closed_broadcast!(nodes[3], true);
2450         assert_eq!(nodes[2].node.list_channels().len(), 0);
2451         assert_eq!(nodes[3].node.list_channels().len(), 1);
2452
2453         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2454         // confusing us in the following tests.
2455         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().remove(&OutPoint { txid: chan_3.3.txid(), index: 0 }).unwrap();
2456
2457         // One pending HTLC to time out:
2458         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2459         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2460         // buffer space).
2461
2462         let (close_chan_update_1, close_chan_update_2) = {
2463                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2464                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2465                 assert_eq!(events.len(), 2);
2466                 let close_chan_update_1 = match events[0] {
2467                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2468                                 msg.clone()
2469                         },
2470                         _ => panic!("Unexpected event"),
2471                 };
2472                 match events[1] {
2473                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2474                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2475                         },
2476                         _ => panic!("Unexpected event"),
2477                 }
2478                 check_added_monitors!(nodes[3], 1);
2479
2480                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2481                 {
2482                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2483                         node_txn.retain(|tx| {
2484                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2485                                         false
2486                                 } else { true }
2487                         });
2488                 }
2489
2490                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2491
2492                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2493                 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2494
2495                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2496                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2497                 assert_eq!(events.len(), 2);
2498                 let close_chan_update_2 = match events[0] {
2499                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2500                                 msg.clone()
2501                         },
2502                         _ => panic!("Unexpected event"),
2503                 };
2504                 match events[1] {
2505                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2506                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2507                         },
2508                         _ => panic!("Unexpected event"),
2509                 }
2510                 check_added_monitors!(nodes[4], 1);
2511                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2512
2513                 mine_transaction(&nodes[4], &node_txn[0]);
2514                 check_preimage_claim(&nodes[4], &node_txn);
2515                 (close_chan_update_1, close_chan_update_2)
2516         };
2517         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2518         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2519         assert_eq!(nodes[3].node.list_channels().len(), 0);
2520         assert_eq!(nodes[4].node.list_channels().len(), 0);
2521
2522         nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().insert(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon);
2523 }
2524
2525 #[test]
2526 fn test_justice_tx() {
2527         // Test justice txn built on revoked HTLC-Success tx, against both sides
2528         let mut alice_config = UserConfig::default();
2529         alice_config.channel_options.announced_channel = true;
2530         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2531         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2532         let mut bob_config = UserConfig::default();
2533         bob_config.channel_options.announced_channel = true;
2534         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2535         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2536         let user_cfgs = [Some(alice_config), Some(bob_config)];
2537         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2538         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2539         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2540         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2541         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2542         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2543         // Create some new channels:
2544         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2545
2546         // A pending HTLC which will be revoked:
2547         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2548         // Get the will-be-revoked local txn from nodes[0]
2549         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2550         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2551         assert_eq!(revoked_local_txn[0].input.len(), 1);
2552         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2553         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2554         assert_eq!(revoked_local_txn[1].input.len(), 1);
2555         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2556         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2557         // Revoke the old state
2558         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2559
2560         {
2561                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2562                 {
2563                         let mut node_txn = nodes[1].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(), 2); // We should claim the revoked output and the HTLC output
2566
2567                         check_spends!(node_txn[0], revoked_local_txn[0]);
2568                         node_txn.swap_remove(0);
2569                         node_txn.truncate(1);
2570                 }
2571                 check_added_monitors!(nodes[1], 1);
2572                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2573
2574                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2575                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2576                 // Verify broadcast of revoked HTLC-timeout
2577                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2578                 check_added_monitors!(nodes[0], 1);
2579                 // Broadcast revoked HTLC-timeout on node 1
2580                 mine_transaction(&nodes[1], &node_txn[1]);
2581                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2582         }
2583         get_announce_close_broadcast_events(&nodes, 0, 1);
2584
2585         assert_eq!(nodes[0].node.list_channels().len(), 0);
2586         assert_eq!(nodes[1].node.list_channels().len(), 0);
2587
2588         // We test justice_tx build by A on B's revoked HTLC-Success tx
2589         // Create some new channels:
2590         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2591         {
2592                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2593                 node_txn.clear();
2594         }
2595
2596         // A pending HTLC which will be revoked:
2597         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2598         // Get the will-be-revoked local txn from B
2599         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2600         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2601         assert_eq!(revoked_local_txn[0].input.len(), 1);
2602         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2603         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2604         // Revoke the old state
2605         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2606         {
2607                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2608                 {
2609                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2610                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2611                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2612
2613                         check_spends!(node_txn[0], revoked_local_txn[0]);
2614                         node_txn.swap_remove(0);
2615                 }
2616                 check_added_monitors!(nodes[0], 1);
2617                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2618
2619                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2620                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2621                 check_added_monitors!(nodes[1], 1);
2622                 mine_transaction(&nodes[0], &node_txn[1]);
2623                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2624         }
2625         get_announce_close_broadcast_events(&nodes, 0, 1);
2626         assert_eq!(nodes[0].node.list_channels().len(), 0);
2627         assert_eq!(nodes[1].node.list_channels().len(), 0);
2628 }
2629
2630 #[test]
2631 fn revoked_output_claim() {
2632         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2633         // transaction is broadcast by its counterparty
2634         let chanmon_cfgs = create_chanmon_cfgs(2);
2635         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2636         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2637         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2638         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2639         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2640         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2641         assert_eq!(revoked_local_txn.len(), 1);
2642         // Only output is the full channel value back to nodes[0]:
2643         assert_eq!(revoked_local_txn[0].output.len(), 1);
2644         // Send a payment through, updating everyone's latest commitment txn
2645         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2646
2647         // Inform nodes[1] that nodes[0] broadcast a stale tx
2648         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2649         check_added_monitors!(nodes[1], 1);
2650         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2651         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2652
2653         check_spends!(node_txn[0], revoked_local_txn[0]);
2654         check_spends!(node_txn[1], chan_1.3);
2655
2656         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2657         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2658         get_announce_close_broadcast_events(&nodes, 0, 1);
2659         check_added_monitors!(nodes[0], 1)
2660 }
2661
2662 #[test]
2663 fn claim_htlc_outputs_shared_tx() {
2664         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2665         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2666         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2667         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2668         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2669         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2670
2671         // Create some new channel:
2672         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2673
2674         // Rebalance the network to generate htlc in the two directions
2675         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2676         // 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
2677         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2678         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2679
2680         // Get the will-be-revoked local txn from node[0]
2681         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2682         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2683         assert_eq!(revoked_local_txn[0].input.len(), 1);
2684         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2685         assert_eq!(revoked_local_txn[1].input.len(), 1);
2686         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2687         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2688         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2689
2690         //Revoke the old state
2691         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2692
2693         {
2694                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2695                 check_added_monitors!(nodes[0], 1);
2696                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2697                 check_added_monitors!(nodes[1], 1);
2698                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2699                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2700
2701                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2702                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2703
2704                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2705                 check_spends!(node_txn[0], revoked_local_txn[0]);
2706
2707                 let mut witness_lens = BTreeSet::new();
2708                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2709                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2710                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2711                 assert_eq!(witness_lens.len(), 3);
2712                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2713                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2714                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2715
2716                 // Next nodes[1] broadcasts its current local tx state:
2717                 assert_eq!(node_txn[1].input.len(), 1);
2718                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2719         }
2720         get_announce_close_broadcast_events(&nodes, 0, 1);
2721         assert_eq!(nodes[0].node.list_channels().len(), 0);
2722         assert_eq!(nodes[1].node.list_channels().len(), 0);
2723 }
2724
2725 #[test]
2726 fn claim_htlc_outputs_single_tx() {
2727         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2728         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2729         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2730         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2731         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2732         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2733
2734         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2735
2736         // Rebalance the network to generate htlc in the two directions
2737         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2738         // 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
2739         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2740         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2741         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2742
2743         // Get the will-be-revoked local txn from node[0]
2744         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2745
2746         //Revoke the old state
2747         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2748
2749         {
2750                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2751                 check_added_monitors!(nodes[0], 1);
2752                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2753                 check_added_monitors!(nodes[1], 1);
2754                 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2755
2756                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2757                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2758
2759                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2760                 assert_eq!(node_txn.len(), 9);
2761                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2762                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2763                 // 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)
2764                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2765
2766                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2767                 assert_eq!(node_txn[0].input.len(), 1);
2768                 check_spends!(node_txn[0], chan_1.3);
2769                 assert_eq!(node_txn[1].input.len(), 1);
2770                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2771                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2772                 check_spends!(node_txn[1], node_txn[0]);
2773
2774                 // Justice transactions are indices 1-2-4
2775                 assert_eq!(node_txn[2].input.len(), 1);
2776                 assert_eq!(node_txn[3].input.len(), 1);
2777                 assert_eq!(node_txn[4].input.len(), 1);
2778
2779                 check_spends!(node_txn[2], revoked_local_txn[0]);
2780                 check_spends!(node_txn[3], revoked_local_txn[0]);
2781                 check_spends!(node_txn[4], revoked_local_txn[0]);
2782
2783                 let mut witness_lens = BTreeSet::new();
2784                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2785                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2786                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2787                 assert_eq!(witness_lens.len(), 3);
2788                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2789                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2790                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2791         }
2792         get_announce_close_broadcast_events(&nodes, 0, 1);
2793         assert_eq!(nodes[0].node.list_channels().len(), 0);
2794         assert_eq!(nodes[1].node.list_channels().len(), 0);
2795 }
2796
2797 #[test]
2798 fn test_htlc_on_chain_success() {
2799         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2800         // the preimage backward accordingly. So here we test that ChannelManager is
2801         // broadcasting the right event to other nodes in payment path.
2802         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2803         // A --------------------> B ----------------------> C (preimage)
2804         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2805         // commitment transaction was broadcast.
2806         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2807         // towards B.
2808         // B should be able to claim via preimage if A then broadcasts its local tx.
2809         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2810         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2811         // PaymentSent event).
2812
2813         let chanmon_cfgs = create_chanmon_cfgs(3);
2814         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2815         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2816         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2817
2818         // Create some initial channels
2819         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2820         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2821
2822         // Ensure all nodes are at the same height
2823         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2824         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2825         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2826         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2827
2828         // Rebalance the network a bit by relaying one payment through all the channels...
2829         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2830         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2831
2832         let (our_payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2833         let (our_payment_preimage_2, _payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2834
2835         // Broadcast legit commitment tx from C on B's chain
2836         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2837         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2838         assert_eq!(commitment_tx.len(), 1);
2839         check_spends!(commitment_tx[0], chan_2.3);
2840         nodes[2].node.claim_funds(our_payment_preimage);
2841         nodes[2].node.claim_funds(our_payment_preimage_2);
2842         check_added_monitors!(nodes[2], 2);
2843         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2844         assert!(updates.update_add_htlcs.is_empty());
2845         assert!(updates.update_fail_htlcs.is_empty());
2846         assert!(updates.update_fail_malformed_htlcs.is_empty());
2847         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2848
2849         mine_transaction(&nodes[2], &commitment_tx[0]);
2850         check_closed_broadcast!(nodes[2], true);
2851         check_added_monitors!(nodes[2], 1);
2852         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)
2853         assert_eq!(node_txn.len(), 5);
2854         assert_eq!(node_txn[0], node_txn[3]);
2855         assert_eq!(node_txn[1], node_txn[4]);
2856         assert_eq!(node_txn[2], commitment_tx[0]);
2857         check_spends!(node_txn[0], commitment_tx[0]);
2858         check_spends!(node_txn[1], commitment_tx[0]);
2859         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2860         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2861         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2862         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2863         assert_eq!(node_txn[0].lock_time, 0);
2864         assert_eq!(node_txn[1].lock_time, 0);
2865
2866         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2867         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2868         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2869         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2870         {
2871                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2872                 assert_eq!(added_monitors.len(), 1);
2873                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2874                 added_monitors.clear();
2875         }
2876         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2877         assert_eq!(forwarded_events.len(), 2);
2878         if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[0] {
2879                 } else { panic!(); }
2880         if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[1] {
2881                 } else { panic!(); }
2882         let events = nodes[1].node.get_and_clear_pending_msg_events();
2883         {
2884                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2885                 assert_eq!(added_monitors.len(), 2);
2886                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2887                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2888                 added_monitors.clear();
2889         }
2890         assert_eq!(events.len(), 3);
2891         match events[0] {
2892                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2893                 _ => panic!("Unexpected event"),
2894         }
2895         match events[1] {
2896                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2897                 _ => panic!("Unexpected event"),
2898         }
2899
2900         match events[2] {
2901                 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, .. } } => {
2902                         assert!(update_add_htlcs.is_empty());
2903                         assert!(update_fail_htlcs.is_empty());
2904                         assert_eq!(update_fulfill_htlcs.len(), 1);
2905                         assert!(update_fail_malformed_htlcs.is_empty());
2906                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2907                 },
2908                 _ => panic!("Unexpected event"),
2909         };
2910         macro_rules! check_tx_local_broadcast {
2911                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2912                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2913                         assert_eq!(node_txn.len(), 3);
2914                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2915                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2916                         check_spends!(node_txn[1], $commitment_tx);
2917                         check_spends!(node_txn[2], $commitment_tx);
2918                         assert_ne!(node_txn[1].lock_time, 0);
2919                         assert_ne!(node_txn[2].lock_time, 0);
2920                         if $htlc_offered {
2921                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2922                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2923                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2924                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2925                         } else {
2926                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2927                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2928                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2929                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2930                         }
2931                         check_spends!(node_txn[0], $chan_tx);
2932                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2933                         node_txn.clear();
2934                 } }
2935         }
2936         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2937         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2938         // timeout-claim of the output that nodes[2] just claimed via success.
2939         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2940
2941         // Broadcast legit commitment tx from A on B's chain
2942         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2943         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2944         check_spends!(node_a_commitment_tx[0], chan_1.3);
2945         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2946         check_closed_broadcast!(nodes[1], true);
2947         check_added_monitors!(nodes[1], 1);
2948         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2949         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2950         let commitment_spend =
2951                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2952                         check_spends!(node_txn[1], commitment_tx[0]);
2953                         check_spends!(node_txn[2], commitment_tx[0]);
2954                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2955                         &node_txn[0]
2956                 } else {
2957                         check_spends!(node_txn[0], commitment_tx[0]);
2958                         check_spends!(node_txn[1], commitment_tx[0]);
2959                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2960                         &node_txn[2]
2961                 };
2962
2963         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2964         assert_eq!(commitment_spend.input.len(), 2);
2965         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2966         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2967         assert_eq!(commitment_spend.lock_time, 0);
2968         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2969         check_spends!(node_txn[3], chan_1.3);
2970         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2971         check_spends!(node_txn[4], node_txn[3]);
2972         check_spends!(node_txn[5], node_txn[3]);
2973         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2974         // we already checked the same situation with A.
2975
2976         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2977         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2978         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2979         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2980         check_closed_broadcast!(nodes[0], true);
2981         check_added_monitors!(nodes[0], 1);
2982         let events = nodes[0].node.get_and_clear_pending_events();
2983         assert_eq!(events.len(), 2);
2984         let mut first_claimed = false;
2985         for event in events {
2986                 match event {
2987                         Event::PaymentSent { payment_preimage } => {
2988                                 if payment_preimage == our_payment_preimage {
2989                                         assert!(!first_claimed);
2990                                         first_claimed = true;
2991                                 } else {
2992                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2993                                 }
2994                         },
2995                         _ => panic!("Unexpected event"),
2996                 }
2997         }
2998         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2999 }
3000
3001 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
3002         // Test that in case of a unilateral close onchain, we detect the state of output and
3003         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
3004         // broadcasting the right event to other nodes in payment path.
3005         // A ------------------> B ----------------------> C (timeout)
3006         //    B's commitment tx                 C's commitment tx
3007         //            \                                  \
3008         //         B's HTLC timeout tx               B's timeout tx
3009
3010         let chanmon_cfgs = create_chanmon_cfgs(3);
3011         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3012         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3013         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3014         *nodes[0].connect_style.borrow_mut() = connect_style;
3015         *nodes[1].connect_style.borrow_mut() = connect_style;
3016         *nodes[2].connect_style.borrow_mut() = connect_style;
3017
3018         // Create some intial channels
3019         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3020         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3021
3022         // Rebalance the network a bit by relaying one payment thorugh all the channels...
3023         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3024         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3025
3026         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3027
3028         // Broadcast legit commitment tx from C on B's chain
3029         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
3030         check_spends!(commitment_tx[0], chan_2.3);
3031         nodes[2].node.fail_htlc_backwards(&payment_hash);
3032         check_added_monitors!(nodes[2], 0);
3033         expect_pending_htlcs_forwardable!(nodes[2]);
3034         check_added_monitors!(nodes[2], 1);
3035
3036         let events = nodes[2].node.get_and_clear_pending_msg_events();
3037         assert_eq!(events.len(), 1);
3038         match events[0] {
3039                 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, .. } } => {
3040                         assert!(update_add_htlcs.is_empty());
3041                         assert!(!update_fail_htlcs.is_empty());
3042                         assert!(update_fulfill_htlcs.is_empty());
3043                         assert!(update_fail_malformed_htlcs.is_empty());
3044                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3045                 },
3046                 _ => panic!("Unexpected event"),
3047         };
3048         mine_transaction(&nodes[2], &commitment_tx[0]);
3049         check_closed_broadcast!(nodes[2], true);
3050         check_added_monitors!(nodes[2], 1);
3051         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
3052         assert_eq!(node_txn.len(), 1);
3053         check_spends!(node_txn[0], chan_2.3);
3054         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
3055
3056         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3057         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3058         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3059         mine_transaction(&nodes[1], &commitment_tx[0]);
3060         let timeout_tx;
3061         {
3062                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3063                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
3064                 assert_eq!(node_txn[0], node_txn[3]);
3065                 assert_eq!(node_txn[1], node_txn[4]);
3066
3067                 check_spends!(node_txn[2], commitment_tx[0]);
3068                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3069
3070                 check_spends!(node_txn[0], chan_2.3);
3071                 check_spends!(node_txn[1], node_txn[0]);
3072                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3073                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3074
3075                 timeout_tx = node_txn[2].clone();
3076                 node_txn.clear();
3077         }
3078
3079         mine_transaction(&nodes[1], &timeout_tx);
3080         check_added_monitors!(nodes[1], 1);
3081         check_closed_broadcast!(nodes[1], true);
3082         {
3083                 // B will rebroadcast a fee-bumped timeout transaction here.
3084                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3085                 assert_eq!(node_txn.len(), 1);
3086                 check_spends!(node_txn[0], commitment_tx[0]);
3087         }
3088
3089         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3090         {
3091                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
3092                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
3093                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
3094                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
3095                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3096                 if node_txn.len() == 1 {
3097                         check_spends!(node_txn[0], chan_2.3);
3098                 } else {
3099                         assert_eq!(node_txn.len(), 0);
3100                 }
3101         }
3102
3103         expect_pending_htlcs_forwardable!(nodes[1]);
3104         check_added_monitors!(nodes[1], 1);
3105         let events = nodes[1].node.get_and_clear_pending_msg_events();
3106         assert_eq!(events.len(), 1);
3107         match events[0] {
3108                 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, .. } } => {
3109                         assert!(update_add_htlcs.is_empty());
3110                         assert!(!update_fail_htlcs.is_empty());
3111                         assert!(update_fulfill_htlcs.is_empty());
3112                         assert!(update_fail_malformed_htlcs.is_empty());
3113                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3114                 },
3115                 _ => panic!("Unexpected event"),
3116         };
3117
3118         // Broadcast legit commitment tx from B on A's chain
3119         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3120         check_spends!(commitment_tx[0], chan_1.3);
3121
3122         mine_transaction(&nodes[0], &commitment_tx[0]);
3123         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
3124
3125         check_closed_broadcast!(nodes[0], true);
3126         check_added_monitors!(nodes[0], 1);
3127         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3128         assert_eq!(node_txn.len(), 2);
3129         check_spends!(node_txn[0], chan_1.3);
3130         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3131         check_spends!(node_txn[1], commitment_tx[0]);
3132         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3133 }
3134
3135 #[test]
3136 fn test_htlc_on_chain_timeout() {
3137         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3138         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3139         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3140 }
3141
3142 #[test]
3143 fn test_simple_commitment_revoked_fail_backward() {
3144         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3145         // and fail backward accordingly.
3146
3147         let chanmon_cfgs = create_chanmon_cfgs(3);
3148         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3149         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3150         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3151
3152         // Create some initial channels
3153         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3154         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3155
3156         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3157         // Get the will-be-revoked local txn from nodes[2]
3158         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3159         // Revoke the old state
3160         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3161
3162         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3163
3164         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3165         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3166         check_added_monitors!(nodes[1], 1);
3167         check_closed_broadcast!(nodes[1], true);
3168
3169         expect_pending_htlcs_forwardable!(nodes[1]);
3170         check_added_monitors!(nodes[1], 1);
3171         let events = nodes[1].node.get_and_clear_pending_msg_events();
3172         assert_eq!(events.len(), 1);
3173         match events[0] {
3174                 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, .. } } => {
3175                         assert!(update_add_htlcs.is_empty());
3176                         assert_eq!(update_fail_htlcs.len(), 1);
3177                         assert!(update_fulfill_htlcs.is_empty());
3178                         assert!(update_fail_malformed_htlcs.is_empty());
3179                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3180
3181                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3182                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3183                         expect_payment_failure_chan_update!(nodes[0], chan_2.0.contents.short_channel_id, true);
3184                         expect_payment_failed!(nodes[0], payment_hash, false);
3185                 },
3186                 _ => panic!("Unexpected event"),
3187         }
3188 }
3189
3190 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3191         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3192         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3193         // commitment transaction anymore.
3194         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3195         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3196         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3197         // technically disallowed and we should probably handle it reasonably.
3198         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3199         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3200         // transactions:
3201         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3202         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3203         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3204         //   and once they revoke the previous commitment transaction (allowing us to send a new
3205         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3206         let chanmon_cfgs = create_chanmon_cfgs(3);
3207         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3208         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3209         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3210
3211         // Create some initial channels
3212         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3213         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3214
3215         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3216         // Get the will-be-revoked local txn from nodes[2]
3217         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3218         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3219         // Revoke the old state
3220         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3221
3222         let value = if use_dust {
3223                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3224                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3225                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3226         } else { 3000000 };
3227
3228         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3229         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3230         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3231
3232         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
3233         expect_pending_htlcs_forwardable!(nodes[2]);
3234         check_added_monitors!(nodes[2], 1);
3235         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3236         assert!(updates.update_add_htlcs.is_empty());
3237         assert!(updates.update_fulfill_htlcs.is_empty());
3238         assert!(updates.update_fail_malformed_htlcs.is_empty());
3239         assert_eq!(updates.update_fail_htlcs.len(), 1);
3240         assert!(updates.update_fee.is_none());
3241         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3242         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3243         // Drop the last RAA from 3 -> 2
3244
3245         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
3246         expect_pending_htlcs_forwardable!(nodes[2]);
3247         check_added_monitors!(nodes[2], 1);
3248         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3249         assert!(updates.update_add_htlcs.is_empty());
3250         assert!(updates.update_fulfill_htlcs.is_empty());
3251         assert!(updates.update_fail_malformed_htlcs.is_empty());
3252         assert_eq!(updates.update_fail_htlcs.len(), 1);
3253         assert!(updates.update_fee.is_none());
3254         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3255         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3256         check_added_monitors!(nodes[1], 1);
3257         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3258         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3259         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3260         check_added_monitors!(nodes[2], 1);
3261
3262         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
3263         expect_pending_htlcs_forwardable!(nodes[2]);
3264         check_added_monitors!(nodes[2], 1);
3265         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3266         assert!(updates.update_add_htlcs.is_empty());
3267         assert!(updates.update_fulfill_htlcs.is_empty());
3268         assert!(updates.update_fail_malformed_htlcs.is_empty());
3269         assert_eq!(updates.update_fail_htlcs.len(), 1);
3270         assert!(updates.update_fee.is_none());
3271         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3272         // At this point first_payment_hash has dropped out of the latest two commitment
3273         // transactions that nodes[1] is tracking...
3274         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3275         check_added_monitors!(nodes[1], 1);
3276         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3277         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3278         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3279         check_added_monitors!(nodes[2], 1);
3280
3281         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3282         // on nodes[2]'s RAA.
3283         let (_, fourth_payment_hash, fourth_payment_secret) = get_payment_preimage_hash!(nodes[2]);
3284         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3285         let logger = test_utils::TestLogger::new();
3286         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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3287         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3288         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3289         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3290         check_added_monitors!(nodes[1], 0);
3291
3292         if deliver_bs_raa {
3293                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3294                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3295                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3296                 check_added_monitors!(nodes[1], 1);
3297                 let events = nodes[1].node.get_and_clear_pending_events();
3298                 assert_eq!(events.len(), 1);
3299                 match events[0] {
3300                         Event::PendingHTLCsForwardable { .. } => { },
3301                         _ => panic!("Unexpected event"),
3302                 };
3303                 // Deliberately don't process the pending fail-back so they all fail back at once after
3304                 // block connection just like the !deliver_bs_raa case
3305         }
3306
3307         let mut failed_htlcs = HashSet::new();
3308         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3309
3310         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3311         check_added_monitors!(nodes[1], 1);
3312         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3313
3314         let events = nodes[1].node.get_and_clear_pending_events();
3315         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3316         match events[0] {
3317                 Event::PaymentFailed { ref payment_hash, .. } => {
3318                         assert_eq!(*payment_hash, fourth_payment_hash);
3319                 },
3320                 _ => panic!("Unexpected event"),
3321         }
3322         if !deliver_bs_raa {
3323                 match events[1] {
3324                         Event::PendingHTLCsForwardable { .. } => { },
3325                         _ => panic!("Unexpected event"),
3326                 };
3327         }
3328         nodes[1].node.process_pending_htlc_forwards();
3329         check_added_monitors!(nodes[1], 1);
3330
3331         let events = nodes[1].node.get_and_clear_pending_msg_events();
3332         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3333         match events[if deliver_bs_raa { 1 } else { 0 }] {
3334                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3335                 _ => panic!("Unexpected event"),
3336         }
3337         match events[if deliver_bs_raa { 2 } else { 1 }] {
3338                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3339                         assert_eq!(channel_id, chan_2.2);
3340                         assert_eq!(data.as_str(), "Commitment or closing transaction was confirmed on chain.");
3341                 },
3342                 _ => panic!("Unexpected event"),
3343         }
3344         if deliver_bs_raa {
3345                 match events[0] {
3346                         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, .. } } => {
3347                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3348                                 assert_eq!(update_add_htlcs.len(), 1);
3349                                 assert!(update_fulfill_htlcs.is_empty());
3350                                 assert!(update_fail_htlcs.is_empty());
3351                                 assert!(update_fail_malformed_htlcs.is_empty());
3352                         },
3353                         _ => panic!("Unexpected event"),
3354                 }
3355         }
3356         match events[if deliver_bs_raa { 3 } else { 2 }] {
3357                 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, .. } } => {
3358                         assert!(update_add_htlcs.is_empty());
3359                         assert_eq!(update_fail_htlcs.len(), 3);
3360                         assert!(update_fulfill_htlcs.is_empty());
3361                         assert!(update_fail_malformed_htlcs.is_empty());
3362                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3363
3364                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3365                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3366                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3367
3368                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3369
3370                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3371                         // If we delivered B's RAA we got an unknown preimage error, not something
3372                         // that we should update our routing table for.
3373                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3374                         for event in events {
3375                                 match event {
3376                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3377                                         _ => panic!("Unexpected event"),
3378                                 }
3379                         }
3380                         let events = nodes[0].node.get_and_clear_pending_events();
3381                         assert_eq!(events.len(), 3);
3382                         match events[0] {
3383                                 Event::PaymentFailed { ref payment_hash, .. } => {
3384                                         assert!(failed_htlcs.insert(payment_hash.0));
3385                                 },
3386                                 _ => panic!("Unexpected event"),
3387                         }
3388                         match events[1] {
3389                                 Event::PaymentFailed { ref payment_hash, .. } => {
3390                                         assert!(failed_htlcs.insert(payment_hash.0));
3391                                 },
3392                                 _ => panic!("Unexpected event"),
3393                         }
3394                         match events[2] {
3395                                 Event::PaymentFailed { ref payment_hash, .. } => {
3396                                         assert!(failed_htlcs.insert(payment_hash.0));
3397                                 },
3398                                 _ => panic!("Unexpected event"),
3399                         }
3400                 },
3401                 _ => panic!("Unexpected event"),
3402         }
3403
3404         assert!(failed_htlcs.contains(&first_payment_hash.0));
3405         assert!(failed_htlcs.contains(&second_payment_hash.0));
3406         assert!(failed_htlcs.contains(&third_payment_hash.0));
3407 }
3408
3409 #[test]
3410 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3411         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3412         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3413         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3414         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3415 }
3416
3417 #[test]
3418 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3419         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3420         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3421         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3422         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3423 }
3424
3425 #[test]
3426 fn fail_backward_pending_htlc_upon_channel_failure() {
3427         let chanmon_cfgs = create_chanmon_cfgs(2);
3428         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3429         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3430         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3431         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3432         let logger = test_utils::TestLogger::new();
3433
3434         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3435         {
3436                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1]);
3437                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3438                 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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3439                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3440                 check_added_monitors!(nodes[0], 1);
3441
3442                 let payment_event = {
3443                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3444                         assert_eq!(events.len(), 1);
3445                         SendEvent::from_event(events.remove(0))
3446                 };
3447                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3448                 assert_eq!(payment_event.msgs.len(), 1);
3449         }
3450
3451         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3452         let (_, failed_payment_hash, failed_payment_secret) = get_payment_preimage_hash!(nodes[1]);
3453         {
3454                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3455                 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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3456                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3457                 check_added_monitors!(nodes[0], 0);
3458
3459                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3460         }
3461
3462         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3463         {
3464                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[0]);
3465
3466                 let secp_ctx = Secp256k1::new();
3467                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3468                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3469                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3470                 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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3471                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3472                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3473                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3474
3475                 // Send a 0-msat update_add_htlc to fail the channel.
3476                 let update_add_htlc = msgs::UpdateAddHTLC {
3477                         channel_id: chan.2,
3478                         htlc_id: 0,
3479                         amount_msat: 0,
3480                         payment_hash,
3481                         cltv_expiry,
3482                         onion_routing_packet,
3483                 };
3484                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3485         }
3486
3487         // Check that Alice fails backward the pending HTLC from the second payment.
3488         expect_payment_failed!(nodes[0], failed_payment_hash, true);
3489         check_closed_broadcast!(nodes[0], true);
3490         check_added_monitors!(nodes[0], 1);
3491 }
3492
3493 #[test]
3494 fn test_htlc_ignore_latest_remote_commitment() {
3495         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3496         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3497         let chanmon_cfgs = create_chanmon_cfgs(2);
3498         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3499         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3500         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3501         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3502
3503         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3504         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3505         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3506         check_closed_broadcast!(nodes[0], true);
3507         check_added_monitors!(nodes[0], 1);
3508
3509         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3510         assert_eq!(node_txn.len(), 3);
3511         assert_eq!(node_txn[0], node_txn[1]);
3512
3513         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3514         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3515         check_closed_broadcast!(nodes[1], true);
3516         check_added_monitors!(nodes[1], 1);
3517
3518         // Duplicate the connect_block call since this may happen due to other listeners
3519         // registering new transactions
3520         header.prev_blockhash = header.block_hash();
3521         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3522 }
3523
3524 #[test]
3525 fn test_force_close_fail_back() {
3526         // Check which HTLCs are failed-backwards on channel force-closure
3527         let chanmon_cfgs = create_chanmon_cfgs(3);
3528         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3529         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3530         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3531         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3532         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3533         let logger = test_utils::TestLogger::new();
3534
3535         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
3536
3537         let mut payment_event = {
3538                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3539                 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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, 42, &logger).unwrap();
3540                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3541                 check_added_monitors!(nodes[0], 1);
3542
3543                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3544                 assert_eq!(events.len(), 1);
3545                 SendEvent::from_event(events.remove(0))
3546         };
3547
3548         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3549         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3550
3551         expect_pending_htlcs_forwardable!(nodes[1]);
3552
3553         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3554         assert_eq!(events_2.len(), 1);
3555         payment_event = SendEvent::from_event(events_2.remove(0));
3556         assert_eq!(payment_event.msgs.len(), 1);
3557
3558         check_added_monitors!(nodes[1], 1);
3559         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3560         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3561         check_added_monitors!(nodes[2], 1);
3562         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3563
3564         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3565         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3566         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3567
3568         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3569         check_closed_broadcast!(nodes[2], true);
3570         check_added_monitors!(nodes[2], 1);
3571         let tx = {
3572                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3573                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3574                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3575                 // back to nodes[1] upon timeout otherwise.
3576                 assert_eq!(node_txn.len(), 1);
3577                 node_txn.remove(0)
3578         };
3579
3580         mine_transaction(&nodes[1], &tx);
3581
3582         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3583         check_closed_broadcast!(nodes[1], true);
3584         check_added_monitors!(nodes[1], 1);
3585
3586         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3587         {
3588                 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3589                 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3590                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3591         }
3592         mine_transaction(&nodes[2], &tx);
3593         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3594         assert_eq!(node_txn.len(), 1);
3595         assert_eq!(node_txn[0].input.len(), 1);
3596         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3597         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3598         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3599
3600         check_spends!(node_txn[0], tx);
3601 }
3602
3603 #[test]
3604 fn test_dup_events_on_peer_disconnect() {
3605         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3606         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3607         // as we used to generate the event immediately upon receipt of the payment preimage in the
3608         // update_fulfill_htlc message.
3609
3610         let chanmon_cfgs = create_chanmon_cfgs(2);
3611         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3612         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3613         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3614         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3615
3616         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3617
3618         assert!(nodes[1].node.claim_funds(payment_preimage));
3619         check_added_monitors!(nodes[1], 1);
3620         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3621         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3622         expect_payment_sent!(nodes[0], payment_preimage);
3623
3624         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3625         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3626
3627         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3628         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3629 }
3630
3631 #[test]
3632 fn test_simple_peer_disconnect() {
3633         // Test that we can reconnect when there are no lost messages
3634         let chanmon_cfgs = create_chanmon_cfgs(3);
3635         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3636         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3637         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3638         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3639         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3640
3641         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3642         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3643         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3644
3645         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3646         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3647         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3648         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3649
3650         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3651         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3652         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3653
3654         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3655         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3656         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3657         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3658
3659         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3660         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3661
3662         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3663         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3664
3665         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3666         {
3667                 let events = nodes[0].node.get_and_clear_pending_events();
3668                 assert_eq!(events.len(), 2);
3669                 match events[0] {
3670                         Event::PaymentSent { payment_preimage } => {
3671                                 assert_eq!(payment_preimage, payment_preimage_3);
3672                         },
3673                         _ => panic!("Unexpected event"),
3674                 }
3675                 match events[1] {
3676                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3677                                 assert_eq!(payment_hash, payment_hash_5);
3678                                 assert!(rejected_by_dest);
3679                         },
3680                         _ => panic!("Unexpected event"),
3681                 }
3682         }
3683
3684         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3685         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3686 }
3687
3688 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3689         // Test that we can reconnect when in-flight HTLC updates get dropped
3690         let chanmon_cfgs = create_chanmon_cfgs(2);
3691         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3692         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3693         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3694
3695         let mut as_funding_locked = None;
3696         if messages_delivered == 0 {
3697                 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3698                 as_funding_locked = Some(funding_locked);
3699                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3700                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3701                 // it before the channel_reestablish message.
3702         } else {
3703                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3704         }
3705
3706         let (payment_preimage_1, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[1]);
3707
3708         let logger = test_utils::TestLogger::new();
3709         let payment_event = {
3710                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3711                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3712                         &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3713                         &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3714                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3715                 check_added_monitors!(nodes[0], 1);
3716
3717                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3718                 assert_eq!(events.len(), 1);
3719                 SendEvent::from_event(events.remove(0))
3720         };
3721         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3722
3723         if messages_delivered < 2 {
3724                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3725         } else {
3726                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3727                 if messages_delivered >= 3 {
3728                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3729                         check_added_monitors!(nodes[1], 1);
3730                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3731
3732                         if messages_delivered >= 4 {
3733                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3734                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3735                                 check_added_monitors!(nodes[0], 1);
3736
3737                                 if messages_delivered >= 5 {
3738                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3739                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3740                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3741                                         check_added_monitors!(nodes[0], 1);
3742
3743                                         if messages_delivered >= 6 {
3744                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3745                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3746                                                 check_added_monitors!(nodes[1], 1);
3747                                         }
3748                                 }
3749                         }
3750                 }
3751         }
3752
3753         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3754         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3755         if messages_delivered < 3 {
3756                 if simulate_broken_lnd {
3757                         // lnd has a long-standing bug where they send a funding_locked prior to a
3758                         // channel_reestablish if you reconnect prior to funding_locked time.
3759                         //
3760                         // Here we simulate that behavior, delivering a funding_locked immediately on
3761                         // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3762                         // in `reconnect_nodes` but we currently don't fail based on that.
3763                         //
3764                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3765                         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3766                 }
3767                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3768                 // received on either side, both sides will need to resend them.
3769                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3770         } else if messages_delivered == 3 {
3771                 // nodes[0] still wants its RAA + commitment_signed
3772                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3773         } else if messages_delivered == 4 {
3774                 // nodes[0] still wants its commitment_signed
3775                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3776         } else if messages_delivered == 5 {
3777                 // nodes[1] still wants its final RAA
3778                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3779         } else if messages_delivered == 6 {
3780                 // Everything was delivered...
3781                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3782         }
3783
3784         let events_1 = nodes[1].node.get_and_clear_pending_events();
3785         assert_eq!(events_1.len(), 1);
3786         match events_1[0] {
3787                 Event::PendingHTLCsForwardable { .. } => { },
3788                 _ => panic!("Unexpected event"),
3789         };
3790
3791         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3792         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3793         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3794
3795         nodes[1].node.process_pending_htlc_forwards();
3796
3797         let events_2 = nodes[1].node.get_and_clear_pending_events();
3798         assert_eq!(events_2.len(), 1);
3799         match events_2[0] {
3800                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3801                         assert_eq!(payment_hash_1, *payment_hash);
3802                         assert_eq!(amt, 1000000);
3803                         match &purpose {
3804                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3805                                         assert!(payment_preimage.is_none());
3806                                         assert_eq!(payment_secret_1, *payment_secret);
3807                                 },
3808                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3809                         }
3810                 },
3811                 _ => panic!("Unexpected event"),
3812         }
3813
3814         nodes[1].node.claim_funds(payment_preimage_1);
3815         check_added_monitors!(nodes[1], 1);
3816
3817         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3818         assert_eq!(events_3.len(), 1);
3819         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3820                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3821                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3822                         assert!(updates.update_add_htlcs.is_empty());
3823                         assert!(updates.update_fail_htlcs.is_empty());
3824                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3825                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3826                         assert!(updates.update_fee.is_none());
3827                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3828                 },
3829                 _ => panic!("Unexpected event"),
3830         };
3831
3832         if messages_delivered >= 1 {
3833                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3834
3835                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3836                 assert_eq!(events_4.len(), 1);
3837                 match events_4[0] {
3838                         Event::PaymentSent { ref payment_preimage } => {
3839                                 assert_eq!(payment_preimage_1, *payment_preimage);
3840                         },
3841                         _ => panic!("Unexpected event"),
3842                 }
3843
3844                 if messages_delivered >= 2 {
3845                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3846                         check_added_monitors!(nodes[0], 1);
3847                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3848
3849                         if messages_delivered >= 3 {
3850                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3851                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3852                                 check_added_monitors!(nodes[1], 1);
3853
3854                                 if messages_delivered >= 4 {
3855                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3856                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3857                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3858                                         check_added_monitors!(nodes[1], 1);
3859
3860                                         if messages_delivered >= 5 {
3861                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3862                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3863                                                 check_added_monitors!(nodes[0], 1);
3864                                         }
3865                                 }
3866                         }
3867                 }
3868         }
3869
3870         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3871         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3872         if messages_delivered < 2 {
3873                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3874                 if messages_delivered < 1 {
3875                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3876                         assert_eq!(events_4.len(), 1);
3877                         match events_4[0] {
3878                                 Event::PaymentSent { ref payment_preimage } => {
3879                                         assert_eq!(payment_preimage_1, *payment_preimage);
3880                                 },
3881                                 _ => panic!("Unexpected event"),
3882                         }
3883                 } else {
3884                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3885                 }
3886         } else if messages_delivered == 2 {
3887                 // nodes[0] still wants its RAA + commitment_signed
3888                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3889         } else if messages_delivered == 3 {
3890                 // nodes[0] still wants its commitment_signed
3891                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3892         } else if messages_delivered == 4 {
3893                 // nodes[1] still wants its final RAA
3894                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3895         } else if messages_delivered == 5 {
3896                 // Everything was delivered...
3897                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3898         }
3899
3900         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3901         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3902         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3903
3904         // Channel should still work fine...
3905         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3906         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3907                 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3908                 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3909         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3910         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3911 }
3912
3913 #[test]
3914 fn test_drop_messages_peer_disconnect_a() {
3915         do_test_drop_messages_peer_disconnect(0, true);
3916         do_test_drop_messages_peer_disconnect(0, false);
3917         do_test_drop_messages_peer_disconnect(1, false);
3918         do_test_drop_messages_peer_disconnect(2, false);
3919 }
3920
3921 #[test]
3922 fn test_drop_messages_peer_disconnect_b() {
3923         do_test_drop_messages_peer_disconnect(3, false);
3924         do_test_drop_messages_peer_disconnect(4, false);
3925         do_test_drop_messages_peer_disconnect(5, false);
3926         do_test_drop_messages_peer_disconnect(6, false);
3927 }
3928
3929 #[test]
3930 fn test_funding_peer_disconnect() {
3931         // Test that we can lock in our funding tx while disconnected
3932         let chanmon_cfgs = create_chanmon_cfgs(2);
3933         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3934         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3935         let persister: test_utils::TestPersister;
3936         let new_chain_monitor: test_utils::TestChainMonitor;
3937         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3938         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3939         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3940
3941         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3942         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3943
3944         confirm_transaction(&nodes[0], &tx);
3945         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3946         assert_eq!(events_1.len(), 1);
3947         match events_1[0] {
3948                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3949                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3950                 },
3951                 _ => panic!("Unexpected event"),
3952         }
3953
3954         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3955
3956         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3957         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3958
3959         confirm_transaction(&nodes[1], &tx);
3960         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3961         assert_eq!(events_2.len(), 2);
3962         let funding_locked = match events_2[0] {
3963                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3964                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3965                         msg.clone()
3966                 },
3967                 _ => panic!("Unexpected event"),
3968         };
3969         let bs_announcement_sigs = match events_2[1] {
3970                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3971                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3972                         msg.clone()
3973                 },
3974                 _ => panic!("Unexpected event"),
3975         };
3976
3977         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3978
3979         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3980         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3981         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3982         assert_eq!(events_3.len(), 2);
3983         let as_announcement_sigs = match events_3[0] {
3984                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3985                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3986                         msg.clone()
3987                 },
3988                 _ => panic!("Unexpected event"),
3989         };
3990         let (as_announcement, as_update) = match events_3[1] {
3991                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3992                         (msg.clone(), update_msg.clone())
3993                 },
3994                 _ => panic!("Unexpected event"),
3995         };
3996
3997         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3998         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3999         assert_eq!(events_4.len(), 1);
4000         let (_, bs_update) = match events_4[0] {
4001                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
4002                         (msg.clone(), update_msg.clone())
4003                 },
4004                 _ => panic!("Unexpected event"),
4005         };
4006
4007         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
4008         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4009         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4010
4011         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4012         let logger = test_utils::TestLogger::new();
4013         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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
4014         let (payment_preimage, _, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
4015         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
4016
4017         // Check that after deserialization and reconnection we can still generate an identical
4018         // channel_announcement from the cached signatures.
4019         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4020
4021         let nodes_0_serialized = nodes[0].node.encode();
4022         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4023         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4024
4025         persister = test_utils::TestPersister::new();
4026         let keys_manager = &chanmon_cfgs[0].keys_manager;
4027         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), nodes[0].logger, node_cfgs[0].fee_estimator, &persister, keys_manager);
4028         nodes[0].chain_monitor = &new_chain_monitor;
4029         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4030         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4031                 &mut chan_0_monitor_read, keys_manager).unwrap();
4032         assert!(chan_0_monitor_read.is_empty());
4033
4034         let mut nodes_0_read = &nodes_0_serialized[..];
4035         let (_, nodes_0_deserialized_tmp) = {
4036                 let mut channel_monitors = HashMap::new();
4037                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4038                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4039                         default_config: UserConfig::default(),
4040                         keys_manager,
4041                         fee_estimator: node_cfgs[0].fee_estimator,
4042                         chain_monitor: nodes[0].chain_monitor,
4043                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4044                         logger: nodes[0].logger,
4045                         channel_monitors,
4046                 }).unwrap()
4047         };
4048         nodes_0_deserialized = nodes_0_deserialized_tmp;
4049         assert!(nodes_0_read.is_empty());
4050
4051         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4052         nodes[0].node = &nodes_0_deserialized;
4053         check_added_monitors!(nodes[0], 1);
4054
4055         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4056
4057         // as_announcement should be re-generated exactly by broadcast_node_announcement.
4058         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4059         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4060         let mut found_announcement = false;
4061         for event in msgs.iter() {
4062                 match event {
4063                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4064                                 if *msg == as_announcement { found_announcement = true; }
4065                         },
4066                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4067                         _ => panic!("Unexpected event"),
4068                 }
4069         }
4070         assert!(found_announcement);
4071 }
4072
4073 #[test]
4074 fn test_drop_messages_peer_disconnect_dual_htlc() {
4075         // Test that we can handle reconnecting when both sides of a channel have pending
4076         // commitment_updates when we disconnect.
4077         let chanmon_cfgs = create_chanmon_cfgs(2);
4078         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4079         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4080         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4081         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4082         let logger = test_utils::TestLogger::new();
4083
4084         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4085
4086         // Now try to send a second payment which will fail to send
4087         let (payment_preimage_2, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
4088         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4089         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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
4090         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4091         check_added_monitors!(nodes[0], 1);
4092
4093         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4094         assert_eq!(events_1.len(), 1);
4095         match events_1[0] {
4096                 MessageSendEvent::UpdateHTLCs { .. } => {},
4097                 _ => panic!("Unexpected event"),
4098         }
4099
4100         assert!(nodes[1].node.claim_funds(payment_preimage_1));
4101         check_added_monitors!(nodes[1], 1);
4102
4103         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4104         assert_eq!(events_2.len(), 1);
4105         match events_2[0] {
4106                 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 } } => {
4107                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4108                         assert!(update_add_htlcs.is_empty());
4109                         assert_eq!(update_fulfill_htlcs.len(), 1);
4110                         assert!(update_fail_htlcs.is_empty());
4111                         assert!(update_fail_malformed_htlcs.is_empty());
4112                         assert!(update_fee.is_none());
4113
4114                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4115                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4116                         assert_eq!(events_3.len(), 1);
4117                         match events_3[0] {
4118                                 Event::PaymentSent { ref payment_preimage } => {
4119                                         assert_eq!(*payment_preimage, payment_preimage_1);
4120                                 },
4121                                 _ => panic!("Unexpected event"),
4122                         }
4123
4124                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4125                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4126                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4127                         check_added_monitors!(nodes[0], 1);
4128                 },
4129                 _ => panic!("Unexpected event"),
4130         }
4131
4132         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4133         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4134
4135         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4136         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4137         assert_eq!(reestablish_1.len(), 1);
4138         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4139         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4140         assert_eq!(reestablish_2.len(), 1);
4141
4142         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4143         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4144         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4145         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4146
4147         assert!(as_resp.0.is_none());
4148         assert!(bs_resp.0.is_none());
4149
4150         assert!(bs_resp.1.is_none());
4151         assert!(bs_resp.2.is_none());
4152
4153         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4154
4155         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4156         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4157         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4158         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4159         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4160         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4161         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4162         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4163         // No commitment_signed so get_event_msg's assert(len == 1) passes
4164         check_added_monitors!(nodes[1], 1);
4165
4166         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4167         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4168         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4169         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4170         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4171         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4172         assert!(bs_second_commitment_signed.update_fee.is_none());
4173         check_added_monitors!(nodes[1], 1);
4174
4175         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4176         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4177         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4178         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4179         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4180         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4181         assert!(as_commitment_signed.update_fee.is_none());
4182         check_added_monitors!(nodes[0], 1);
4183
4184         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4185         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4186         // No commitment_signed so get_event_msg's assert(len == 1) passes
4187         check_added_monitors!(nodes[0], 1);
4188
4189         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4190         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4191         // No commitment_signed so get_event_msg's assert(len == 1) passes
4192         check_added_monitors!(nodes[1], 1);
4193
4194         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4195         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4196         check_added_monitors!(nodes[1], 1);
4197
4198         expect_pending_htlcs_forwardable!(nodes[1]);
4199
4200         let events_5 = nodes[1].node.get_and_clear_pending_events();
4201         assert_eq!(events_5.len(), 1);
4202         match events_5[0] {
4203                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4204                         assert_eq!(payment_hash_2, *payment_hash);
4205                         match &purpose {
4206                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4207                                         assert!(payment_preimage.is_none());
4208                                         assert_eq!(payment_secret_2, *payment_secret);
4209                                 },
4210                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4211                         }
4212                 },
4213                 _ => panic!("Unexpected event"),
4214         }
4215
4216         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4217         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4218         check_added_monitors!(nodes[0], 1);
4219
4220         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4221 }
4222
4223 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4224         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4225         // to avoid our counterparty failing the channel.
4226         let chanmon_cfgs = create_chanmon_cfgs(2);
4227         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4228         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4229         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4230
4231         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4232         let logger = test_utils::TestLogger::new();
4233
4234         let our_payment_hash = if send_partial_mpp {
4235                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4236                 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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4237                 let (_, our_payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[1]);
4238                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4239                 // indicates there are more HTLCs coming.
4240                 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.
4241                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height, &None).unwrap();
4242                 check_added_monitors!(nodes[0], 1);
4243                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4244                 assert_eq!(events.len(), 1);
4245                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4246                 // hop should *not* yet generate any PaymentReceived event(s).
4247                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4248                 our_payment_hash
4249         } else {
4250                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4251         };
4252
4253         let mut block = Block {
4254                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4255                 txdata: vec![],
4256         };
4257         connect_block(&nodes[0], &block);
4258         connect_block(&nodes[1], &block);
4259         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4260         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4261                 block.header.prev_blockhash = block.block_hash();
4262                 connect_block(&nodes[0], &block);
4263                 connect_block(&nodes[1], &block);
4264         }
4265
4266         expect_pending_htlcs_forwardable!(nodes[1]);
4267
4268         check_added_monitors!(nodes[1], 1);
4269         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4270         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4271         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4272         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4273         assert!(htlc_timeout_updates.update_fee.is_none());
4274
4275         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4276         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4277         // 100_000 msat as u64, followed by the height at which we failed back above
4278         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4279         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4280         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4281 }
4282
4283 #[test]
4284 fn test_htlc_timeout() {
4285         do_test_htlc_timeout(true);
4286         do_test_htlc_timeout(false);
4287 }
4288
4289 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4290         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4291         let chanmon_cfgs = create_chanmon_cfgs(3);
4292         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4293         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4294         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4295         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4296         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4297
4298         // Make sure all nodes are at the same starting height
4299         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4300         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4301         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4302
4303         let logger = test_utils::TestLogger::new();
4304
4305         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4306         let (_, first_payment_hash, first_payment_secret) = get_payment_preimage_hash!(nodes[2]);
4307         {
4308                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4309                 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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4310                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4311         }
4312         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4313         check_added_monitors!(nodes[1], 1);
4314
4315         // Now attempt to route a second payment, which should be placed in the holding cell
4316         let (_, second_payment_hash, second_payment_secret) = get_payment_preimage_hash!(nodes[2]);
4317         if forwarded_htlc {
4318                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4319                 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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4320                 nodes[0].node.send_payment(&route, second_payment_hash, &Some(first_payment_secret)).unwrap();
4321                 check_added_monitors!(nodes[0], 1);
4322                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4323                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4324                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4325                 expect_pending_htlcs_forwardable!(nodes[1]);
4326                 check_added_monitors!(nodes[1], 0);
4327         } else {
4328                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4329                 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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4330                 nodes[1].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4331                 check_added_monitors!(nodes[1], 0);
4332         }
4333
4334         connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4335         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4336         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4337         connect_blocks(&nodes[1], 1);
4338
4339         if forwarded_htlc {
4340                 expect_pending_htlcs_forwardable!(nodes[1]);
4341                 check_added_monitors!(nodes[1], 1);
4342                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4343                 assert_eq!(fail_commit.len(), 1);
4344                 match fail_commit[0] {
4345                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4346                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4347                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4348                         },
4349                         _ => unreachable!(),
4350                 }
4351                 expect_payment_failed!(nodes[0], second_payment_hash, false);
4352                 expect_payment_failure_chan_update!(nodes[0], chan_2.0.contents.short_channel_id, false);
4353         } else {
4354                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4355         }
4356 }
4357
4358 #[test]
4359 fn test_holding_cell_htlc_add_timeouts() {
4360         do_test_holding_cell_htlc_add_timeouts(false);
4361         do_test_holding_cell_htlc_add_timeouts(true);
4362 }
4363
4364 #[test]
4365 fn test_invalid_channel_announcement() {
4366         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4367         let secp_ctx = Secp256k1::new();
4368         let chanmon_cfgs = create_chanmon_cfgs(2);
4369         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4370         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4371         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4372
4373         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4374
4375         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4376         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4377         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4378         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4379
4380         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 } );
4381
4382         let as_bitcoin_key = as_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4383         let bs_bitcoin_key = bs_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4384
4385         let as_network_key = nodes[0].node.get_our_node_id();
4386         let bs_network_key = nodes[1].node.get_our_node_id();
4387
4388         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4389
4390         let mut chan_announcement;
4391
4392         macro_rules! dummy_unsigned_msg {
4393                 () => {
4394                         msgs::UnsignedChannelAnnouncement {
4395                                 features: ChannelFeatures::known(),
4396                                 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4397                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4398                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4399                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4400                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4401                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4402                                 excess_data: Vec::new(),
4403                         };
4404                 }
4405         }
4406
4407         macro_rules! sign_msg {
4408                 ($unsigned_msg: expr) => {
4409                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4410                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_signer().inner.funding_key);
4411                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_signer().inner.funding_key);
4412                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4413                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4414                         chan_announcement = msgs::ChannelAnnouncement {
4415                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4416                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4417                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4418                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4419                                 contents: $unsigned_msg
4420                         }
4421                 }
4422         }
4423
4424         let unsigned_msg = dummy_unsigned_msg!();
4425         sign_msg!(unsigned_msg);
4426         assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4427         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 } );
4428
4429         // Configured with Network::Testnet
4430         let mut unsigned_msg = dummy_unsigned_msg!();
4431         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4432         sign_msg!(unsigned_msg);
4433         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4434
4435         let mut unsigned_msg = dummy_unsigned_msg!();
4436         unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4437         sign_msg!(unsigned_msg);
4438         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4439 }
4440
4441 #[test]
4442 fn test_no_txn_manager_serialize_deserialize() {
4443         let chanmon_cfgs = create_chanmon_cfgs(2);
4444         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4445         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4446         let logger: test_utils::TestLogger;
4447         let fee_estimator: test_utils::TestFeeEstimator;
4448         let persister: test_utils::TestPersister;
4449         let new_chain_monitor: test_utils::TestChainMonitor;
4450         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4451         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4452
4453         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4454
4455         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4456
4457         let nodes_0_serialized = nodes[0].node.encode();
4458         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4459         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4460
4461         logger = test_utils::TestLogger::new();
4462         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4463         persister = test_utils::TestPersister::new();
4464         let keys_manager = &chanmon_cfgs[0].keys_manager;
4465         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4466         nodes[0].chain_monitor = &new_chain_monitor;
4467         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4468         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4469                 &mut chan_0_monitor_read, keys_manager).unwrap();
4470         assert!(chan_0_monitor_read.is_empty());
4471
4472         let mut nodes_0_read = &nodes_0_serialized[..];
4473         let config = UserConfig::default();
4474         let (_, nodes_0_deserialized_tmp) = {
4475                 let mut channel_monitors = HashMap::new();
4476                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4477                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4478                         default_config: config,
4479                         keys_manager,
4480                         fee_estimator: &fee_estimator,
4481                         chain_monitor: nodes[0].chain_monitor,
4482                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4483                         logger: &logger,
4484                         channel_monitors,
4485                 }).unwrap()
4486         };
4487         nodes_0_deserialized = nodes_0_deserialized_tmp;
4488         assert!(nodes_0_read.is_empty());
4489
4490         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4491         nodes[0].node = &nodes_0_deserialized;
4492         assert_eq!(nodes[0].node.list_channels().len(), 1);
4493         check_added_monitors!(nodes[0], 1);
4494
4495         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4496         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4497         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4498         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4499
4500         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4501         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4502         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4503         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4504
4505         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4506         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4507         for node in nodes.iter() {
4508                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4509                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4510                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4511         }
4512
4513         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4514 }
4515
4516 #[test]
4517 fn test_dup_htlc_onchain_fails_on_reload() {
4518         // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
4519         // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
4520         // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
4521         // the ChannelMonitor tells it to.
4522         //
4523         // If, due to an on-chain event, an HTLC is failed/claimed, and then we serialize the
4524         // ChannelManager, we generally expect there not to be a duplicate HTLC fail/claim (eg via a
4525         // PaymentFailed event appearing). However, because we may not serialize the relevant
4526         // ChannelMonitor at the same time, this isn't strictly guaranteed. In order to provide this
4527         // consistency, the ChannelManager explicitly tracks pending-onchain-resolution outbound HTLCs
4528         // and de-duplicates ChannelMonitor events.
4529         //
4530         // This tests that explicit tracking behavior.
4531         let chanmon_cfgs = create_chanmon_cfgs(2);
4532         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4533         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4534         let persister: test_utils::TestPersister;
4535         let new_chain_monitor: test_utils::TestChainMonitor;
4536         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4537         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4538
4539         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4540
4541         // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
4542         // nodes[0].
4543         let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 10000000);
4544         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
4545         check_closed_broadcast!(nodes[0], true);
4546         check_added_monitors!(nodes[0], 1);
4547
4548         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4549         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4550
4551         // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
4552         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
4553         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4554         assert_eq!(node_txn.len(), 3);
4555         assert_eq!(node_txn[0], node_txn[1]);
4556
4557         assert!(nodes[1].node.claim_funds(payment_preimage));
4558         check_added_monitors!(nodes[1], 1);
4559
4560         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4561         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4562         check_closed_broadcast!(nodes[1], true);
4563         check_added_monitors!(nodes[1], 1);
4564         let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4565
4566         header.prev_blockhash = nodes[0].best_block_hash();
4567         connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4568
4569         // Serialize out the ChannelMonitor before connecting the on-chain claim transactions. This is
4570         // fairly normal behavior as ChannelMonitor(s) are often not re-serialized when on-chain events
4571         // happen, unlike ChannelManager which tends to be re-serialized after any relevant event(s).
4572         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4573         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4574
4575         header.prev_blockhash = nodes[0].best_block_hash();
4576         let claim_block = Block { header, txdata: claim_txn};
4577         connect_block(&nodes[0], &claim_block);
4578         expect_payment_sent!(nodes[0], payment_preimage);
4579
4580         // ChannelManagers generally get re-serialized after any relevant event(s). Since we just
4581         // connected a highly-relevant block, it likely gets serialized out now.
4582         let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
4583         nodes[0].node.write(&mut chan_manager_serialized).unwrap();
4584
4585         // Now reload nodes[0]...
4586         persister = test_utils::TestPersister::new();
4587         let keys_manager = &chanmon_cfgs[0].keys_manager;
4588         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), nodes[0].logger, node_cfgs[0].fee_estimator, &persister, keys_manager);
4589         nodes[0].chain_monitor = &new_chain_monitor;
4590         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4591         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4592                 &mut chan_0_monitor_read, keys_manager).unwrap();
4593         assert!(chan_0_monitor_read.is_empty());
4594
4595         let (_, nodes_0_deserialized_tmp) = {
4596                 let mut channel_monitors = HashMap::new();
4597                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4598                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
4599                         ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
4600                                 default_config: Default::default(),
4601                                 keys_manager,
4602                                 fee_estimator: node_cfgs[0].fee_estimator,
4603                                 chain_monitor: nodes[0].chain_monitor,
4604                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4605                                 logger: nodes[0].logger,
4606                                 channel_monitors,
4607                         }).unwrap()
4608         };
4609         nodes_0_deserialized = nodes_0_deserialized_tmp;
4610
4611         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4612         check_added_monitors!(nodes[0], 1);
4613         nodes[0].node = &nodes_0_deserialized;
4614
4615         // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
4616         // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
4617         // payment events should kick in, leaving us with no pending events here.
4618         let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
4619         nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
4620         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4621 }
4622
4623 #[test]
4624 fn test_manager_serialize_deserialize_events() {
4625         // This test makes sure the events field in ChannelManager survives de/serialization
4626         let chanmon_cfgs = create_chanmon_cfgs(2);
4627         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4628         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4629         let fee_estimator: test_utils::TestFeeEstimator;
4630         let persister: test_utils::TestPersister;
4631         let logger: test_utils::TestLogger;
4632         let new_chain_monitor: test_utils::TestChainMonitor;
4633         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4634         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4635
4636         // Start creating a channel, but stop right before broadcasting the funding transaction
4637         let channel_value = 100000;
4638         let push_msat = 10001;
4639         let a_flags = InitFeatures::known();
4640         let b_flags = InitFeatures::known();
4641         let node_a = nodes.remove(0);
4642         let node_b = nodes.remove(0);
4643         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4644         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()));
4645         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()));
4646
4647         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4648
4649         node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4650         check_added_monitors!(node_a, 0);
4651
4652         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()));
4653         {
4654                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4655                 assert_eq!(added_monitors.len(), 1);
4656                 assert_eq!(added_monitors[0].0, funding_output);
4657                 added_monitors.clear();
4658         }
4659
4660         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()));
4661         {
4662                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4663                 assert_eq!(added_monitors.len(), 1);
4664                 assert_eq!(added_monitors[0].0, funding_output);
4665                 added_monitors.clear();
4666         }
4667         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4668
4669         nodes.push(node_a);
4670         nodes.push(node_b);
4671
4672         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4673         let nodes_0_serialized = nodes[0].node.encode();
4674         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4675         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4676
4677         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4678         logger = test_utils::TestLogger::new();
4679         persister = test_utils::TestPersister::new();
4680         let keys_manager = &chanmon_cfgs[0].keys_manager;
4681         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4682         nodes[0].chain_monitor = &new_chain_monitor;
4683         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4684         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4685                 &mut chan_0_monitor_read, keys_manager).unwrap();
4686         assert!(chan_0_monitor_read.is_empty());
4687
4688         let mut nodes_0_read = &nodes_0_serialized[..];
4689         let config = UserConfig::default();
4690         let (_, nodes_0_deserialized_tmp) = {
4691                 let mut channel_monitors = HashMap::new();
4692                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4693                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4694                         default_config: config,
4695                         keys_manager,
4696                         fee_estimator: &fee_estimator,
4697                         chain_monitor: nodes[0].chain_monitor,
4698                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4699                         logger: &logger,
4700                         channel_monitors,
4701                 }).unwrap()
4702         };
4703         nodes_0_deserialized = nodes_0_deserialized_tmp;
4704         assert!(nodes_0_read.is_empty());
4705
4706         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4707
4708         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4709         nodes[0].node = &nodes_0_deserialized;
4710
4711         // After deserializing, make sure the funding_transaction is still held by the channel manager
4712         let events_4 = nodes[0].node.get_and_clear_pending_events();
4713         assert_eq!(events_4.len(), 0);
4714         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4715         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4716
4717         // Make sure the channel is functioning as though the de/serialization never happened
4718         assert_eq!(nodes[0].node.list_channels().len(), 1);
4719         check_added_monitors!(nodes[0], 1);
4720
4721         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4722         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4723         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4724         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4725
4726         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4727         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4728         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4729         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4730
4731         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4732         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4733         for node in nodes.iter() {
4734                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4735                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4736                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4737         }
4738
4739         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4740 }
4741
4742 #[test]
4743 fn test_simple_manager_serialize_deserialize() {
4744         let chanmon_cfgs = create_chanmon_cfgs(2);
4745         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4746         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4747         let logger: test_utils::TestLogger;
4748         let fee_estimator: test_utils::TestFeeEstimator;
4749         let persister: test_utils::TestPersister;
4750         let new_chain_monitor: test_utils::TestChainMonitor;
4751         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4752         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4753         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4754
4755         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4756         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4757
4758         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4759
4760         let nodes_0_serialized = nodes[0].node.encode();
4761         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4762         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4763
4764         logger = test_utils::TestLogger::new();
4765         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4766         persister = test_utils::TestPersister::new();
4767         let keys_manager = &chanmon_cfgs[0].keys_manager;
4768         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4769         nodes[0].chain_monitor = &new_chain_monitor;
4770         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4771         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4772                 &mut chan_0_monitor_read, keys_manager).unwrap();
4773         assert!(chan_0_monitor_read.is_empty());
4774
4775         let mut nodes_0_read = &nodes_0_serialized[..];
4776         let (_, nodes_0_deserialized_tmp) = {
4777                 let mut channel_monitors = HashMap::new();
4778                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4779                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4780                         default_config: UserConfig::default(),
4781                         keys_manager,
4782                         fee_estimator: &fee_estimator,
4783                         chain_monitor: nodes[0].chain_monitor,
4784                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4785                         logger: &logger,
4786                         channel_monitors,
4787                 }).unwrap()
4788         };
4789         nodes_0_deserialized = nodes_0_deserialized_tmp;
4790         assert!(nodes_0_read.is_empty());
4791
4792         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4793         nodes[0].node = &nodes_0_deserialized;
4794         check_added_monitors!(nodes[0], 1);
4795
4796         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4797
4798         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4799         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4800 }
4801
4802 #[test]
4803 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4804         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4805         let chanmon_cfgs = create_chanmon_cfgs(4);
4806         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4807         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4808         let logger: test_utils::TestLogger;
4809         let fee_estimator: test_utils::TestFeeEstimator;
4810         let persister: test_utils::TestPersister;
4811         let new_chain_monitor: test_utils::TestChainMonitor;
4812         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4813         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4814         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4815         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4816         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4817
4818         let mut node_0_stale_monitors_serialized = Vec::new();
4819         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4820                 let mut writer = test_utils::TestVecWriter(Vec::new());
4821                 monitor.1.write(&mut writer).unwrap();
4822                 node_0_stale_monitors_serialized.push(writer.0);
4823         }
4824
4825         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4826
4827         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4828         let nodes_0_serialized = nodes[0].node.encode();
4829
4830         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4831         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4832         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4833         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4834
4835         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4836         // nodes[3])
4837         let mut node_0_monitors_serialized = Vec::new();
4838         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4839                 let mut writer = test_utils::TestVecWriter(Vec::new());
4840                 monitor.1.write(&mut writer).unwrap();
4841                 node_0_monitors_serialized.push(writer.0);
4842         }
4843
4844         logger = test_utils::TestLogger::new();
4845         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4846         persister = test_utils::TestPersister::new();
4847         let keys_manager = &chanmon_cfgs[0].keys_manager;
4848         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4849         nodes[0].chain_monitor = &new_chain_monitor;
4850
4851
4852         let mut node_0_stale_monitors = Vec::new();
4853         for serialized in node_0_stale_monitors_serialized.iter() {
4854                 let mut read = &serialized[..];
4855                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4856                 assert!(read.is_empty());
4857                 node_0_stale_monitors.push(monitor);
4858         }
4859
4860         let mut node_0_monitors = Vec::new();
4861         for serialized in node_0_monitors_serialized.iter() {
4862                 let mut read = &serialized[..];
4863                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4864                 assert!(read.is_empty());
4865                 node_0_monitors.push(monitor);
4866         }
4867
4868         let mut nodes_0_read = &nodes_0_serialized[..];
4869         if let Err(msgs::DecodeError::InvalidValue) =
4870                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4871                 default_config: UserConfig::default(),
4872                 keys_manager,
4873                 fee_estimator: &fee_estimator,
4874                 chain_monitor: nodes[0].chain_monitor,
4875                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4876                 logger: &logger,
4877                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4878         }) { } else {
4879                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4880         };
4881
4882         let mut nodes_0_read = &nodes_0_serialized[..];
4883         let (_, nodes_0_deserialized_tmp) =
4884                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4885                 default_config: UserConfig::default(),
4886                 keys_manager,
4887                 fee_estimator: &fee_estimator,
4888                 chain_monitor: nodes[0].chain_monitor,
4889                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4890                 logger: &logger,
4891                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4892         }).unwrap();
4893         nodes_0_deserialized = nodes_0_deserialized_tmp;
4894         assert!(nodes_0_read.is_empty());
4895
4896         { // Channel close should result in a commitment tx
4897                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4898                 assert_eq!(txn.len(), 1);
4899                 check_spends!(txn[0], funding_tx);
4900                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4901         }
4902
4903         for monitor in node_0_monitors.drain(..) {
4904                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4905                 check_added_monitors!(nodes[0], 1);
4906         }
4907         nodes[0].node = &nodes_0_deserialized;
4908
4909         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4910         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4911         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4912         //... and we can even still claim the payment!
4913         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4914
4915         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4916         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4917         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4918         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4919         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4920         assert_eq!(msg_events.len(), 1);
4921         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4922                 match action {
4923                         &ErrorAction::SendErrorMessage { ref msg } => {
4924                                 assert_eq!(msg.channel_id, channel_id);
4925                         },
4926                         _ => panic!("Unexpected event!"),
4927                 }
4928         }
4929 }
4930
4931 macro_rules! check_spendable_outputs {
4932         ($node: expr, $keysinterface: expr) => {
4933                 {
4934                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4935                         let mut txn = Vec::new();
4936                         let mut all_outputs = Vec::new();
4937                         let secp_ctx = Secp256k1::new();
4938                         for event in events.drain(..) {
4939                                 match event {
4940                                         Event::SpendableOutputs { mut outputs } => {
4941                                                 for outp in outputs.drain(..) {
4942                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4943                                                         all_outputs.push(outp);
4944                                                 }
4945                                         },
4946                                         _ => panic!("Unexpected event"),
4947                                 };
4948                         }
4949                         if all_outputs.len() > 1 {
4950                                 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) {
4951                                         txn.push(tx);
4952                                 }
4953                         }
4954                         txn
4955                 }
4956         }
4957 }
4958
4959 #[test]
4960 fn test_claim_sizeable_push_msat() {
4961         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4962         let chanmon_cfgs = create_chanmon_cfgs(2);
4963         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4964         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4965         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4966
4967         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4968         nodes[1].node.force_close_channel(&chan.2).unwrap();
4969         check_closed_broadcast!(nodes[1], true);
4970         check_added_monitors!(nodes[1], 1);
4971         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4972         assert_eq!(node_txn.len(), 1);
4973         check_spends!(node_txn[0], chan.3);
4974         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
4975
4976         mine_transaction(&nodes[1], &node_txn[0]);
4977         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4978
4979         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4980         assert_eq!(spend_txn.len(), 1);
4981         assert_eq!(spend_txn[0].input.len(), 1);
4982         check_spends!(spend_txn[0], node_txn[0]);
4983         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4984 }
4985
4986 #[test]
4987 fn test_claim_on_remote_sizeable_push_msat() {
4988         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4989         // to_remote output is encumbered by a P2WPKH
4990         let chanmon_cfgs = create_chanmon_cfgs(2);
4991         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4992         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4993         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4994
4995         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4996         nodes[0].node.force_close_channel(&chan.2).unwrap();
4997         check_closed_broadcast!(nodes[0], true);
4998         check_added_monitors!(nodes[0], 1);
4999
5000         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5001         assert_eq!(node_txn.len(), 1);
5002         check_spends!(node_txn[0], chan.3);
5003         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
5004
5005         mine_transaction(&nodes[1], &node_txn[0]);
5006         check_closed_broadcast!(nodes[1], true);
5007         check_added_monitors!(nodes[1], 1);
5008         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5009
5010         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5011         assert_eq!(spend_txn.len(), 1);
5012         check_spends!(spend_txn[0], node_txn[0]);
5013 }
5014
5015 #[test]
5016 fn test_claim_on_remote_revoked_sizeable_push_msat() {
5017         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
5018         // to_remote output is encumbered by a P2WPKH
5019
5020         let chanmon_cfgs = create_chanmon_cfgs(2);
5021         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5022         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5023         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5024
5025         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
5026         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5027         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
5028         assert_eq!(revoked_local_txn[0].input.len(), 1);
5029         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
5030
5031         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5032         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5033         check_closed_broadcast!(nodes[1], true);
5034         check_added_monitors!(nodes[1], 1);
5035
5036         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5037         mine_transaction(&nodes[1], &node_txn[0]);
5038         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5039
5040         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5041         assert_eq!(spend_txn.len(), 3);
5042         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
5043         check_spends!(spend_txn[1], node_txn[0]);
5044         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
5045 }
5046
5047 #[test]
5048 fn test_static_spendable_outputs_preimage_tx() {
5049         let chanmon_cfgs = create_chanmon_cfgs(2);
5050         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5051         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5052         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5053
5054         // Create some initial channels
5055         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5056
5057         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5058
5059         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5060         assert_eq!(commitment_tx[0].input.len(), 1);
5061         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
5062
5063         // Settle A's commitment tx on B's chain
5064         assert!(nodes[1].node.claim_funds(payment_preimage));
5065         check_added_monitors!(nodes[1], 1);
5066         mine_transaction(&nodes[1], &commitment_tx[0]);
5067         check_added_monitors!(nodes[1], 1);
5068         let events = nodes[1].node.get_and_clear_pending_msg_events();
5069         match events[0] {
5070                 MessageSendEvent::UpdateHTLCs { .. } => {},
5071                 _ => panic!("Unexpected event"),
5072         }
5073         match events[1] {
5074                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5075                 _ => panic!("Unexepected event"),
5076         }
5077
5078         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
5079         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
5080         assert_eq!(node_txn.len(), 3);
5081         check_spends!(node_txn[0], commitment_tx[0]);
5082         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5083         check_spends!(node_txn[1], chan_1.3);
5084         check_spends!(node_txn[2], node_txn[1]);
5085
5086         mine_transaction(&nodes[1], &node_txn[0]);
5087         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5088
5089         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5090         assert_eq!(spend_txn.len(), 1);
5091         check_spends!(spend_txn[0], node_txn[0]);
5092 }
5093
5094 #[test]
5095 fn test_static_spendable_outputs_timeout_tx() {
5096         let chanmon_cfgs = create_chanmon_cfgs(2);
5097         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5098         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5099         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5100
5101         // Create some initial channels
5102         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5103
5104         // Rebalance the network a bit by relaying one payment through all the channels ...
5105         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5106
5107         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
5108
5109         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5110         assert_eq!(commitment_tx[0].input.len(), 1);
5111         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
5112
5113         // Settle A's commitment tx on B' chain
5114         mine_transaction(&nodes[1], &commitment_tx[0]);
5115         check_added_monitors!(nodes[1], 1);
5116         let events = nodes[1].node.get_and_clear_pending_msg_events();
5117         match events[0] {
5118                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5119                 _ => panic!("Unexpected event"),
5120         }
5121         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5122
5123         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
5124         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
5125         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
5126         check_spends!(node_txn[0], chan_1.3.clone());
5127         check_spends!(node_txn[1],  commitment_tx[0].clone());
5128         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5129
5130         mine_transaction(&nodes[1], &node_txn[1]);
5131         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5132         expect_payment_failed!(nodes[1], our_payment_hash, true);
5133
5134         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5135         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
5136         check_spends!(spend_txn[0], commitment_tx[0]);
5137         check_spends!(spend_txn[1], node_txn[1]);
5138         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
5139 }
5140
5141 #[test]
5142 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
5143         let chanmon_cfgs = create_chanmon_cfgs(2);
5144         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5145         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5146         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5147
5148         // Create some initial channels
5149         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5150
5151         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5152         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5153         assert_eq!(revoked_local_txn[0].input.len(), 1);
5154         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5155
5156         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5157
5158         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5159         check_closed_broadcast!(nodes[1], true);
5160         check_added_monitors!(nodes[1], 1);
5161
5162         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5163         assert_eq!(node_txn.len(), 2);
5164         assert_eq!(node_txn[0].input.len(), 2);
5165         check_spends!(node_txn[0], revoked_local_txn[0]);
5166
5167         mine_transaction(&nodes[1], &node_txn[0]);
5168         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5169
5170         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5171         assert_eq!(spend_txn.len(), 1);
5172         check_spends!(spend_txn[0], node_txn[0]);
5173 }
5174
5175 #[test]
5176 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5177         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5178         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
5179         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5180         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5181         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5182
5183         // Create some initial channels
5184         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5185
5186         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5187         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5188         assert_eq!(revoked_local_txn[0].input.len(), 1);
5189         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5190
5191         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5192
5193         // A will generate HTLC-Timeout from revoked commitment tx
5194         mine_transaction(&nodes[0], &revoked_local_txn[0]);
5195         check_closed_broadcast!(nodes[0], true);
5196         check_added_monitors!(nodes[0], 1);
5197         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5198
5199         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5200         assert_eq!(revoked_htlc_txn.len(), 2);
5201         check_spends!(revoked_htlc_txn[0], chan_1.3);
5202         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5203         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5204         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5205         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5206
5207         // B will generate justice tx from A's revoked commitment/HTLC tx
5208         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5209         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5210         check_closed_broadcast!(nodes[1], true);
5211         check_added_monitors!(nodes[1], 1);
5212
5213         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5214         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5215         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5216         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5217         // transactions next...
5218         assert_eq!(node_txn[0].input.len(), 3);
5219         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5220
5221         assert_eq!(node_txn[1].input.len(), 2);
5222         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5223         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5224                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5225         } else {
5226                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5227                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5228         }
5229
5230         assert_eq!(node_txn[2].input.len(), 1);
5231         check_spends!(node_txn[2], chan_1.3);
5232
5233         mine_transaction(&nodes[1], &node_txn[1]);
5234         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5235
5236         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5237         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5238         assert_eq!(spend_txn.len(), 1);
5239         assert_eq!(spend_txn[0].input.len(), 1);
5240         check_spends!(spend_txn[0], node_txn[1]);
5241 }
5242
5243 #[test]
5244 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5245         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5246         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5247         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5248         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5249         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5250
5251         // Create some initial channels
5252         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5253
5254         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5255         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5256         assert_eq!(revoked_local_txn[0].input.len(), 1);
5257         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5258
5259         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5260         assert_eq!(revoked_local_txn[0].output.len(), 2);
5261
5262         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5263
5264         // B will generate HTLC-Success from revoked commitment tx
5265         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5266         check_closed_broadcast!(nodes[1], true);
5267         check_added_monitors!(nodes[1], 1);
5268         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5269
5270         assert_eq!(revoked_htlc_txn.len(), 2);
5271         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5272         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5273         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5274
5275         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5276         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5277         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5278
5279         // A will generate justice tx from B's revoked commitment/HTLC tx
5280         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5281         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5282         check_closed_broadcast!(nodes[0], true);
5283         check_added_monitors!(nodes[0], 1);
5284
5285         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5286         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5287
5288         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5289         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5290         // transactions next...
5291         assert_eq!(node_txn[0].input.len(), 2);
5292         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5293         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5294                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5295         } else {
5296                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5297                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5298         }
5299
5300         assert_eq!(node_txn[1].input.len(), 1);
5301         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5302
5303         check_spends!(node_txn[2], chan_1.3);
5304
5305         mine_transaction(&nodes[0], &node_txn[1]);
5306         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5307
5308         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5309         // didn't try to generate any new transactions.
5310
5311         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5312         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5313         assert_eq!(spend_txn.len(), 3);
5314         assert_eq!(spend_txn[0].input.len(), 1);
5315         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5316         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5317         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5318         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5319 }
5320
5321 #[test]
5322 fn test_onchain_to_onchain_claim() {
5323         // Test that in case of channel closure, we detect the state of output and claim HTLC
5324         // on downstream peer's remote commitment tx.
5325         // First, have C claim an HTLC against its own latest commitment transaction.
5326         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5327         // channel.
5328         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5329         // gets broadcast.
5330
5331         let chanmon_cfgs = create_chanmon_cfgs(3);
5332         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5333         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5334         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5335
5336         // Create some initial channels
5337         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5338         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5339
5340         // Ensure all nodes are at the same height
5341         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5342         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5343         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5344         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5345
5346         // Rebalance the network a bit by relaying one payment through all the channels ...
5347         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5348         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5349
5350         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5351         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5352         check_spends!(commitment_tx[0], chan_2.3);
5353         nodes[2].node.claim_funds(payment_preimage);
5354         check_added_monitors!(nodes[2], 1);
5355         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5356         assert!(updates.update_add_htlcs.is_empty());
5357         assert!(updates.update_fail_htlcs.is_empty());
5358         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5359         assert!(updates.update_fail_malformed_htlcs.is_empty());
5360
5361         mine_transaction(&nodes[2], &commitment_tx[0]);
5362         check_closed_broadcast!(nodes[2], true);
5363         check_added_monitors!(nodes[2], 1);
5364
5365         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5366         assert_eq!(c_txn.len(), 3);
5367         assert_eq!(c_txn[0], c_txn[2]);
5368         assert_eq!(commitment_tx[0], c_txn[1]);
5369         check_spends!(c_txn[1], chan_2.3);
5370         check_spends!(c_txn[2], c_txn[1]);
5371         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5372         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5373         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5374         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5375
5376         // 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
5377         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5378         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5379         check_added_monitors!(nodes[1], 1);
5380         expect_payment_forwarded!(nodes[1], Some(1000), true);
5381         {
5382                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5383                 // ChannelMonitor: claim tx
5384                 assert_eq!(b_txn.len(), 1);
5385                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5386                 b_txn.clear();
5387         }
5388         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5389         assert_eq!(msg_events.len(), 3);
5390         check_added_monitors!(nodes[1], 1);
5391         match msg_events[0] {
5392                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5393                 _ => panic!("Unexpected event"),
5394         }
5395         match msg_events[1] {
5396                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5397                 _ => panic!("Unexpected event"),
5398         }
5399         match msg_events[2] {
5400                 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, .. } } => {
5401                         assert!(update_add_htlcs.is_empty());
5402                         assert!(update_fail_htlcs.is_empty());
5403                         assert_eq!(update_fulfill_htlcs.len(), 1);
5404                         assert!(update_fail_malformed_htlcs.is_empty());
5405                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5406                 },
5407                 _ => panic!("Unexpected event"),
5408         };
5409         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5410         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5411         mine_transaction(&nodes[1], &commitment_tx[0]);
5412         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5413         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5414         assert_eq!(b_txn.len(), 3);
5415         check_spends!(b_txn[1], chan_1.3);
5416         check_spends!(b_txn[2], b_txn[1]);
5417         check_spends!(b_txn[0], commitment_tx[0]);
5418         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5419         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5420         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5421
5422         check_closed_broadcast!(nodes[1], true);
5423         check_added_monitors!(nodes[1], 1);
5424 }
5425
5426 #[test]
5427 fn test_duplicate_payment_hash_one_failure_one_success() {
5428         // Topology : A --> B --> C --> D
5429         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5430         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5431         // we forward one of the payments onwards to D.
5432         let chanmon_cfgs = create_chanmon_cfgs(4);
5433         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5434         // When this test was written, the default base fee floated based on the HTLC count.
5435         // It is now fixed, so we simply set the fee to the expected value here.
5436         let mut config = test_default_channel_config();
5437         config.channel_options.forwarding_fee_base_msat = 196;
5438         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5439                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5440         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5441
5442         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5443         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5444         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5445
5446         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5447         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5448         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5449         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5450         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5451
5452         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5453
5454         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, 0).unwrap();
5455         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5456         // script push size limit so that the below script length checks match
5457         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5458         let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph.read().unwrap(),
5459                 &nodes[3].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 900000, TEST_FINAL_CLTV - 40, nodes[0].logger).unwrap();
5460         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5461
5462         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5463         assert_eq!(commitment_txn[0].input.len(), 1);
5464         check_spends!(commitment_txn[0], chan_2.3);
5465
5466         mine_transaction(&nodes[1], &commitment_txn[0]);
5467         check_closed_broadcast!(nodes[1], true);
5468         check_added_monitors!(nodes[1], 1);
5469         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5470
5471         let htlc_timeout_tx;
5472         { // Extract one of the two HTLC-Timeout transaction
5473                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5474                 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5475                 assert_eq!(node_txn.len(), 4);
5476                 check_spends!(node_txn[0], chan_2.3);
5477
5478                 check_spends!(node_txn[1], commitment_txn[0]);
5479                 assert_eq!(node_txn[1].input.len(), 1);
5480                 check_spends!(node_txn[2], commitment_txn[0]);
5481                 assert_eq!(node_txn[2].input.len(), 1);
5482                 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5483                 check_spends!(node_txn[3], commitment_txn[0]);
5484                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5485
5486                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5487                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5488                 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5489                 htlc_timeout_tx = node_txn[1].clone();
5490         }
5491
5492         nodes[2].node.claim_funds(our_payment_preimage);
5493         mine_transaction(&nodes[2], &commitment_txn[0]);
5494         check_added_monitors!(nodes[2], 2);
5495         let events = nodes[2].node.get_and_clear_pending_msg_events();
5496         match events[0] {
5497                 MessageSendEvent::UpdateHTLCs { .. } => {},
5498                 _ => panic!("Unexpected event"),
5499         }
5500         match events[1] {
5501                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5502                 _ => panic!("Unexepected event"),
5503         }
5504         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5505         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)
5506         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5507         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5508         assert_eq!(htlc_success_txn[0].input.len(), 1);
5509         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5510         assert_eq!(htlc_success_txn[1].input.len(), 1);
5511         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5512         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5513         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5514         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5515         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5516         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5517
5518         mine_transaction(&nodes[1], &htlc_timeout_tx);
5519         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5520         expect_pending_htlcs_forwardable!(nodes[1]);
5521         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5522         assert!(htlc_updates.update_add_htlcs.is_empty());
5523         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5524         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5525         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5526         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5527         check_added_monitors!(nodes[1], 1);
5528
5529         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5530         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5531         {
5532                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5533                 expect_payment_failure_chan_update!(nodes[0], chan_2.0.contents.short_channel_id, true);
5534         }
5535         expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5536
5537         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5538         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5539         // and nodes[2] fee) is rounded down and then claimed in full.
5540         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5541         expect_payment_forwarded!(nodes[1], Some(196*2), true);
5542         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5543         assert!(updates.update_add_htlcs.is_empty());
5544         assert!(updates.update_fail_htlcs.is_empty());
5545         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5546         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5547         assert!(updates.update_fail_malformed_htlcs.is_empty());
5548         check_added_monitors!(nodes[1], 1);
5549
5550         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5551         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5552
5553         let events = nodes[0].node.get_and_clear_pending_events();
5554         match events[0] {
5555                 Event::PaymentSent { ref payment_preimage } => {
5556                         assert_eq!(*payment_preimage, our_payment_preimage);
5557                 }
5558                 _ => panic!("Unexpected event"),
5559         }
5560 }
5561
5562 #[test]
5563 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5564         let chanmon_cfgs = create_chanmon_cfgs(2);
5565         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5566         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5567         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5568
5569         // Create some initial channels
5570         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5571
5572         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5573         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5574         assert_eq!(local_txn.len(), 1);
5575         assert_eq!(local_txn[0].input.len(), 1);
5576         check_spends!(local_txn[0], chan_1.3);
5577
5578         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5579         nodes[1].node.claim_funds(payment_preimage);
5580         check_added_monitors!(nodes[1], 1);
5581         mine_transaction(&nodes[1], &local_txn[0]);
5582         check_added_monitors!(nodes[1], 1);
5583         let events = nodes[1].node.get_and_clear_pending_msg_events();
5584         match events[0] {
5585                 MessageSendEvent::UpdateHTLCs { .. } => {},
5586                 _ => panic!("Unexpected event"),
5587         }
5588         match events[1] {
5589                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5590                 _ => panic!("Unexepected event"),
5591         }
5592         let node_tx = {
5593                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5594                 assert_eq!(node_txn.len(), 3);
5595                 assert_eq!(node_txn[0], node_txn[2]);
5596                 assert_eq!(node_txn[1], local_txn[0]);
5597                 assert_eq!(node_txn[0].input.len(), 1);
5598                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5599                 check_spends!(node_txn[0], local_txn[0]);
5600                 node_txn[0].clone()
5601         };
5602
5603         mine_transaction(&nodes[1], &node_tx);
5604         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5605
5606         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5607         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5608         assert_eq!(spend_txn.len(), 1);
5609         assert_eq!(spend_txn[0].input.len(), 1);
5610         check_spends!(spend_txn[0], node_tx);
5611         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5612 }
5613
5614 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5615         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5616         // unrevoked commitment transaction.
5617         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5618         // a remote RAA before they could be failed backwards (and combinations thereof).
5619         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5620         // use the same payment hashes.
5621         // Thus, we use a six-node network:
5622         //
5623         // A \         / E
5624         //    - C - D -
5625         // B /         \ F
5626         // And test where C fails back to A/B when D announces its latest commitment transaction
5627         let chanmon_cfgs = create_chanmon_cfgs(6);
5628         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5629         // When this test was written, the default base fee floated based on the HTLC count.
5630         // It is now fixed, so we simply set the fee to the expected value here.
5631         let mut config = test_default_channel_config();
5632         config.channel_options.forwarding_fee_base_msat = 196;
5633         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5634                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5635         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5636         let logger = test_utils::TestLogger::new();
5637
5638         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5639         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5640         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5641         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5642         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5643
5644         // Rebalance and check output sanity...
5645         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5646         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5647         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5648
5649         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5650         // 0th HTLC:
5651         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
5652         // 1st HTLC:
5653         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
5654         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5655         let our_node_id = &nodes[1].node.get_our_node_id();
5656         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5657         // 2nd HTLC:
5658         send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_1, nodes[5].node.create_inbound_payment_for_hash(payment_hash_1, None, 7200, 0).unwrap()); // not added < dust limit + HTLC tx fee
5659         // 3rd HTLC:
5660         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_2, nodes[5].node.create_inbound_payment_for_hash(payment_hash_2, None, 7200, 0).unwrap()); // not added < dust limit + HTLC tx fee
5661         // 4th HTLC:
5662         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5663         // 5th HTLC:
5664         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5665         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5666         // 6th HTLC:
5667         send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_3, nodes[5].node.create_inbound_payment_for_hash(payment_hash_3, None, 7200, 0).unwrap());
5668         // 7th HTLC:
5669         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_4, nodes[5].node.create_inbound_payment_for_hash(payment_hash_4, None, 7200, 0).unwrap());
5670
5671         // 8th HTLC:
5672         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5673         // 9th HTLC:
5674         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5675         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_5, nodes[5].node.create_inbound_payment_for_hash(payment_hash_5, None, 7200, 0).unwrap()); // not added < dust limit + HTLC tx fee
5676
5677         // 10th HTLC:
5678         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
5679         // 11th HTLC:
5680         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5681         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_6, nodes[5].node.create_inbound_payment_for_hash(payment_hash_6, None, 7200, 0).unwrap());
5682
5683         // Double-check that six of the new HTLC were added
5684         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5685         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5686         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5687         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5688
5689         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5690         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5691         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5692         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5693         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5694         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5695         check_added_monitors!(nodes[4], 0);
5696         expect_pending_htlcs_forwardable!(nodes[4]);
5697         check_added_monitors!(nodes[4], 1);
5698
5699         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5700         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5701         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5702         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5703         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5704         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5705
5706         // Fail 3rd below-dust and 7th above-dust HTLCs
5707         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5708         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5709         check_added_monitors!(nodes[5], 0);
5710         expect_pending_htlcs_forwardable!(nodes[5]);
5711         check_added_monitors!(nodes[5], 1);
5712
5713         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5714         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5715         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5716         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5717
5718         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5719
5720         expect_pending_htlcs_forwardable!(nodes[3]);
5721         check_added_monitors!(nodes[3], 1);
5722         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5723         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5724         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5725         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5726         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5727         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5728         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5729         if deliver_last_raa {
5730                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5731         } else {
5732                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5733         }
5734
5735         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5736         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5737         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5738         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5739         //
5740         // We now broadcast the latest commitment transaction, which *should* result in failures for
5741         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5742         // the non-broadcast above-dust HTLCs.
5743         //
5744         // Alternatively, we may broadcast the previous commitment transaction, which should only
5745         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5746         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5747
5748         if announce_latest {
5749                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5750         } else {
5751                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5752         }
5753         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5754         check_closed_broadcast!(nodes[2], true);
5755         expect_pending_htlcs_forwardable!(nodes[2]);
5756         check_added_monitors!(nodes[2], 3);
5757
5758         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5759         assert_eq!(cs_msgs.len(), 2);
5760         let mut a_done = false;
5761         for msg in cs_msgs {
5762                 match msg {
5763                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5764                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5765                                 // should be failed-backwards here.
5766                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5767                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5768                                         for htlc in &updates.update_fail_htlcs {
5769                                                 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 });
5770                                         }
5771                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5772                                         assert!(!a_done);
5773                                         a_done = true;
5774                                         &nodes[0]
5775                                 } else {
5776                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5777                                         for htlc in &updates.update_fail_htlcs {
5778                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5779                                         }
5780                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5781                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5782                                         &nodes[1]
5783                                 };
5784                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5785                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5786                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5787                                 if announce_latest {
5788                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5789                                         if *node_id == nodes[0].node.get_our_node_id() {
5790                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5791                                         }
5792                                 }
5793                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5794                         },
5795                         _ => panic!("Unexpected event"),
5796                 }
5797         }
5798
5799         let as_events = nodes[0].node.get_and_clear_pending_events();
5800         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5801         let mut as_failds = HashSet::new();
5802         for event in as_events.iter() {
5803                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5804                         assert!(as_failds.insert(*payment_hash));
5805                         if *payment_hash != payment_hash_2 {
5806                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5807                         } else {
5808                                 assert!(!rejected_by_dest);
5809                         }
5810                 } else { panic!("Unexpected event"); }
5811         }
5812         assert!(as_failds.contains(&payment_hash_1));
5813         assert!(as_failds.contains(&payment_hash_2));
5814         if announce_latest {
5815                 assert!(as_failds.contains(&payment_hash_3));
5816                 assert!(as_failds.contains(&payment_hash_5));
5817         }
5818         assert!(as_failds.contains(&payment_hash_6));
5819
5820         let bs_events = nodes[1].node.get_and_clear_pending_events();
5821         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5822         let mut bs_failds = HashSet::new();
5823         for event in bs_events.iter() {
5824                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5825                         assert!(bs_failds.insert(*payment_hash));
5826                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5827                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5828                         } else {
5829                                 assert!(!rejected_by_dest);
5830                         }
5831                 } else { panic!("Unexpected event"); }
5832         }
5833         assert!(bs_failds.contains(&payment_hash_1));
5834         assert!(bs_failds.contains(&payment_hash_2));
5835         if announce_latest {
5836                 assert!(bs_failds.contains(&payment_hash_4));
5837         }
5838         assert!(bs_failds.contains(&payment_hash_5));
5839
5840         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5841         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5842         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5843         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5844         // PaymentFailureNetworkUpdates.
5845         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5846         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5847         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5848         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5849         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5850                 match event {
5851                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5852                         _ => panic!("Unexpected event"),
5853                 }
5854         }
5855 }
5856
5857 #[test]
5858 fn test_fail_backwards_latest_remote_announce_a() {
5859         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5860 }
5861
5862 #[test]
5863 fn test_fail_backwards_latest_remote_announce_b() {
5864         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5865 }
5866
5867 #[test]
5868 fn test_fail_backwards_previous_remote_announce() {
5869         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5870         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5871         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5872 }
5873
5874 #[test]
5875 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5876         let chanmon_cfgs = create_chanmon_cfgs(2);
5877         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5878         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5879         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5880
5881         // Create some initial channels
5882         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5883
5884         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5885         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5886         assert_eq!(local_txn[0].input.len(), 1);
5887         check_spends!(local_txn[0], chan_1.3);
5888
5889         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5890         mine_transaction(&nodes[0], &local_txn[0]);
5891         check_closed_broadcast!(nodes[0], true);
5892         check_added_monitors!(nodes[0], 1);
5893         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5894
5895         let htlc_timeout = {
5896                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5897                 assert_eq!(node_txn.len(), 2);
5898                 check_spends!(node_txn[0], chan_1.3);
5899                 assert_eq!(node_txn[1].input.len(), 1);
5900                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5901                 check_spends!(node_txn[1], local_txn[0]);
5902                 node_txn[1].clone()
5903         };
5904
5905         mine_transaction(&nodes[0], &htlc_timeout);
5906         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5907         expect_payment_failed!(nodes[0], our_payment_hash, true);
5908
5909         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5910         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5911         assert_eq!(spend_txn.len(), 3);
5912         check_spends!(spend_txn[0], local_txn[0]);
5913         assert_eq!(spend_txn[1].input.len(), 1);
5914         check_spends!(spend_txn[1], htlc_timeout);
5915         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5916         assert_eq!(spend_txn[2].input.len(), 2);
5917         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5918         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5919                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5920 }
5921
5922 #[test]
5923 fn test_key_derivation_params() {
5924         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5925         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5926         // let us re-derive the channel key set to then derive a delayed_payment_key.
5927
5928         let chanmon_cfgs = create_chanmon_cfgs(3);
5929
5930         // We manually create the node configuration to backup the seed.
5931         let seed = [42; 32];
5932         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5933         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);
5934         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, features: InitFeatures::known() };
5935         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5936         node_cfgs.remove(0);
5937         node_cfgs.insert(0, node);
5938
5939         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5940         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5941
5942         // Create some initial channels
5943         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5944         // for node 0
5945         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5946         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5947         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5948
5949         // Ensure all nodes are at the same height
5950         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5951         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5952         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5953         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5954
5955         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5956         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5957         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5958         assert_eq!(local_txn_1[0].input.len(), 1);
5959         check_spends!(local_txn_1[0], chan_1.3);
5960
5961         // We check funding pubkey are unique
5962         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]));
5963         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]));
5964         if from_0_funding_key_0 == from_1_funding_key_0
5965             || from_0_funding_key_0 == from_1_funding_key_1
5966             || from_0_funding_key_1 == from_1_funding_key_0
5967             || from_0_funding_key_1 == from_1_funding_key_1 {
5968                 panic!("Funding pubkeys aren't unique");
5969         }
5970
5971         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5972         mine_transaction(&nodes[0], &local_txn_1[0]);
5973         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5974         check_closed_broadcast!(nodes[0], true);
5975         check_added_monitors!(nodes[0], 1);
5976
5977         let htlc_timeout = {
5978                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5979                 assert_eq!(node_txn[1].input.len(), 1);
5980                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5981                 check_spends!(node_txn[1], local_txn_1[0]);
5982                 node_txn[1].clone()
5983         };
5984
5985         mine_transaction(&nodes[0], &htlc_timeout);
5986         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5987         expect_payment_failed!(nodes[0], our_payment_hash, true);
5988
5989         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5990         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5991         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5992         assert_eq!(spend_txn.len(), 3);
5993         check_spends!(spend_txn[0], local_txn_1[0]);
5994         assert_eq!(spend_txn[1].input.len(), 1);
5995         check_spends!(spend_txn[1], htlc_timeout);
5996         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5997         assert_eq!(spend_txn[2].input.len(), 2);
5998         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5999         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
6000                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
6001 }
6002
6003 #[test]
6004 fn test_static_output_closing_tx() {
6005         let chanmon_cfgs = create_chanmon_cfgs(2);
6006         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6007         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6008         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6009
6010         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6011
6012         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6013         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
6014
6015         mine_transaction(&nodes[0], &closing_tx);
6016         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6017
6018         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
6019         assert_eq!(spend_txn.len(), 1);
6020         check_spends!(spend_txn[0], closing_tx);
6021
6022         mine_transaction(&nodes[1], &closing_tx);
6023         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
6024
6025         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
6026         assert_eq!(spend_txn.len(), 1);
6027         check_spends!(spend_txn[0], closing_tx);
6028 }
6029
6030 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
6031         let chanmon_cfgs = create_chanmon_cfgs(2);
6032         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6033         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6034         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6035         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6036
6037         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
6038
6039         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
6040         // present in B's local commitment transaction, but none of A's commitment transactions.
6041         assert!(nodes[1].node.claim_funds(our_payment_preimage));
6042         check_added_monitors!(nodes[1], 1);
6043
6044         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6045         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
6046         let events = nodes[0].node.get_and_clear_pending_events();
6047         assert_eq!(events.len(), 1);
6048         match events[0] {
6049                 Event::PaymentSent { payment_preimage } => {
6050                         assert_eq!(payment_preimage, our_payment_preimage);
6051                 },
6052                 _ => panic!("Unexpected event"),
6053         }
6054
6055         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6056         check_added_monitors!(nodes[0], 1);
6057         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6058         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6059         check_added_monitors!(nodes[1], 1);
6060
6061         let starting_block = nodes[1].best_block_info();
6062         let mut block = Block {
6063                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
6064                 txdata: vec![],
6065         };
6066         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
6067                 connect_block(&nodes[1], &block);
6068                 block.header.prev_blockhash = block.block_hash();
6069         }
6070         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
6071         check_closed_broadcast!(nodes[1], true);
6072         check_added_monitors!(nodes[1], 1);
6073 }
6074
6075 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
6076         let chanmon_cfgs = create_chanmon_cfgs(2);
6077         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6078         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6079         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6080         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6081         let logger = test_utils::TestLogger::new();
6082
6083         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1]);
6084         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6085         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(), Some(InvoiceFeatures::known()), None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV, &logger).unwrap();
6086         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
6087         check_added_monitors!(nodes[0], 1);
6088
6089         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6090
6091         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
6092         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
6093         // to "time out" the HTLC.
6094
6095         let starting_block = nodes[1].best_block_info();
6096         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6097
6098         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
6099                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
6100                 header.prev_blockhash = header.block_hash();
6101         }
6102         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6103         check_closed_broadcast!(nodes[0], true);
6104         check_added_monitors!(nodes[0], 1);
6105 }
6106
6107 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
6108         let chanmon_cfgs = create_chanmon_cfgs(3);
6109         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6110         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6111         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6112         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6113
6114         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
6115         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
6116         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6117         // actually revoked.
6118         let htlc_value = if use_dust { 50000 } else { 3000000 };
6119         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6120         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
6121         expect_pending_htlcs_forwardable!(nodes[1]);
6122         check_added_monitors!(nodes[1], 1);
6123
6124         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6125         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
6126         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6127         check_added_monitors!(nodes[0], 1);
6128         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6129         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6130         check_added_monitors!(nodes[1], 1);
6131         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6132         check_added_monitors!(nodes[1], 1);
6133         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6134
6135         if check_revoke_no_close {
6136                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6137                 check_added_monitors!(nodes[0], 1);
6138         }
6139
6140         let starting_block = nodes[1].best_block_info();
6141         let mut block = Block {
6142                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
6143                 txdata: vec![],
6144         };
6145         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6146                 connect_block(&nodes[0], &block);
6147                 block.header.prev_blockhash = block.block_hash();
6148         }
6149         if !check_revoke_no_close {
6150                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6151                 check_closed_broadcast!(nodes[0], true);
6152                 check_added_monitors!(nodes[0], 1);
6153         } else {
6154                 expect_payment_failed!(nodes[0], our_payment_hash, true);
6155         }
6156 }
6157
6158 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6159 // There are only a few cases to test here:
6160 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
6161 //    broadcastable commitment transactions result in channel closure,
6162 //  * its included in an unrevoked-but-previous remote commitment transaction,
6163 //  * its included in the latest remote or local commitment transactions.
6164 // We test each of the three possible commitment transactions individually and use both dust and
6165 // non-dust HTLCs.
6166 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6167 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6168 // tested for at least one of the cases in other tests.
6169 #[test]
6170 fn htlc_claim_single_commitment_only_a() {
6171         do_htlc_claim_local_commitment_only(true);
6172         do_htlc_claim_local_commitment_only(false);
6173
6174         do_htlc_claim_current_remote_commitment_only(true);
6175         do_htlc_claim_current_remote_commitment_only(false);
6176 }
6177
6178 #[test]
6179 fn htlc_claim_single_commitment_only_b() {
6180         do_htlc_claim_previous_remote_commitment_only(true, false);
6181         do_htlc_claim_previous_remote_commitment_only(false, false);
6182         do_htlc_claim_previous_remote_commitment_only(true, true);
6183         do_htlc_claim_previous_remote_commitment_only(false, true);
6184 }
6185
6186 #[test]
6187 #[should_panic]
6188 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6189         let chanmon_cfgs = create_chanmon_cfgs(2);
6190         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6191         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6192         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6193         //Force duplicate channel ids
6194         for node in nodes.iter() {
6195                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
6196         }
6197
6198         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6199         let channel_value_satoshis=10000;
6200         let push_msat=10001;
6201         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6202         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6203         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6204
6205         //Create a second channel with a channel_id collision
6206         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6207 }
6208
6209 #[test]
6210 fn bolt2_open_channel_sending_node_checks_part2() {
6211         let chanmon_cfgs = create_chanmon_cfgs(2);
6212         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6213         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6214         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6215
6216         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6217         let channel_value_satoshis=2^24;
6218         let push_msat=10001;
6219         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6220
6221         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6222         let channel_value_satoshis=10000;
6223         // Test when push_msat is equal to 1000 * funding_satoshis.
6224         let push_msat=1000*channel_value_satoshis+1;
6225         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6226
6227         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6228         let channel_value_satoshis=10000;
6229         let push_msat=10001;
6230         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
6231         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6232         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6233
6234         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6235         // 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
6236         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6237
6238         // 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.
6239         assert!(BREAKDOWN_TIMEOUT>0);
6240         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6241
6242         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6243         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6244         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6245
6246         // 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.
6247         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6248         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6249         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6250         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6251         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6252 }
6253
6254 #[test]
6255 fn bolt2_open_channel_sane_dust_limit() {
6256         let chanmon_cfgs = create_chanmon_cfgs(2);
6257         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6258         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6259         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6260
6261         let channel_value_satoshis=1000000;
6262         let push_msat=10001;
6263         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6264         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6265         node0_to_1_send_open_channel.dust_limit_satoshis = 661;
6266         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6267
6268         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6269         let events = nodes[1].node.get_and_clear_pending_msg_events();
6270         let err_msg = match events[0] {
6271                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6272                         msg.clone()
6273                 },
6274                 _ => panic!("Unexpected event"),
6275         };
6276         assert_eq!(err_msg.data, "dust_limit_satoshis (661) is greater than the implementation limit (660)");
6277 }
6278
6279 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6280 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6281 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6282 // is no longer affordable once it's freed.
6283 #[test]
6284 fn test_fail_holding_cell_htlc_upon_free() {
6285         let chanmon_cfgs = create_chanmon_cfgs(2);
6286         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6287         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6288         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6289         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6290         let logger = test_utils::TestLogger::new();
6291
6292         // First nodes[0] generates an update_fee, setting the channel's
6293         // pending_update_fee.
6294         {
6295                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6296                 *feerate_lock += 20;
6297         }
6298         nodes[0].node.timer_tick_occurred();
6299         check_added_monitors!(nodes[0], 1);
6300
6301         let events = nodes[0].node.get_and_clear_pending_msg_events();
6302         assert_eq!(events.len(), 1);
6303         let (update_msg, commitment_signed) = match events[0] {
6304                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6305                         (update_fee.as_ref(), commitment_signed)
6306                 },
6307                 _ => panic!("Unexpected event"),
6308         };
6309
6310         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6311
6312         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6313         let channel_reserve = chan_stat.channel_reserve_msat;
6314         let feerate = get_feerate!(nodes[0], chan.2);
6315
6316         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6317         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6318         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6319         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6320         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(), Some(InvoiceFeatures::known()), None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6321
6322         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6323         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6324         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6325         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6326
6327         // Flush the pending fee update.
6328         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6329         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6330         check_added_monitors!(nodes[1], 1);
6331         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6332         check_added_monitors!(nodes[0], 1);
6333
6334         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6335         // HTLC, but now that the fee has been raised the payment will now fail, causing
6336         // us to surface its failure to the user.
6337         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6338         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6339         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 1 HTLC updates in channel {}", hex::encode(chan.2)), 1);
6340         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 ({}) in channel {}",
6341                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6342         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6343
6344         // Check that the payment failed to be sent out.
6345         let events = nodes[0].node.get_and_clear_pending_events();
6346         assert_eq!(events.len(), 1);
6347         match &events[0] {
6348                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6349                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6350                         assert_eq!(*rejected_by_dest, false);
6351                         assert_eq!(*error_code, None);
6352                         assert_eq!(*error_data, None);
6353                 },
6354                 _ => panic!("Unexpected event"),
6355         }
6356 }
6357
6358 // Test that if multiple HTLCs are released from the holding cell and one is
6359 // valid but the other is no longer valid upon release, the valid HTLC can be
6360 // successfully completed while the other one fails as expected.
6361 #[test]
6362 fn test_free_and_fail_holding_cell_htlcs() {
6363         let chanmon_cfgs = create_chanmon_cfgs(2);
6364         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6365         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6366         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6367         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6368         let logger = test_utils::TestLogger::new();
6369
6370         // First nodes[0] generates an update_fee, setting the channel's
6371         // pending_update_fee.
6372         {
6373                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6374                 *feerate_lock += 200;
6375         }
6376         nodes[0].node.timer_tick_occurred();
6377         check_added_monitors!(nodes[0], 1);
6378
6379         let events = nodes[0].node.get_and_clear_pending_msg_events();
6380         assert_eq!(events.len(), 1);
6381         let (update_msg, commitment_signed) = match events[0] {
6382                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6383                         (update_fee.as_ref(), commitment_signed)
6384                 },
6385                 _ => panic!("Unexpected event"),
6386         };
6387
6388         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6389
6390         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6391         let channel_reserve = chan_stat.channel_reserve_msat;
6392         let feerate = get_feerate!(nodes[0], chan.2);
6393
6394         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6395         let (payment_preimage_1, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[1]);
6396         let amt_1 = 20000;
6397         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
6398         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6399         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6400         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(), Some(InvoiceFeatures::known()), None, &[], amt_1, TEST_FINAL_CLTV, &logger).unwrap();
6401         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(), Some(InvoiceFeatures::known()), None, &[], amt_2, TEST_FINAL_CLTV, &logger).unwrap();
6402
6403         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6404         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6405         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6406         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6407         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6408         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6409         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6410
6411         // Flush the pending fee update.
6412         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6413         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6414         check_added_monitors!(nodes[1], 1);
6415         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6416         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6417         check_added_monitors!(nodes[0], 2);
6418
6419         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6420         // but now that the fee has been raised the second payment will now fail, causing us
6421         // to surface its failure to the user. The first payment should succeed.
6422         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6423         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6424         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 2 HTLC updates in channel {}", hex::encode(chan.2)), 1);
6425         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 ({}) in channel {}",
6426                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6427         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6428
6429         // Check that the second payment failed to be sent out.
6430         let events = nodes[0].node.get_and_clear_pending_events();
6431         assert_eq!(events.len(), 1);
6432         match &events[0] {
6433                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6434                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6435                         assert_eq!(*rejected_by_dest, false);
6436                         assert_eq!(*error_code, None);
6437                         assert_eq!(*error_data, None);
6438                 },
6439                 _ => panic!("Unexpected event"),
6440         }
6441
6442         // Complete the first payment and the RAA from the fee update.
6443         let (payment_event, send_raa_event) = {
6444                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6445                 assert_eq!(msgs.len(), 2);
6446                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6447         };
6448         let raa = match send_raa_event {
6449                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6450                 _ => panic!("Unexpected event"),
6451         };
6452         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6453         check_added_monitors!(nodes[1], 1);
6454         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6455         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6456         let events = nodes[1].node.get_and_clear_pending_events();
6457         assert_eq!(events.len(), 1);
6458         match events[0] {
6459                 Event::PendingHTLCsForwardable { .. } => {},
6460                 _ => panic!("Unexpected event"),
6461         }
6462         nodes[1].node.process_pending_htlc_forwards();
6463         let events = nodes[1].node.get_and_clear_pending_events();
6464         assert_eq!(events.len(), 1);
6465         match events[0] {
6466                 Event::PaymentReceived { .. } => {},
6467                 _ => panic!("Unexpected event"),
6468         }
6469         nodes[1].node.claim_funds(payment_preimage_1);
6470         check_added_monitors!(nodes[1], 1);
6471         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6472         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6473         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6474         let events = nodes[0].node.get_and_clear_pending_events();
6475         assert_eq!(events.len(), 1);
6476         match events[0] {
6477                 Event::PaymentSent { ref payment_preimage } => {
6478                         assert_eq!(*payment_preimage, payment_preimage_1);
6479                 }
6480                 _ => panic!("Unexpected event"),
6481         }
6482 }
6483
6484 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6485 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6486 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6487 // once it's freed.
6488 #[test]
6489 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6490         let chanmon_cfgs = create_chanmon_cfgs(3);
6491         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6492         // When this test was written, the default base fee floated based on the HTLC count.
6493         // It is now fixed, so we simply set the fee to the expected value here.
6494         let mut config = test_default_channel_config();
6495         config.channel_options.forwarding_fee_base_msat = 196;
6496         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6497         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6498         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6499         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6500         let logger = test_utils::TestLogger::new();
6501
6502         // First nodes[1] generates an update_fee, setting the channel's
6503         // pending_update_fee.
6504         {
6505                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6506                 *feerate_lock += 20;
6507         }
6508         nodes[1].node.timer_tick_occurred();
6509         check_added_monitors!(nodes[1], 1);
6510
6511         let events = nodes[1].node.get_and_clear_pending_msg_events();
6512         assert_eq!(events.len(), 1);
6513         let (update_msg, commitment_signed) = match events[0] {
6514                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6515                         (update_fee.as_ref(), commitment_signed)
6516                 },
6517                 _ => panic!("Unexpected event"),
6518         };
6519
6520         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6521
6522         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6523         let channel_reserve = chan_stat.channel_reserve_msat;
6524         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6525
6526         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6527         let feemsat = 239;
6528         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6529         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
6530         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6531         let payment_event = {
6532                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6533                 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(), Some(InvoiceFeatures::known()), None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6534                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6535                 check_added_monitors!(nodes[0], 1);
6536
6537                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6538                 assert_eq!(events.len(), 1);
6539
6540                 SendEvent::from_event(events.remove(0))
6541         };
6542         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6543         check_added_monitors!(nodes[1], 0);
6544         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6545         expect_pending_htlcs_forwardable!(nodes[1]);
6546
6547         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6548         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6549
6550         // Flush the pending fee update.
6551         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6552         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6553         check_added_monitors!(nodes[2], 1);
6554         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6555         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6556         check_added_monitors!(nodes[1], 2);
6557
6558         // A final RAA message is generated to finalize the fee update.
6559         let events = nodes[1].node.get_and_clear_pending_msg_events();
6560         assert_eq!(events.len(), 1);
6561
6562         let raa_msg = match &events[0] {
6563                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6564                         msg.clone()
6565                 },
6566                 _ => panic!("Unexpected event"),
6567         };
6568
6569         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6570         check_added_monitors!(nodes[2], 1);
6571         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6572
6573         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6574         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6575         assert_eq!(process_htlc_forwards_event.len(), 1);
6576         match &process_htlc_forwards_event[0] {
6577                 &Event::PendingHTLCsForwardable { .. } => {},
6578                 _ => panic!("Unexpected event"),
6579         }
6580
6581         // In response, we call ChannelManager's process_pending_htlc_forwards
6582         nodes[1].node.process_pending_htlc_forwards();
6583         check_added_monitors!(nodes[1], 1);
6584
6585         // This causes the HTLC to be failed backwards.
6586         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6587         assert_eq!(fail_event.len(), 1);
6588         let (fail_msg, commitment_signed) = match &fail_event[0] {
6589                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6590                         assert_eq!(updates.update_add_htlcs.len(), 0);
6591                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6592                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6593                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6594                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6595                 },
6596                 _ => panic!("Unexpected event"),
6597         };
6598
6599         // Pass the failure messages back to nodes[0].
6600         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6601         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6602
6603         // Complete the HTLC failure+removal process.
6604         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6605         check_added_monitors!(nodes[0], 1);
6606         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6607         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6608         check_added_monitors!(nodes[1], 2);
6609         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6610         assert_eq!(final_raa_event.len(), 1);
6611         let raa = match &final_raa_event[0] {
6612                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6613                 _ => panic!("Unexpected event"),
6614         };
6615         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6616         expect_payment_failure_chan_update!(nodes[0], chan_1_2.0.contents.short_channel_id, false);
6617         expect_payment_failed!(nodes[0], our_payment_hash, false);
6618         check_added_monitors!(nodes[0], 1);
6619 }
6620
6621 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6622 // 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.
6623 //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.
6624
6625 #[test]
6626 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6627         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6628         let chanmon_cfgs = create_chanmon_cfgs(2);
6629         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6630         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6631         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6632         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6633
6634         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6635         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6636         let logger = test_utils::TestLogger::new();
6637         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(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6638         route.paths[0][0].fee_msat = 100;
6639
6640         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6641                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6642         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6643         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6644 }
6645
6646 #[test]
6647 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6648         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6649         let chanmon_cfgs = create_chanmon_cfgs(2);
6650         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6651         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6652         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6653         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6654         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6655
6656         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6657         let logger = test_utils::TestLogger::new();
6658         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(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6659         route.paths[0][0].fee_msat = 0;
6660         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6661                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6662
6663         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6664         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6665 }
6666
6667 #[test]
6668 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6669         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6670         let chanmon_cfgs = create_chanmon_cfgs(2);
6671         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6672         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6673         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6674         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6675
6676         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6677         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6678         let logger = test_utils::TestLogger::new();
6679         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6680         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6681         check_added_monitors!(nodes[0], 1);
6682         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6683         updates.update_add_htlcs[0].amount_msat = 0;
6684
6685         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6686         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6687         check_closed_broadcast!(nodes[1], true).unwrap();
6688         check_added_monitors!(nodes[1], 1);
6689 }
6690
6691 #[test]
6692 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6693         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6694         //It is enforced when constructing a route.
6695         let chanmon_cfgs = create_chanmon_cfgs(2);
6696         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6697         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6698         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6699         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6700         let logger = test_utils::TestLogger::new();
6701
6702         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6703
6704         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6705         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(), Some(InvoiceFeatures::known()), None, &[], 100000000, 500000001, &logger).unwrap();
6706         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6707                 assert_eq!(err, &"Channel CLTV overflowed?"));
6708 }
6709
6710 #[test]
6711 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6712         //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.
6713         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6714         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6715         let chanmon_cfgs = create_chanmon_cfgs(2);
6716         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6717         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6718         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6719         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6720         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6721
6722         let logger = test_utils::TestLogger::new();
6723         for i in 0..max_accepted_htlcs {
6724                 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6725                 let payment_event = {
6726                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6727                         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(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6728                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6729                         check_added_monitors!(nodes[0], 1);
6730
6731                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6732                         assert_eq!(events.len(), 1);
6733                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6734                                 assert_eq!(htlcs[0].htlc_id, i);
6735                         } else {
6736                                 assert!(false);
6737                         }
6738                         SendEvent::from_event(events.remove(0))
6739                 };
6740                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6741                 check_added_monitors!(nodes[1], 0);
6742                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6743
6744                 expect_pending_htlcs_forwardable!(nodes[1]);
6745                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6746         }
6747         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6748         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6749         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(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6750         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6751                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6752
6753         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6754         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6755 }
6756
6757 #[test]
6758 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6759         //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.
6760         let chanmon_cfgs = create_chanmon_cfgs(2);
6761         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6762         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6763         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6764         let channel_value = 100000;
6765         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6766         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6767
6768         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6769
6770         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6771         // Manually create a route over our max in flight (which our router normally automatically
6772         // limits us to.
6773         let route = Route { paths: vec![vec![RouteHop {
6774            pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6775            short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6776            fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6777         }]] };
6778         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6779                 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)));
6780
6781         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6782         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);
6783
6784         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6785 }
6786
6787 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6788 #[test]
6789 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6790         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6791         let chanmon_cfgs = create_chanmon_cfgs(2);
6792         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6793         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6794         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6795         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6796         let htlc_minimum_msat: u64;
6797         {
6798                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6799                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6800                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6801         }
6802
6803         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6804         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6805         let logger = test_utils::TestLogger::new();
6806         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(), Some(InvoiceFeatures::known()), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV, &logger).unwrap();
6807         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6808         check_added_monitors!(nodes[0], 1);
6809         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6810         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6811         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6812         assert!(nodes[1].node.list_channels().is_empty());
6813         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6814         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()));
6815         check_added_monitors!(nodes[1], 1);
6816 }
6817
6818 #[test]
6819 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6820         //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
6821         let chanmon_cfgs = create_chanmon_cfgs(2);
6822         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6823         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6824         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6825         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6826         let logger = test_utils::TestLogger::new();
6827
6828         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6829         let channel_reserve = chan_stat.channel_reserve_msat;
6830         let feerate = get_feerate!(nodes[0], chan.2);
6831         // The 2* and +1 are for the fee spike reserve.
6832         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6833
6834         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6835         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6836         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6837         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(), Some(InvoiceFeatures::known()), None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6838         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6839         check_added_monitors!(nodes[0], 1);
6840         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6841
6842         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6843         // at this time channel-initiatee receivers are not required to enforce that senders
6844         // respect the fee_spike_reserve.
6845         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6846         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6847
6848         assert!(nodes[1].node.list_channels().is_empty());
6849         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6850         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6851         check_added_monitors!(nodes[1], 1);
6852 }
6853
6854 #[test]
6855 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6856         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6857         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6858         let chanmon_cfgs = create_chanmon_cfgs(2);
6859         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6860         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6861         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6862         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6863         let logger = test_utils::TestLogger::new();
6864
6865         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6866         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6867
6868         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6869         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(), Some(InvoiceFeatures::known()), None, &[], 3999999, TEST_FINAL_CLTV, &logger).unwrap();
6870
6871         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6872         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6873         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6874         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6875
6876         let mut msg = msgs::UpdateAddHTLC {
6877                 channel_id: chan.2,
6878                 htlc_id: 0,
6879                 amount_msat: 1000,
6880                 payment_hash: our_payment_hash,
6881                 cltv_expiry: htlc_cltv,
6882                 onion_routing_packet: onion_packet.clone(),
6883         };
6884
6885         for i in 0..super::channel::OUR_MAX_HTLCS {
6886                 msg.htlc_id = i as u64;
6887                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6888         }
6889         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6890         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6891
6892         assert!(nodes[1].node.list_channels().is_empty());
6893         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6894         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6895         check_added_monitors!(nodes[1], 1);
6896 }
6897
6898 #[test]
6899 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6900         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6901         let chanmon_cfgs = create_chanmon_cfgs(2);
6902         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6903         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6904         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6905         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6906         let logger = test_utils::TestLogger::new();
6907
6908         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6909         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6910         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(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6911         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6912         check_added_monitors!(nodes[0], 1);
6913         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6914         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6915         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6916
6917         assert!(nodes[1].node.list_channels().is_empty());
6918         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6919         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6920         check_added_monitors!(nodes[1], 1);
6921 }
6922
6923 #[test]
6924 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6925         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6926         let chanmon_cfgs = create_chanmon_cfgs(2);
6927         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6928         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6929         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6930         let logger = test_utils::TestLogger::new();
6931
6932         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6933         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6934         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6935         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(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6936         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6937         check_added_monitors!(nodes[0], 1);
6938         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6939         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6940         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6941
6942         assert!(nodes[1].node.list_channels().is_empty());
6943         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6944         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6945         check_added_monitors!(nodes[1], 1);
6946 }
6947
6948 #[test]
6949 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6950         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6951         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6952         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6953         let chanmon_cfgs = create_chanmon_cfgs(2);
6954         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6955         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6956         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6957         let logger = test_utils::TestLogger::new();
6958
6959         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6960         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6961         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6962         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(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6963         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6964         check_added_monitors!(nodes[0], 1);
6965         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6966         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6967
6968         //Disconnect and Reconnect
6969         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6970         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6971         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6972         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6973         assert_eq!(reestablish_1.len(), 1);
6974         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6975         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6976         assert_eq!(reestablish_2.len(), 1);
6977         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6978         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6979         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6980         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6981
6982         //Resend HTLC
6983         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6984         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6985         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6986         check_added_monitors!(nodes[1], 1);
6987         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6988
6989         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6990
6991         assert!(nodes[1].node.list_channels().is_empty());
6992         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6993         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6994         check_added_monitors!(nodes[1], 1);
6995 }
6996
6997 #[test]
6998 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6999         //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.
7000
7001         let chanmon_cfgs = create_chanmon_cfgs(2);
7002         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7003         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7004         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7005         let logger = test_utils::TestLogger::new();
7006         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7007         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
7008         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7009         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(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
7010         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7011
7012         check_added_monitors!(nodes[0], 1);
7013         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7014         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7015
7016         let update_msg = msgs::UpdateFulfillHTLC{
7017                 channel_id: chan.2,
7018                 htlc_id: 0,
7019                 payment_preimage: our_payment_preimage,
7020         };
7021
7022         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7023
7024         assert!(nodes[0].node.list_channels().is_empty());
7025         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7026         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()));
7027         check_added_monitors!(nodes[0], 1);
7028 }
7029
7030 #[test]
7031 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
7032         //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.
7033
7034         let chanmon_cfgs = create_chanmon_cfgs(2);
7035         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7036         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7037         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7038         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7039         let logger = test_utils::TestLogger::new();
7040
7041         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
7042         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7043         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(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
7044         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7045         check_added_monitors!(nodes[0], 1);
7046         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7047         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7048
7049         let update_msg = msgs::UpdateFailHTLC{
7050                 channel_id: chan.2,
7051                 htlc_id: 0,
7052                 reason: msgs::OnionErrorPacket { data: Vec::new()},
7053         };
7054
7055         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7056
7057         assert!(nodes[0].node.list_channels().is_empty());
7058         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7059         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()));
7060         check_added_monitors!(nodes[0], 1);
7061 }
7062
7063 #[test]
7064 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
7065         //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.
7066
7067         let chanmon_cfgs = create_chanmon_cfgs(2);
7068         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7069         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7070         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7071         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7072         let logger = test_utils::TestLogger::new();
7073
7074         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
7075         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7076         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(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
7077         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7078         check_added_monitors!(nodes[0], 1);
7079         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7080         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7081         let update_msg = msgs::UpdateFailMalformedHTLC{
7082                 channel_id: chan.2,
7083                 htlc_id: 0,
7084                 sha256_of_onion: [1; 32],
7085                 failure_code: 0x8000,
7086         };
7087
7088         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7089
7090         assert!(nodes[0].node.list_channels().is_empty());
7091         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7092         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()));
7093         check_added_monitors!(nodes[0], 1);
7094 }
7095
7096 #[test]
7097 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
7098         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
7099
7100         let chanmon_cfgs = create_chanmon_cfgs(2);
7101         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7102         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7103         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7104         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7105
7106         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
7107
7108         nodes[1].node.claim_funds(our_payment_preimage);
7109         check_added_monitors!(nodes[1], 1);
7110
7111         let events = nodes[1].node.get_and_clear_pending_msg_events();
7112         assert_eq!(events.len(), 1);
7113         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7114                 match events[0] {
7115                         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, .. } } => {
7116                                 assert!(update_add_htlcs.is_empty());
7117                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7118                                 assert!(update_fail_htlcs.is_empty());
7119                                 assert!(update_fail_malformed_htlcs.is_empty());
7120                                 assert!(update_fee.is_none());
7121                                 update_fulfill_htlcs[0].clone()
7122                         },
7123                         _ => panic!("Unexpected event"),
7124                 }
7125         };
7126
7127         update_fulfill_msg.htlc_id = 1;
7128
7129         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7130
7131         assert!(nodes[0].node.list_channels().is_empty());
7132         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7133         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
7134         check_added_monitors!(nodes[0], 1);
7135 }
7136
7137 #[test]
7138 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
7139         //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.
7140
7141         let chanmon_cfgs = create_chanmon_cfgs(2);
7142         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7143         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7144         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7145         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7146
7147         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
7148
7149         nodes[1].node.claim_funds(our_payment_preimage);
7150         check_added_monitors!(nodes[1], 1);
7151
7152         let events = nodes[1].node.get_and_clear_pending_msg_events();
7153         assert_eq!(events.len(), 1);
7154         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7155                 match events[0] {
7156                         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, .. } } => {
7157                                 assert!(update_add_htlcs.is_empty());
7158                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7159                                 assert!(update_fail_htlcs.is_empty());
7160                                 assert!(update_fail_malformed_htlcs.is_empty());
7161                                 assert!(update_fee.is_none());
7162                                 update_fulfill_htlcs[0].clone()
7163                         },
7164                         _ => panic!("Unexpected event"),
7165                 }
7166         };
7167
7168         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7169
7170         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7171
7172         assert!(nodes[0].node.list_channels().is_empty());
7173         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7174         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7175         check_added_monitors!(nodes[0], 1);
7176 }
7177
7178 #[test]
7179 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7180         //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.
7181
7182         let chanmon_cfgs = create_chanmon_cfgs(2);
7183         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7184         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7185         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7186         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7187         let logger = test_utils::TestLogger::new();
7188
7189         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
7190         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7191         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(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
7192         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7193         check_added_monitors!(nodes[0], 1);
7194
7195         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7196         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7197
7198         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7199         check_added_monitors!(nodes[1], 0);
7200         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7201
7202         let events = nodes[1].node.get_and_clear_pending_msg_events();
7203
7204         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7205                 match events[0] {
7206                         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, .. } } => {
7207                                 assert!(update_add_htlcs.is_empty());
7208                                 assert!(update_fulfill_htlcs.is_empty());
7209                                 assert!(update_fail_htlcs.is_empty());
7210                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7211                                 assert!(update_fee.is_none());
7212                                 update_fail_malformed_htlcs[0].clone()
7213                         },
7214                         _ => panic!("Unexpected event"),
7215                 }
7216         };
7217         update_msg.failure_code &= !0x8000;
7218         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7219
7220         assert!(nodes[0].node.list_channels().is_empty());
7221         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7222         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7223         check_added_monitors!(nodes[0], 1);
7224 }
7225
7226 #[test]
7227 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7228         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7229         //    * 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.
7230
7231         let chanmon_cfgs = create_chanmon_cfgs(3);
7232         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7233         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7234         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7235         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7236         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7237         let logger = test_utils::TestLogger::new();
7238
7239         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
7240
7241         //First hop
7242         let mut payment_event = {
7243                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7244                 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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
7245                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7246                 check_added_monitors!(nodes[0], 1);
7247                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7248                 assert_eq!(events.len(), 1);
7249                 SendEvent::from_event(events.remove(0))
7250         };
7251         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7252         check_added_monitors!(nodes[1], 0);
7253         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7254         expect_pending_htlcs_forwardable!(nodes[1]);
7255         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7256         assert_eq!(events_2.len(), 1);
7257         check_added_monitors!(nodes[1], 1);
7258         payment_event = SendEvent::from_event(events_2.remove(0));
7259         assert_eq!(payment_event.msgs.len(), 1);
7260
7261         //Second Hop
7262         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7263         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7264         check_added_monitors!(nodes[2], 0);
7265         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7266
7267         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7268         assert_eq!(events_3.len(), 1);
7269         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7270                 match events_3[0] {
7271                         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 } } => {
7272                                 assert!(update_add_htlcs.is_empty());
7273                                 assert!(update_fulfill_htlcs.is_empty());
7274                                 assert!(update_fail_htlcs.is_empty());
7275                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7276                                 assert!(update_fee.is_none());
7277                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7278                         },
7279                         _ => panic!("Unexpected event"),
7280                 }
7281         };
7282
7283         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7284
7285         check_added_monitors!(nodes[1], 0);
7286         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7287         expect_pending_htlcs_forwardable!(nodes[1]);
7288         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7289         assert_eq!(events_4.len(), 1);
7290
7291         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7292         match events_4[0] {
7293                 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, .. } } => {
7294                         assert!(update_add_htlcs.is_empty());
7295                         assert!(update_fulfill_htlcs.is_empty());
7296                         assert_eq!(update_fail_htlcs.len(), 1);
7297                         assert!(update_fail_malformed_htlcs.is_empty());
7298                         assert!(update_fee.is_none());
7299                 },
7300                 _ => panic!("Unexpected event"),
7301         };
7302
7303         check_added_monitors!(nodes[1], 1);
7304 }
7305
7306 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7307         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7308         // 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
7309         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7310
7311         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7312         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7313         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7314         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7315         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7316         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7317
7318         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7319
7320         // We route 2 dust-HTLCs between A and B
7321         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7322         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7323         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7324
7325         // Cache one local commitment tx as previous
7326         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7327
7328         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7329         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
7330         check_added_monitors!(nodes[1], 0);
7331         expect_pending_htlcs_forwardable!(nodes[1]);
7332         check_added_monitors!(nodes[1], 1);
7333
7334         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7335         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7336         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7337         check_added_monitors!(nodes[0], 1);
7338
7339         // Cache one local commitment tx as lastest
7340         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7341
7342         let events = nodes[0].node.get_and_clear_pending_msg_events();
7343         match events[0] {
7344                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7345                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7346                 },
7347                 _ => panic!("Unexpected event"),
7348         }
7349         match events[1] {
7350                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7351                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7352                 },
7353                 _ => panic!("Unexpected event"),
7354         }
7355
7356         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7357         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7358         if announce_latest {
7359                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7360         } else {
7361                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7362         }
7363
7364         check_closed_broadcast!(nodes[0], true);
7365         check_added_monitors!(nodes[0], 1);
7366
7367         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7368         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7369         let events = nodes[0].node.get_and_clear_pending_events();
7370         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7371         assert_eq!(events.len(), 2);
7372         let mut first_failed = false;
7373         for event in events {
7374                 match event {
7375                         Event::PaymentFailed { payment_hash, .. } => {
7376                                 if payment_hash == payment_hash_1 {
7377                                         assert!(!first_failed);
7378                                         first_failed = true;
7379                                 } else {
7380                                         assert_eq!(payment_hash, payment_hash_2);
7381                                 }
7382                         }
7383                         _ => panic!("Unexpected event"),
7384                 }
7385         }
7386 }
7387
7388 #[test]
7389 fn test_failure_delay_dust_htlc_local_commitment() {
7390         do_test_failure_delay_dust_htlc_local_commitment(true);
7391         do_test_failure_delay_dust_htlc_local_commitment(false);
7392 }
7393
7394 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7395         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7396         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7397         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7398         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7399         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7400         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7401
7402         let chanmon_cfgs = create_chanmon_cfgs(3);
7403         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7404         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7405         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7406         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7407
7408         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7409
7410         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7411         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7412
7413         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7414         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7415
7416         // We revoked bs_commitment_tx
7417         if revoked {
7418                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7419                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7420         }
7421
7422         let mut timeout_tx = Vec::new();
7423         if local {
7424                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7425                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7426                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7427                 expect_payment_failed!(nodes[0], dust_hash, true);
7428
7429                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7430                 check_closed_broadcast!(nodes[0], true);
7431                 check_added_monitors!(nodes[0], 1);
7432                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7433                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7434                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7435                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7436                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7437                 mine_transaction(&nodes[0], &timeout_tx[0]);
7438                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7439                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7440         } else {
7441                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7442                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7443                 check_closed_broadcast!(nodes[0], true);
7444                 check_added_monitors!(nodes[0], 1);
7445                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7446                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7447                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7448                 if !revoked {
7449                         expect_payment_failed!(nodes[0], dust_hash, true);
7450                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7451                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7452                         mine_transaction(&nodes[0], &timeout_tx[0]);
7453                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7454                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7455                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7456                 } else {
7457                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7458                         // commitment tx
7459                         let events = nodes[0].node.get_and_clear_pending_events();
7460                         assert_eq!(events.len(), 2);
7461                         let first;
7462                         match events[0] {
7463                                 Event::PaymentFailed { payment_hash, .. } => {
7464                                         if payment_hash == dust_hash { first = true; }
7465                                         else { first = false; }
7466                                 },
7467                                 _ => panic!("Unexpected event"),
7468                         }
7469                         match events[1] {
7470                                 Event::PaymentFailed { payment_hash, .. } => {
7471                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7472                                         else { assert_eq!(payment_hash, dust_hash); }
7473                                 },
7474                                 _ => panic!("Unexpected event"),
7475                         }
7476                 }
7477         }
7478 }
7479
7480 #[test]
7481 fn test_sweep_outbound_htlc_failure_update() {
7482         do_test_sweep_outbound_htlc_failure_update(false, true);
7483         do_test_sweep_outbound_htlc_failure_update(false, false);
7484         do_test_sweep_outbound_htlc_failure_update(true, false);
7485 }
7486
7487 #[test]
7488 fn test_upfront_shutdown_script() {
7489         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7490         // enforce it at shutdown message
7491
7492         let mut config = UserConfig::default();
7493         config.channel_options.announced_channel = true;
7494         config.peer_channel_config_limits.force_announced_channel_preference = false;
7495         config.channel_options.commit_upfront_shutdown_pubkey = false;
7496         let user_cfgs = [None, Some(config), None];
7497         let chanmon_cfgs = create_chanmon_cfgs(3);
7498         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7499         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7500         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7501
7502         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7503         let flags = InitFeatures::known();
7504         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7505         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7506         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7507         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7508         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
7509         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7510     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()));
7511         check_added_monitors!(nodes[2], 1);
7512
7513         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7514         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7515         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7516         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7517         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7518         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7519         let events = nodes[2].node.get_and_clear_pending_msg_events();
7520         assert_eq!(events.len(), 1);
7521         match events[0] {
7522                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7523                 _ => panic!("Unexpected event"),
7524         }
7525
7526         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7527         let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7528         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7529         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7530         let node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7531         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
7532         check_added_monitors!(nodes[1], 1);
7533         let events = nodes[1].node.get_and_clear_pending_msg_events();
7534         assert_eq!(events.len(), 1);
7535         match events[0] {
7536                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7537                 _ => panic!("Unexpected event"),
7538         }
7539
7540         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7541         // channel smoothly, opt-out is from channel initiator here
7542         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7543         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7544         check_added_monitors!(nodes[1], 1);
7545         let node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7546         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7547         let events = nodes[0].node.get_and_clear_pending_msg_events();
7548         assert_eq!(events.len(), 1);
7549         match events[0] {
7550                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7551                 _ => panic!("Unexpected event"),
7552         }
7553
7554         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7555         //// channel smoothly
7556         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7557         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7558         check_added_monitors!(nodes[1], 1);
7559         let node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7560         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7561         let events = nodes[0].node.get_and_clear_pending_msg_events();
7562         assert_eq!(events.len(), 2);
7563         match events[0] {
7564                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7565                 _ => panic!("Unexpected event"),
7566         }
7567         match events[1] {
7568                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7569                 _ => panic!("Unexpected event"),
7570         }
7571 }
7572
7573 #[test]
7574 fn test_unsupported_anysegwit_upfront_shutdown_script() {
7575         let chanmon_cfgs = create_chanmon_cfgs(2);
7576         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7577         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7578         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7579
7580         // Use a non-v0 segwit script supported by option_shutdown_anysegwit
7581         let node_features = InitFeatures::known().clear_shutdown_anysegwit();
7582         let anysegwit_shutdown_script = Builder::new()
7583                 .push_int(16)
7584                 .push_slice(&[0, 40])
7585                 .into_script();
7586
7587         // Check script when handling an open_channel message
7588         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
7589         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7590         open_channel.shutdown_scriptpubkey = Present(anysegwit_shutdown_script.clone());
7591         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), node_features.clone(), &open_channel);
7592
7593         let events = nodes[1].node.get_and_clear_pending_msg_events();
7594         assert_eq!(events.len(), 1);
7595         match events[0] {
7596                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7597                         assert_eq!(node_id, nodes[0].node.get_our_node_id());
7598                         assert_eq!(msg.data, "Peer is signaling upfront_shutdown but has provided an unacceptable scriptpubkey format: Script(OP_PUSHNUM_16 OP_PUSHBYTES_2 0028)");
7599                 },
7600                 _ => panic!("Unexpected event"),
7601         }
7602
7603         // Check script when handling an accept_channel message
7604         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
7605         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7606         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
7607         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7608         accept_channel.shutdown_scriptpubkey = Present(anysegwit_shutdown_script.clone());
7609         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), node_features, &accept_channel);
7610
7611         let events = nodes[0].node.get_and_clear_pending_msg_events();
7612         assert_eq!(events.len(), 1);
7613         match events[0] {
7614                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7615                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7616                         assert_eq!(msg.data, "Peer is signaling upfront_shutdown but has provided an unacceptable scriptpubkey format: Script(OP_PUSHNUM_16 OP_PUSHBYTES_2 0028)");
7617                 },
7618                 _ => panic!("Unexpected event"),
7619         }
7620 }
7621
7622 #[test]
7623 fn test_invalid_upfront_shutdown_script() {
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         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
7630
7631         // Use a segwit v0 script with an unsupported witness program
7632         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7633         open_channel.shutdown_scriptpubkey = Present(Builder::new().push_int(0)
7634                 .push_slice(&[0, 0])
7635                 .into_script());
7636         nodes[0].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
7637
7638         let events = nodes[0].node.get_and_clear_pending_msg_events();
7639         assert_eq!(events.len(), 1);
7640         match events[0] {
7641                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7642                         assert_eq!(node_id, nodes[0].node.get_our_node_id());
7643                         assert_eq!(msg.data, "Peer is signaling upfront_shutdown but has provided an unacceptable scriptpubkey format: Script(OP_0 OP_PUSHBYTES_2 0000)");
7644                 },
7645                 _ => panic!("Unexpected event"),
7646         }
7647 }
7648
7649 #[test]
7650 fn test_segwit_v0_shutdown_script() {
7651         let mut config = UserConfig::default();
7652         config.channel_options.announced_channel = true;
7653         config.peer_channel_config_limits.force_announced_channel_preference = false;
7654         config.channel_options.commit_upfront_shutdown_pubkey = false;
7655         let user_cfgs = [None, Some(config), None];
7656         let chanmon_cfgs = create_chanmon_cfgs(3);
7657         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7658         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7659         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7660
7661         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7662         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7663         check_added_monitors!(nodes[1], 1);
7664
7665         // Use a segwit v0 script supported even without option_shutdown_anysegwit
7666         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7667         node_0_shutdown.scriptpubkey = Builder::new().push_int(0)
7668                 .push_slice(&[0; 20])
7669                 .into_script();
7670         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7671
7672         let events = nodes[0].node.get_and_clear_pending_msg_events();
7673         assert_eq!(events.len(), 2);
7674         match events[0] {
7675                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7676                 _ => panic!("Unexpected event"),
7677         }
7678         match events[1] {
7679                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7680                 _ => panic!("Unexpected event"),
7681         }
7682 }
7683
7684 #[test]
7685 fn test_anysegwit_shutdown_script() {
7686         let mut config = UserConfig::default();
7687         config.channel_options.announced_channel = true;
7688         config.peer_channel_config_limits.force_announced_channel_preference = false;
7689         config.channel_options.commit_upfront_shutdown_pubkey = false;
7690         let user_cfgs = [None, Some(config), None];
7691         let chanmon_cfgs = create_chanmon_cfgs(3);
7692         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7693         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7694         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7695
7696         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7697         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7698         check_added_monitors!(nodes[1], 1);
7699
7700         // Use a non-v0 segwit script supported by option_shutdown_anysegwit
7701         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7702         node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7703                 .push_slice(&[0, 0])
7704                 .into_script();
7705         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7706
7707         let events = nodes[0].node.get_and_clear_pending_msg_events();
7708         assert_eq!(events.len(), 2);
7709         match events[0] {
7710                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7711                 _ => panic!("Unexpected event"),
7712         }
7713         match events[1] {
7714                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7715                 _ => panic!("Unexpected event"),
7716         }
7717 }
7718
7719 #[test]
7720 fn test_unsupported_anysegwit_shutdown_script() {
7721         let mut config = UserConfig::default();
7722         config.channel_options.announced_channel = true;
7723         config.peer_channel_config_limits.force_announced_channel_preference = false;
7724         config.channel_options.commit_upfront_shutdown_pubkey = false;
7725         let user_cfgs = [None, Some(config), None];
7726         let chanmon_cfgs = create_chanmon_cfgs(3);
7727         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7728         node_cfgs[0].features = InitFeatures::known().clear_shutdown_anysegwit();
7729         node_cfgs[1].features = InitFeatures::known().clear_shutdown_anysegwit();
7730         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7731         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7732
7733         // Check that using an unsupported shutdown script fails and a supported one succeeds.
7734         let supported_shutdown_script = chanmon_cfgs[1].keys_manager.get_shutdown_scriptpubkey();
7735         let unsupported_shutdown_script =
7736                 ShutdownScript::new_witness_program(NonZeroU8::new(16).unwrap(), &[0, 40]).unwrap();
7737         chanmon_cfgs[1].keys_manager
7738                 .expect(OnGetShutdownScriptpubkey { returns: unsupported_shutdown_script.clone() })
7739                 .expect(OnGetShutdownScriptpubkey { returns: supported_shutdown_script });
7740
7741         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, node_cfgs[0].features.clone(), node_cfgs[1].features.clone());
7742         match nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()) {
7743                 Err(APIError::IncompatibleShutdownScript { script }) => {
7744                         assert_eq!(script.into_inner(), unsupported_shutdown_script.clone().into_inner());
7745                 },
7746                 Err(e) => panic!("Unexpected error: {:?}", e),
7747                 Ok(_) => panic!("Expected error"),
7748         }
7749         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7750         check_added_monitors!(nodes[1], 1);
7751
7752         // Use a non-v0 segwit script unsupported without option_shutdown_anysegwit
7753         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7754         node_0_shutdown.scriptpubkey = unsupported_shutdown_script.into_inner();
7755         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_cfgs[1].features, &node_0_shutdown);
7756
7757         let events = nodes[0].node.get_and_clear_pending_msg_events();
7758         assert_eq!(events.len(), 2);
7759         match events[1] {
7760                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7761                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7762                         assert_eq!(msg.data, "Got a nonstandard scriptpubkey (60020028) from remote peer".to_owned());
7763                 },
7764                 _ => panic!("Unexpected event"),
7765         }
7766         check_added_monitors!(nodes[0], 1);
7767 }
7768
7769 #[test]
7770 fn test_invalid_shutdown_script() {
7771         let mut config = UserConfig::default();
7772         config.channel_options.announced_channel = true;
7773         config.peer_channel_config_limits.force_announced_channel_preference = false;
7774         config.channel_options.commit_upfront_shutdown_pubkey = false;
7775         let user_cfgs = [None, Some(config), None];
7776         let chanmon_cfgs = create_chanmon_cfgs(3);
7777         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7778         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7779         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7780
7781         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7782         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7783         check_added_monitors!(nodes[1], 1);
7784
7785         // Use a segwit v0 script with an unsupported witness program
7786         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7787         node_0_shutdown.scriptpubkey = Builder::new().push_int(0)
7788                 .push_slice(&[0, 0])
7789                 .into_script();
7790         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7791
7792         let events = nodes[0].node.get_and_clear_pending_msg_events();
7793         assert_eq!(events.len(), 2);
7794         match events[1] {
7795                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7796                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7797                         assert_eq!(msg.data, "Got a nonstandard scriptpubkey (00020000) from remote peer".to_owned())
7798                 },
7799                 _ => panic!("Unexpected event"),
7800         }
7801         check_added_monitors!(nodes[0], 1);
7802 }
7803
7804 #[test]
7805 fn test_user_configurable_csv_delay() {
7806         // We test our channel constructors yield errors when we pass them absurd csv delay
7807
7808         let mut low_our_to_self_config = UserConfig::default();
7809         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7810         let mut high_their_to_self_config = UserConfig::default();
7811         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7812         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7813         let chanmon_cfgs = create_chanmon_cfgs(2);
7814         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7815         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7816         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7817
7818         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7819         if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0, &low_our_to_self_config) {
7820                 match error {
7821                         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())); },
7822                         _ => panic!("Unexpected event"),
7823                 }
7824         } else { assert!(false) }
7825
7826         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7827         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7828         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7829         open_channel.to_self_delay = 200;
7830         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0, &low_our_to_self_config) {
7831                 match error {
7832                         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()));  },
7833                         _ => panic!("Unexpected event"),
7834                 }
7835         } else { assert!(false); }
7836
7837         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7838         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7839         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()));
7840         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7841         accept_channel.to_self_delay = 200;
7842         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7843         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7844                 match action {
7845                         &ErrorAction::SendErrorMessage { ref msg } => {
7846                                 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()));
7847                         },
7848                         _ => { assert!(false); }
7849                 }
7850         } else { assert!(false); }
7851
7852         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7853         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7854         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7855         open_channel.to_self_delay = 200;
7856         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0, &high_their_to_self_config) {
7857                 match error {
7858                         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())); },
7859                         _ => panic!("Unexpected event"),
7860                 }
7861         } else { assert!(false); }
7862 }
7863
7864 #[test]
7865 fn test_data_loss_protect() {
7866         // We want to be sure that :
7867         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7868         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7869         // * we close channel in case of detecting other being fallen behind
7870         // * we are able to claim our own outputs thanks to to_remote being static
7871         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7872         let persister;
7873         let logger;
7874         let fee_estimator;
7875         let tx_broadcaster;
7876         let chain_source;
7877         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7878         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7879         // during signing due to revoked tx
7880         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7881         let keys_manager = &chanmon_cfgs[0].keys_manager;
7882         let monitor;
7883         let node_state_0;
7884         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7885         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7886         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7887
7888         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7889
7890         // Cache node A state before any channel update
7891         let previous_node_state = nodes[0].node.encode();
7892         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7893         nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7894
7895         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7896         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7897
7898         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7899         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7900
7901         // Restore node A from previous state
7902         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7903         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7904         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7905         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7906         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7907         persister = test_utils::TestPersister::new();
7908         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7909         node_state_0 = {
7910                 let mut channel_monitors = HashMap::new();
7911                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7912                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
7913                         keys_manager: keys_manager,
7914                         fee_estimator: &fee_estimator,
7915                         chain_monitor: &monitor,
7916                         logger: &logger,
7917                         tx_broadcaster: &tx_broadcaster,
7918                         default_config: UserConfig::default(),
7919                         channel_monitors,
7920                 }).unwrap().1
7921         };
7922         nodes[0].node = &node_state_0;
7923         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7924         nodes[0].chain_monitor = &monitor;
7925         nodes[0].chain_source = &chain_source;
7926
7927         check_added_monitors!(nodes[0], 1);
7928
7929         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7930         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7931
7932         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7933
7934         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7935         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7936         check_added_monitors!(nodes[0], 1);
7937
7938         {
7939                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7940                 assert_eq!(node_txn.len(), 0);
7941         }
7942
7943         let mut reestablish_1 = Vec::with_capacity(1);
7944         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7945                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7946                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7947                         reestablish_1.push(msg.clone());
7948                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7949                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7950                         match action {
7951                                 &ErrorAction::SendErrorMessage { ref msg } => {
7952                                         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");
7953                                 },
7954                                 _ => panic!("Unexpected event!"),
7955                         }
7956                 } else {
7957                         panic!("Unexpected event")
7958                 }
7959         }
7960
7961         // Check we close channel detecting A is fallen-behind
7962         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7963         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7964         check_added_monitors!(nodes[1], 1);
7965
7966
7967         // Check A is able to claim to_remote output
7968         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7969         assert_eq!(node_txn.len(), 1);
7970         check_spends!(node_txn[0], chan.3);
7971         assert_eq!(node_txn[0].output.len(), 2);
7972         mine_transaction(&nodes[0], &node_txn[0]);
7973         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7974         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7975         assert_eq!(spend_txn.len(), 1);
7976         check_spends!(spend_txn[0], node_txn[0]);
7977 }
7978
7979 #[test]
7980 fn test_check_htlc_underpaying() {
7981         // Send payment through A -> B but A is maliciously
7982         // sending a probe payment (i.e less than expected value0
7983         // to B, B should refuse payment.
7984
7985         let chanmon_cfgs = create_chanmon_cfgs(2);
7986         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7987         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7988         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7989
7990         // Create some initial channels
7991         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7992
7993         let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, TEST_FINAL_CLTV, nodes[0].logger).unwrap();
7994         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7995         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, 0).unwrap();
7996         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7997         check_added_monitors!(nodes[0], 1);
7998
7999         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8000         assert_eq!(events.len(), 1);
8001         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8002         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8003         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8004
8005         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
8006         // and then will wait a second random delay before failing the HTLC back:
8007         expect_pending_htlcs_forwardable!(nodes[1]);
8008         expect_pending_htlcs_forwardable!(nodes[1]);
8009
8010         // Node 3 is expecting payment of 100_000 but received 10_000,
8011         // it should fail htlc like we didn't know the preimage.
8012         nodes[1].node.process_pending_htlc_forwards();
8013
8014         let events = nodes[1].node.get_and_clear_pending_msg_events();
8015         assert_eq!(events.len(), 1);
8016         let (update_fail_htlc, commitment_signed) = match events[0] {
8017                 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 } } => {
8018                         assert!(update_add_htlcs.is_empty());
8019                         assert!(update_fulfill_htlcs.is_empty());
8020                         assert_eq!(update_fail_htlcs.len(), 1);
8021                         assert!(update_fail_malformed_htlcs.is_empty());
8022                         assert!(update_fee.is_none());
8023                         (update_fail_htlcs[0].clone(), commitment_signed)
8024                 },
8025                 _ => panic!("Unexpected event"),
8026         };
8027         check_added_monitors!(nodes[1], 1);
8028
8029         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
8030         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
8031
8032         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
8033         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
8034         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
8035         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
8036 }
8037
8038 #[test]
8039 fn test_announce_disable_channels() {
8040         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
8041         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
8042
8043         let chanmon_cfgs = create_chanmon_cfgs(2);
8044         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8045         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8046         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8047
8048         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8049         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8050         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8051
8052         // Disconnect peers
8053         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8054         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8055
8056         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
8057         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
8058         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
8059         assert_eq!(msg_events.len(), 3);
8060         let mut chans_disabled: HashSet<u64> = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
8061         for e in msg_events {
8062                 match e {
8063                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8064                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
8065                                 // Check that each channel gets updated exactly once
8066                                 if !chans_disabled.remove(&msg.contents.short_channel_id) {
8067                                         panic!("Generated ChannelUpdate for wrong chan!");
8068                                 }
8069                         },
8070                         _ => panic!("Unexpected event"),
8071                 }
8072         }
8073         // Reconnect peers
8074         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
8075         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
8076         assert_eq!(reestablish_1.len(), 3);
8077         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
8078         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
8079         assert_eq!(reestablish_2.len(), 3);
8080
8081         // Reestablish chan_1
8082         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
8083         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
8084         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
8085         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
8086         // Reestablish chan_2
8087         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
8088         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
8089         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
8090         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
8091         // Reestablish chan_3
8092         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
8093         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
8094         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
8095         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
8096
8097         nodes[0].node.timer_tick_occurred();
8098         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8099         nodes[0].node.timer_tick_occurred();
8100         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
8101         assert_eq!(msg_events.len(), 3);
8102         chans_disabled = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
8103         for e in msg_events {
8104                 match e {
8105                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8106                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
8107                                 // Check that each channel gets updated exactly once
8108                                 if !chans_disabled.remove(&msg.contents.short_channel_id) {
8109                                         panic!("Generated ChannelUpdate for wrong chan!");
8110                                 }
8111                         },
8112                         _ => panic!("Unexpected event"),
8113                 }
8114         }
8115 }
8116
8117 #[test]
8118 fn test_priv_forwarding_rejection() {
8119         // If we have a private channel with outbound liquidity, and
8120         // UserConfig::accept_forwards_to_priv_channels is set to false, we should reject any attempts
8121         // to forward through that channel.
8122         let chanmon_cfgs = create_chanmon_cfgs(3);
8123         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8124         let mut no_announce_cfg = test_default_channel_config();
8125         no_announce_cfg.channel_options.announced_channel = false;
8126         no_announce_cfg.accept_forwards_to_priv_channels = false;
8127         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]);
8128         let persister: test_utils::TestPersister;
8129         let new_chain_monitor: test_utils::TestChainMonitor;
8130         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
8131         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8132
8133         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
8134
8135         // Note that the create_*_chan functions in utils requires announcement_signatures, which we do
8136         // not send for private channels.
8137         nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
8138         let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[2].node.get_our_node_id());
8139         nodes[2].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
8140         let accept_channel = get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
8141         nodes[1].node.handle_accept_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
8142
8143         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[1], 1_000_000, 42);
8144         nodes[1].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8145         nodes[2].node.handle_funding_created(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingCreated, nodes[2].node.get_our_node_id()));
8146         check_added_monitors!(nodes[2], 1);
8147
8148         nodes[1].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[1].node.get_our_node_id()));
8149         check_added_monitors!(nodes[1], 1);
8150
8151         let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[2].best_block_info().1 + 1);
8152         confirm_transaction_at(&nodes[1], &tx, conf_height);
8153         connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
8154         confirm_transaction_at(&nodes[2], &tx, conf_height);
8155         connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
8156         let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[2].node.get_our_node_id());
8157         nodes[1].node.handle_funding_locked(&nodes[2].node.get_our_node_id(), &get_event_msg!(nodes[2], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id()));
8158         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
8159         nodes[2].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
8160         get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
8161
8162         assert!(nodes[0].node.list_usable_channels()[0].is_public);
8163         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8164         assert!(!nodes[2].node.list_usable_channels()[0].is_public);
8165
8166         // We should always be able to forward through nodes[1] as long as its out through a public
8167         // channel:
8168         send_payment(&nodes[2], &[&nodes[1], &nodes[0]], 10_000);
8169
8170         // ... however, if we send to nodes[2], we will have to pass the private channel from nodes[1]
8171         // to nodes[2], which should be rejected:
8172         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
8173         let route = get_route(&nodes[0].node.get_our_node_id(),
8174                 &nodes[0].net_graph_msg_handler.network_graph.read().unwrap(),
8175                 &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None,
8176                 &[&RouteHint(vec![RouteHintHop {
8177                         src_node_id: nodes[1].node.get_our_node_id(),
8178                         short_channel_id: nodes[2].node.list_channels()[0].short_channel_id.unwrap(),
8179                         fees: RoutingFees { base_msat: 1000, proportional_millionths: 0 },
8180                         cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
8181                         htlc_minimum_msat: None,
8182                         htlc_maximum_msat: None,
8183                 }])], 10_000, TEST_FINAL_CLTV, nodes[0].logger).unwrap();
8184
8185         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
8186         check_added_monitors!(nodes[0], 1);
8187         let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8188         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8189         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
8190
8191         let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8192         assert!(htlc_fail_updates.update_add_htlcs.is_empty());
8193         assert_eq!(htlc_fail_updates.update_fail_htlcs.len(), 1);
8194         assert!(htlc_fail_updates.update_fail_malformed_htlcs.is_empty());
8195         assert!(htlc_fail_updates.update_fee.is_none());
8196
8197         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
8198         commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, true, true);
8199         expect_payment_failed!(nodes[0], our_payment_hash, false);
8200         expect_payment_failure_chan_update!(nodes[0], nodes[2].node.list_channels()[0].short_channel_id.unwrap(), true);
8201
8202         // Now disconnect nodes[1] from its peers and restart with accept_forwards_to_priv_channels set
8203         // to true. Sadly there is currently no way to change it at runtime.
8204
8205         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8206         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8207
8208         let nodes_1_serialized = nodes[1].node.encode();
8209         let mut monitor_a_serialized = test_utils::TestVecWriter(Vec::new());
8210         let mut monitor_b_serialized = test_utils::TestVecWriter(Vec::new());
8211         {
8212                 let mons = nodes[1].chain_monitor.chain_monitor.monitors.read().unwrap();
8213                 let mut mon_iter = mons.iter();
8214                 mon_iter.next().unwrap().1.write(&mut monitor_a_serialized).unwrap();
8215                 mon_iter.next().unwrap().1.write(&mut monitor_b_serialized).unwrap();
8216         }
8217
8218         persister = test_utils::TestPersister::new();
8219         let keys_manager = &chanmon_cfgs[1].keys_manager;
8220         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[1].chain_source), nodes[1].tx_broadcaster.clone(), nodes[1].logger, node_cfgs[1].fee_estimator, &persister, keys_manager);
8221         nodes[1].chain_monitor = &new_chain_monitor;
8222
8223         let mut monitor_a_read = &monitor_a_serialized.0[..];
8224         let mut monitor_b_read = &monitor_b_serialized.0[..];
8225         let (_, mut monitor_a) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_a_read, keys_manager).unwrap();
8226         let (_, mut monitor_b) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_b_read, keys_manager).unwrap();
8227         assert!(monitor_a_read.is_empty());
8228         assert!(monitor_b_read.is_empty());
8229
8230         no_announce_cfg.accept_forwards_to_priv_channels = true;
8231
8232         let mut nodes_1_read = &nodes_1_serialized[..];
8233         let (_, nodes_1_deserialized_tmp) = {
8234                 let mut channel_monitors = HashMap::new();
8235                 channel_monitors.insert(monitor_a.get_funding_txo().0, &mut monitor_a);
8236                 channel_monitors.insert(monitor_b.get_funding_txo().0, &mut monitor_b);
8237                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
8238                         default_config: no_announce_cfg,
8239                         keys_manager,
8240                         fee_estimator: node_cfgs[1].fee_estimator,
8241                         chain_monitor: nodes[1].chain_monitor,
8242                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
8243                         logger: nodes[1].logger,
8244                         channel_monitors,
8245                 }).unwrap()
8246         };
8247         assert!(nodes_1_read.is_empty());
8248         nodes_1_deserialized = nodes_1_deserialized_tmp;
8249
8250         assert!(nodes[1].chain_monitor.watch_channel(monitor_a.get_funding_txo().0, monitor_a).is_ok());
8251         assert!(nodes[1].chain_monitor.watch_channel(monitor_b.get_funding_txo().0, monitor_b).is_ok());
8252         check_added_monitors!(nodes[1], 2);
8253         nodes[1].node = &nodes_1_deserialized;
8254
8255         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
8256         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
8257         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
8258         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8259         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
8260         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
8261         get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
8262         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
8263
8264         nodes[1].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
8265         nodes[2].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
8266         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[2].node.get_our_node_id());
8267         let cs_reestablish = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
8268         nodes[2].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
8269         nodes[1].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &cs_reestablish);
8270         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
8271         get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
8272
8273         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
8274         check_added_monitors!(nodes[0], 1);
8275         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 10_000, our_payment_hash, our_payment_secret);
8276         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage);
8277 }
8278
8279 #[test]
8280 fn test_bump_penalty_txn_on_revoked_commitment() {
8281         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
8282         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
8283
8284         let chanmon_cfgs = create_chanmon_cfgs(2);
8285         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8286         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8287         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8288
8289         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8290         let logger = test_utils::TestLogger::new();
8291
8292         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8293         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8294         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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3000000, 30, &logger).unwrap();
8295         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
8296
8297         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
8298         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8299         assert_eq!(revoked_txn[0].output.len(), 4);
8300         assert_eq!(revoked_txn[0].input.len(), 1);
8301         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
8302         let revoked_txid = revoked_txn[0].txid();
8303
8304         let mut penalty_sum = 0;
8305         for outp in revoked_txn[0].output.iter() {
8306                 if outp.script_pubkey.is_v0_p2wsh() {
8307                         penalty_sum += outp.value;
8308                 }
8309         }
8310
8311         // Connect blocks to change height_timer range to see if we use right soonest_timelock
8312         let header_114 = connect_blocks(&nodes[1], 14);
8313
8314         // Actually revoke tx by claiming a HTLC
8315         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8316         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8317         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
8318         check_added_monitors!(nodes[1], 1);
8319
8320         // One or more justice tx should have been broadcast, check it
8321         let penalty_1;
8322         let feerate_1;
8323         {
8324                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8325                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
8326                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
8327                 assert_eq!(node_txn[0].output.len(), 1);
8328                 check_spends!(node_txn[0], revoked_txn[0]);
8329                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
8330                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
8331                 penalty_1 = node_txn[0].txid();
8332                 node_txn.clear();
8333         };
8334
8335         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
8336         connect_blocks(&nodes[1], 15);
8337         let mut penalty_2 = penalty_1;
8338         let mut feerate_2 = 0;
8339         {
8340                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8341                 assert_eq!(node_txn.len(), 1);
8342                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
8343                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
8344                         assert_eq!(node_txn[0].output.len(), 1);
8345                         check_spends!(node_txn[0], revoked_txn[0]);
8346                         penalty_2 = node_txn[0].txid();
8347                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
8348                         assert_ne!(penalty_2, penalty_1);
8349                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
8350                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
8351                         // Verify 25% bump heuristic
8352                         assert!(feerate_2 * 100 >= feerate_1 * 125);
8353                         node_txn.clear();
8354                 }
8355         }
8356         assert_ne!(feerate_2, 0);
8357
8358         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
8359         connect_blocks(&nodes[1], 1);
8360         let penalty_3;
8361         let mut feerate_3 = 0;
8362         {
8363                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8364                 assert_eq!(node_txn.len(), 1);
8365                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
8366                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
8367                         assert_eq!(node_txn[0].output.len(), 1);
8368                         check_spends!(node_txn[0], revoked_txn[0]);
8369                         penalty_3 = node_txn[0].txid();
8370                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
8371                         assert_ne!(penalty_3, penalty_2);
8372                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
8373                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
8374                         // Verify 25% bump heuristic
8375                         assert!(feerate_3 * 100 >= feerate_2 * 125);
8376                         node_txn.clear();
8377                 }
8378         }
8379         assert_ne!(feerate_3, 0);
8380
8381         nodes[1].node.get_and_clear_pending_events();
8382         nodes[1].node.get_and_clear_pending_msg_events();
8383 }
8384
8385 #[test]
8386 fn test_bump_penalty_txn_on_revoked_htlcs() {
8387         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
8388         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
8389
8390         let mut chanmon_cfgs = create_chanmon_cfgs(2);
8391         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
8392         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8393         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8394         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8395
8396         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8397         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
8398         let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph.read().unwrap(),
8399                 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
8400         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
8401         let route = get_route(&nodes[1].node.get_our_node_id(), &nodes[1].net_graph_msg_handler.network_graph.read().unwrap(),
8402                 &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
8403         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
8404
8405         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8406         assert_eq!(revoked_local_txn[0].input.len(), 1);
8407         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8408
8409         // Revoke local commitment tx
8410         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8411
8412         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8413         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
8414         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
8415         check_closed_broadcast!(nodes[1], true);
8416         check_added_monitors!(nodes[1], 1);
8417         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
8418
8419         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8420         assert_eq!(revoked_htlc_txn.len(), 3);
8421         check_spends!(revoked_htlc_txn[1], chan.3);
8422
8423         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
8424         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
8425         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
8426
8427         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
8428         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8429         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
8430         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
8431
8432         // Broadcast set of revoked txn on A
8433         let hash_128 = connect_blocks(&nodes[0], 40);
8434         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8435         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
8436         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8437         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
8438         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8439         let first;
8440         let feerate_1;
8441         let penalty_txn;
8442         {
8443                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8444                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
8445                 // Verify claim tx are spending revoked HTLC txn
8446
8447                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
8448                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
8449                 // which are included in the same block (they are broadcasted because we scan the
8450                 // transactions linearly and generate claims as we go, they likely should be removed in the
8451                 // future).
8452                 assert_eq!(node_txn[0].input.len(), 1);
8453                 check_spends!(node_txn[0], revoked_local_txn[0]);
8454                 assert_eq!(node_txn[1].input.len(), 1);
8455                 check_spends!(node_txn[1], revoked_local_txn[0]);
8456                 assert_eq!(node_txn[2].input.len(), 1);
8457                 check_spends!(node_txn[2], revoked_local_txn[0]);
8458
8459                 // Each of the three justice transactions claim a separate (single) output of the three
8460                 // available, which we check here:
8461                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
8462                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
8463                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
8464
8465                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
8466                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
8467
8468                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
8469                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
8470                 // a remote commitment tx has already been confirmed).
8471                 check_spends!(node_txn[3], chan.3);
8472
8473                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
8474                 // output, checked above).
8475                 assert_eq!(node_txn[4].input.len(), 2);
8476                 assert_eq!(node_txn[4].output.len(), 1);
8477                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
8478
8479                 first = node_txn[4].txid();
8480                 // Store both feerates for later comparison
8481                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
8482                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
8483                 penalty_txn = vec![node_txn[2].clone()];
8484                 node_txn.clear();
8485         }
8486
8487         // Connect one more block to see if bumped penalty are issued for HTLC txn
8488         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8489         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8490         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8491         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
8492         {
8493                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8494                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
8495
8496                 check_spends!(node_txn[0], revoked_local_txn[0]);
8497                 check_spends!(node_txn[1], revoked_local_txn[0]);
8498                 // Note that these are both bogus - they spend outputs already claimed in block 129:
8499                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
8500                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
8501                 } else {
8502                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
8503                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
8504                 }
8505
8506                 node_txn.clear();
8507         };
8508
8509         // Few more blocks to confirm penalty txn
8510         connect_blocks(&nodes[0], 4);
8511         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
8512         let header_144 = connect_blocks(&nodes[0], 9);
8513         let node_txn = {
8514                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8515                 assert_eq!(node_txn.len(), 1);
8516
8517                 assert_eq!(node_txn[0].input.len(), 2);
8518                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
8519                 // Verify bumped tx is different and 25% bump heuristic
8520                 assert_ne!(first, node_txn[0].txid());
8521                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
8522                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
8523                 assert!(feerate_2 * 100 > feerate_1 * 125);
8524                 let txn = vec![node_txn[0].clone()];
8525                 node_txn.clear();
8526                 txn
8527         };
8528         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
8529         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8530         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
8531         connect_blocks(&nodes[0], 20);
8532         {
8533                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8534                 // We verify than no new transaction has been broadcast because previously
8535                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
8536                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
8537                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
8538                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
8539                 // up bumped justice generation.
8540                 assert_eq!(node_txn.len(), 0);
8541                 node_txn.clear();
8542         }
8543         check_closed_broadcast!(nodes[0], true);
8544         check_added_monitors!(nodes[0], 1);
8545 }
8546
8547 #[test]
8548 fn test_bump_penalty_txn_on_remote_commitment() {
8549         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
8550         // we're able to claim outputs on remote commitment transaction before timelocks expiration
8551
8552         // Create 2 HTLCs
8553         // Provide preimage for one
8554         // Check aggregation
8555
8556         let chanmon_cfgs = create_chanmon_cfgs(2);
8557         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8558         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8559         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8560
8561         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8562         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8563         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
8564
8565         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8566         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
8567         assert_eq!(remote_txn[0].output.len(), 4);
8568         assert_eq!(remote_txn[0].input.len(), 1);
8569         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8570
8571         // Claim a HTLC without revocation (provide B monitor with preimage)
8572         nodes[1].node.claim_funds(payment_preimage);
8573         mine_transaction(&nodes[1], &remote_txn[0]);
8574         check_added_monitors!(nodes[1], 2);
8575         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8576
8577         // One or more claim tx should have been broadcast, check it
8578         let timeout;
8579         let preimage;
8580         let preimage_bump;
8581         let feerate_timeout;
8582         let feerate_preimage;
8583         {
8584                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8585                 // 9 transactions including:
8586                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8587                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8588                 // 2 * HTLC-Success (one RBF bump we'll check later)
8589                 // 1 * HTLC-Timeout
8590                 assert_eq!(node_txn.len(), 8);
8591                 assert_eq!(node_txn[0].input.len(), 1);
8592                 assert_eq!(node_txn[6].input.len(), 1);
8593                 check_spends!(node_txn[0], remote_txn[0]);
8594                 check_spends!(node_txn[6], remote_txn[0]);
8595                 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
8596                 preimage_bump = node_txn[3].clone();
8597
8598                 check_spends!(node_txn[1], chan.3);
8599                 check_spends!(node_txn[2], node_txn[1]);
8600                 assert_eq!(node_txn[1], node_txn[4]);
8601                 assert_eq!(node_txn[2], node_txn[5]);
8602
8603                 timeout = node_txn[6].txid();
8604                 let index = node_txn[6].input[0].previous_output.vout;
8605                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8606                 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
8607
8608                 preimage = node_txn[0].txid();
8609                 let index = node_txn[0].input[0].previous_output.vout;
8610                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8611                 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
8612
8613                 node_txn.clear();
8614         };
8615         assert_ne!(feerate_timeout, 0);
8616         assert_ne!(feerate_preimage, 0);
8617
8618         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8619         connect_blocks(&nodes[1], 15);
8620         {
8621                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8622                 assert_eq!(node_txn.len(), 1);
8623                 assert_eq!(node_txn[0].input.len(), 1);
8624                 assert_eq!(preimage_bump.input.len(), 1);
8625                 check_spends!(node_txn[0], remote_txn[0]);
8626                 check_spends!(preimage_bump, remote_txn[0]);
8627
8628                 let index = preimage_bump.input[0].previous_output.vout;
8629                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8630                 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
8631                 assert!(new_feerate * 100 > feerate_timeout * 125);
8632                 assert_ne!(timeout, preimage_bump.txid());
8633
8634                 let index = node_txn[0].input[0].previous_output.vout;
8635                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8636                 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8637                 assert!(new_feerate * 100 > feerate_preimage * 125);
8638                 assert_ne!(preimage, node_txn[0].txid());
8639
8640                 node_txn.clear();
8641         }
8642
8643         nodes[1].node.get_and_clear_pending_events();
8644         nodes[1].node.get_and_clear_pending_msg_events();
8645 }
8646
8647 #[test]
8648 fn test_counterparty_raa_skip_no_crash() {
8649         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8650         // commitment transaction, we would have happily carried on and provided them the next
8651         // commitment transaction based on one RAA forward. This would probably eventually have led to
8652         // channel closure, but it would not have resulted in funds loss. Still, our
8653         // EnforcingSigner would have paniced as it doesn't like jumps into the future. Here, we
8654         // check simply that the channel is closed in response to such an RAA, but don't check whether
8655         // we decide to punish our counterparty for revoking their funds (as we don't currently
8656         // implement that).
8657         let chanmon_cfgs = create_chanmon_cfgs(2);
8658         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8659         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8660         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8661         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8662
8663         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8664         let keys = &guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8665         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8666         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8667         // Must revoke without gaps
8668         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8669         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8670                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8671
8672         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8673                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8674         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8675         check_added_monitors!(nodes[1], 1);
8676 }
8677
8678 #[test]
8679 fn test_bump_txn_sanitize_tracking_maps() {
8680         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8681         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8682
8683         let chanmon_cfgs = create_chanmon_cfgs(2);
8684         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8685         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8686         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8687
8688         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8689         // Lock HTLC in both directions
8690         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8691         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8692
8693         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8694         assert_eq!(revoked_local_txn[0].input.len(), 1);
8695         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8696
8697         // Revoke local commitment tx
8698         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8699
8700         // Broadcast set of revoked txn on A
8701         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8702         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8703         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8704
8705         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8706         check_closed_broadcast!(nodes[0], true);
8707         check_added_monitors!(nodes[0], 1);
8708         let penalty_txn = {
8709                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8710                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8711                 check_spends!(node_txn[0], revoked_local_txn[0]);
8712                 check_spends!(node_txn[1], revoked_local_txn[0]);
8713                 check_spends!(node_txn[2], revoked_local_txn[0]);
8714                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8715                 node_txn.clear();
8716                 penalty_txn
8717         };
8718         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8719         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8720         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8721         {
8722                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8723                 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8724                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8725                         assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8726                 }
8727         }
8728 }
8729
8730 #[test]
8731 fn test_override_channel_config() {
8732         let chanmon_cfgs = create_chanmon_cfgs(2);
8733         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8734         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8735         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8736
8737         // Node0 initiates a channel to node1 using the override config.
8738         let mut override_config = UserConfig::default();
8739         override_config.own_channel_config.our_to_self_delay = 200;
8740
8741         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8742
8743         // Assert the channel created by node0 is using the override config.
8744         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8745         assert_eq!(res.channel_flags, 0);
8746         assert_eq!(res.to_self_delay, 200);
8747 }
8748
8749 #[test]
8750 fn test_override_0msat_htlc_minimum() {
8751         let mut zero_config = UserConfig::default();
8752         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8753         let chanmon_cfgs = create_chanmon_cfgs(2);
8754         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8755         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8756         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8757
8758         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8759         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8760         assert_eq!(res.htlc_minimum_msat, 1);
8761
8762         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8763         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8764         assert_eq!(res.htlc_minimum_msat, 1);
8765 }
8766
8767 #[test]
8768 fn test_simple_mpp() {
8769         // Simple test of sending a multi-path payment.
8770         let chanmon_cfgs = create_chanmon_cfgs(4);
8771         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8772         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8773         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8774
8775         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8776         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8777         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8778         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8779         let logger = test_utils::TestLogger::new();
8780
8781         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[3]);
8782         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8783         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(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8784         let path = route.paths[0].clone();
8785         route.paths.push(path);
8786         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8787         route.paths[0][0].short_channel_id = chan_1_id;
8788         route.paths[0][1].short_channel_id = chan_3_id;
8789         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8790         route.paths[1][0].short_channel_id = chan_2_id;
8791         route.paths[1][1].short_channel_id = chan_4_id;
8792         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8793         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8794 }
8795
8796 #[test]
8797 fn test_preimage_storage() {
8798         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8799         let chanmon_cfgs = create_chanmon_cfgs(2);
8800         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8801         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8802         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8803
8804         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8805
8806         {
8807                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, 42);
8808
8809                 let logger = test_utils::TestLogger::new();
8810                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8811                 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(), Some(InvoiceFeatures::known()), None, &[], 100_000, TEST_FINAL_CLTV, &logger).unwrap();
8812                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8813                 check_added_monitors!(nodes[0], 1);
8814                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8815                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8816                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8817                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8818         }
8819         // Note that after leaving the above scope we have no knowledge of any arguments or return
8820         // values from previous calls.
8821         expect_pending_htlcs_forwardable!(nodes[1]);
8822         let events = nodes[1].node.get_and_clear_pending_events();
8823         assert_eq!(events.len(), 1);
8824         match events[0] {
8825                 Event::PaymentReceived { ref purpose, .. } => {
8826                         match &purpose {
8827                                 PaymentPurpose::InvoicePayment { payment_preimage, user_payment_id, .. } => {
8828                                         assert_eq!(*user_payment_id, 42);
8829                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8830                                 },
8831                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8832                         }
8833                 },
8834                 _ => panic!("Unexpected event"),
8835         }
8836 }
8837
8838 #[test]
8839 fn test_secret_timeout() {
8840         // Simple test of payment secret storage time outs
8841         let chanmon_cfgs = create_chanmon_cfgs(2);
8842         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8843         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8844         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8845
8846         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8847
8848         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8849
8850         // We should fail to register the same payment hash twice, at least until we've connected a
8851         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8852         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8853                 assert_eq!(err, "Duplicate payment hash");
8854         } else { panic!(); }
8855         let mut block = {
8856                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8857                 Block {
8858                         header: BlockHeader {
8859                                 version: 0x2000000,
8860                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8861                                 merkle_root: Default::default(),
8862                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8863                         txdata: vec![],
8864                 }
8865         };
8866         connect_block(&nodes[1], &block);
8867         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8868                 assert_eq!(err, "Duplicate payment hash");
8869         } else { panic!(); }
8870
8871         // If we then connect the second block, we should be able to register the same payment hash
8872         // again with a different user_payment_id (this time getting a new payment secret).
8873         block.header.prev_blockhash = block.header.block_hash();
8874         block.header.time += 1;
8875         connect_block(&nodes[1], &block);
8876         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 42).unwrap();
8877         assert_ne!(payment_secret_1, our_payment_secret);
8878
8879         {
8880                 let logger = test_utils::TestLogger::new();
8881                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8882                 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(), Some(InvoiceFeatures::known()), None, &[], 100_000, TEST_FINAL_CLTV, &logger).unwrap();
8883                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8884                 check_added_monitors!(nodes[0], 1);
8885                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8886                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8887                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8888                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8889         }
8890         // Note that after leaving the above scope we have no knowledge of any arguments or return
8891         // values from previous calls.
8892         expect_pending_htlcs_forwardable!(nodes[1]);
8893         let events = nodes[1].node.get_and_clear_pending_events();
8894         assert_eq!(events.len(), 1);
8895         match events[0] {
8896                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, user_payment_id }, .. } => {
8897                         assert!(payment_preimage.is_none());
8898                         assert_eq!(user_payment_id, 42);
8899                         assert_eq!(payment_secret, our_payment_secret);
8900                         // We don't actually have the payment preimage with which to claim this payment!
8901                 },
8902                 _ => panic!("Unexpected event"),
8903         }
8904 }
8905
8906 #[test]
8907 fn test_bad_secret_hash() {
8908         // Simple test of unregistered payment hash/invalid payment secret handling
8909         let chanmon_cfgs = create_chanmon_cfgs(2);
8910         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8911         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8912         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8913
8914         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8915
8916         let random_payment_hash = PaymentHash([42; 32]);
8917         let random_payment_secret = PaymentSecret([43; 32]);
8918         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8919
8920         let logger = test_utils::TestLogger::new();
8921         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8922         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(), Some(InvoiceFeatures::known()), None, &[], 100_000, TEST_FINAL_CLTV, &logger).unwrap();
8923
8924         // All the below cases should end up being handled exactly identically, so we macro the
8925         // resulting events.
8926         macro_rules! handle_unknown_invalid_payment_data {
8927                 () => {
8928                         check_added_monitors!(nodes[0], 1);
8929                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8930                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8931                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8932                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8933
8934                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8935                         // again to process the pending backwards-failure of the HTLC
8936                         expect_pending_htlcs_forwardable!(nodes[1]);
8937                         expect_pending_htlcs_forwardable!(nodes[1]);
8938                         check_added_monitors!(nodes[1], 1);
8939
8940                         // We should fail the payment back
8941                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8942                         match events.pop().unwrap() {
8943                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8944                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8945                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8946                                 },
8947                                 _ => panic!("Unexpected event"),
8948                         }
8949                 }
8950         }
8951
8952         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8953         // Error data is the HTLC value (100,000) and current block height
8954         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8955
8956         // Send a payment with the right payment hash but the wrong payment secret
8957         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8958         handle_unknown_invalid_payment_data!();
8959         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8960
8961         // Send a payment with a random payment hash, but the right payment secret
8962         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8963         handle_unknown_invalid_payment_data!();
8964         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8965
8966         // Send a payment with a random payment hash and random payment secret
8967         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8968         handle_unknown_invalid_payment_data!();
8969         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8970 }
8971
8972 #[test]
8973 fn test_update_err_monitor_lockdown() {
8974         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8975         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8976         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8977         //
8978         // This scenario may happen in a watchtower setup, where watchtower process a block height
8979         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8980         // commitment at same time.
8981
8982         let chanmon_cfgs = create_chanmon_cfgs(2);
8983         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8984         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8985         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8986
8987         // Create some initial channel
8988         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8989         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8990
8991         // Rebalance the network to generate htlc in the two directions
8992         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8993
8994         // Route a HTLC from node 0 to node 1 (but don't settle)
8995         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8996
8997         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8998         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8999         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
9000         let persister = test_utils::TestPersister::new();
9001         let watchtower = {
9002                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
9003                 let monitor = monitors.get(&outpoint).unwrap();
9004                 let mut w = test_utils::TestVecWriter(Vec::new());
9005                 monitor.write(&mut w).unwrap();
9006                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
9007                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
9008                 assert!(new_monitor == *monitor);
9009                 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);
9010                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
9011                 watchtower
9012         };
9013         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9014         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
9015         // transaction lock time requirements here.
9016         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
9017         watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
9018
9019         // Try to update ChannelMonitor
9020         assert!(nodes[1].node.claim_funds(preimage));
9021         check_added_monitors!(nodes[1], 1);
9022         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9023         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9024         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
9025         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
9026                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
9027                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
9028                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
9029                 } else { assert!(false); }
9030         } else { assert!(false); };
9031         // Our local monitor is in-sync and hasn't processed yet timeout
9032         check_added_monitors!(nodes[0], 1);
9033         let events = nodes[0].node.get_and_clear_pending_events();
9034         assert_eq!(events.len(), 1);
9035 }
9036
9037 #[test]
9038 fn test_concurrent_monitor_claim() {
9039         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
9040         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
9041         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
9042         // state N+1 confirms. Alice claims output from state N+1.
9043
9044         let chanmon_cfgs = create_chanmon_cfgs(2);
9045         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9046         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9047         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9048
9049         // Create some initial channel
9050         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9051         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
9052
9053         // Rebalance the network to generate htlc in the two directions
9054         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
9055
9056         // Route a HTLC from node 0 to node 1 (but don't settle)
9057         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
9058
9059         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
9060         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
9061         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
9062         let persister = test_utils::TestPersister::new();
9063         let watchtower_alice = {
9064                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
9065                 let monitor = monitors.get(&outpoint).unwrap();
9066                 let mut w = test_utils::TestVecWriter(Vec::new());
9067                 monitor.write(&mut w).unwrap();
9068                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
9069                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
9070                 assert!(new_monitor == *monitor);
9071                 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);
9072                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
9073                 watchtower
9074         };
9075         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9076         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
9077         // transaction lock time requirements here.
9078         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
9079         watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
9080
9081         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
9082         {
9083                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9084                 assert_eq!(txn.len(), 2);
9085                 txn.clear();
9086         }
9087
9088         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
9089         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
9090         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
9091         let persister = test_utils::TestPersister::new();
9092         let watchtower_bob = {
9093                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
9094                 let monitor = monitors.get(&outpoint).unwrap();
9095                 let mut w = test_utils::TestVecWriter(Vec::new());
9096                 monitor.write(&mut w).unwrap();
9097                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
9098                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
9099                 assert!(new_monitor == *monitor);
9100                 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);
9101                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
9102                 watchtower
9103         };
9104         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9105         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
9106
9107         // Route another payment to generate another update with still previous HTLC pending
9108         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[0]);
9109         {
9110                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
9111                 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(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3000000 , TEST_FINAL_CLTV, &logger).unwrap();
9112                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9113         }
9114         check_added_monitors!(nodes[1], 1);
9115
9116         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9117         assert_eq!(updates.update_add_htlcs.len(), 1);
9118         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
9119         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
9120                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
9121                         // Watchtower Alice should already have seen the block and reject the update
9122                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
9123                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
9124                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
9125                 } else { assert!(false); }
9126         } else { assert!(false); };
9127         // Our local monitor is in-sync and hasn't processed yet timeout
9128         check_added_monitors!(nodes[0], 1);
9129
9130         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
9131         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9132         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
9133
9134         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
9135         let bob_state_y;
9136         {
9137                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9138                 assert_eq!(txn.len(), 2);
9139                 bob_state_y = txn[0].clone();
9140                 txn.clear();
9141         };
9142
9143         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
9144         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9145         watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![bob_state_y.clone()] }, CHAN_CONFIRM_DEPTH + 2 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
9146         {
9147                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9148                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
9149                 // the onchain detection of the HTLC output
9150                 assert_eq!(htlc_txn.len(), 2);
9151                 check_spends!(htlc_txn[0], bob_state_y);
9152                 check_spends!(htlc_txn[1], bob_state_y);
9153         }
9154 }
9155
9156 #[test]
9157 fn test_pre_lockin_no_chan_closed_update() {
9158         // Test that if a peer closes a channel in response to a funding_created message we don't
9159         // generate a channel update (as the channel cannot appear on chain without a funding_signed
9160         // message).
9161         //
9162         // Doing so would imply a channel monitor update before the initial channel monitor
9163         // registration, violating our API guarantees.
9164         //
9165         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
9166         // then opening a second channel with the same funding output as the first (which is not
9167         // rejected because the first channel does not exist in the ChannelManager) and closing it
9168         // before receiving funding_signed.
9169         let chanmon_cfgs = create_chanmon_cfgs(2);
9170         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9171         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9172         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9173
9174         // Create an initial channel
9175         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9176         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9177         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9178         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9179         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
9180
9181         // Move the first channel through the funding flow...
9182         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
9183
9184         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9185         check_added_monitors!(nodes[0], 0);
9186
9187         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9188         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
9189         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
9190         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
9191 }
9192
9193 #[test]
9194 fn test_htlc_no_detection() {
9195         // This test is a mutation to underscore the detection logic bug we had
9196         // before #653. HTLC value routed is above the remaining balance, thus
9197         // inverting HTLC and `to_remote` output. HTLC will come second and
9198         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
9199         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
9200         // outputs order detection for correct spending children filtring.
9201
9202         let chanmon_cfgs = create_chanmon_cfgs(2);
9203         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9204         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9205         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9206
9207         // Create some initial channels
9208         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9209
9210         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
9211         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
9212         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
9213         assert_eq!(local_txn[0].input.len(), 1);
9214         assert_eq!(local_txn[0].output.len(), 3);
9215         check_spends!(local_txn[0], chan_1.3);
9216
9217         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9218         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9219         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
9220         // We deliberately connect the local tx twice as this should provoke a failure calling
9221         // this test before #653 fix.
9222         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);
9223         check_closed_broadcast!(nodes[0], true);
9224         check_added_monitors!(nodes[0], 1);
9225         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
9226
9227         let htlc_timeout = {
9228                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9229                 assert_eq!(node_txn[1].input.len(), 1);
9230                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9231                 check_spends!(node_txn[1], local_txn[0]);
9232                 node_txn[1].clone()
9233         };
9234
9235         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9236         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9237         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9238         expect_payment_failed!(nodes[0], our_payment_hash, true);
9239 }
9240
9241 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9242         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9243         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9244         // Carol, Alice would be the upstream node, and Carol the downstream.)
9245         //
9246         // Steps of the test:
9247         // 1) Alice sends a HTLC to Carol through Bob.
9248         // 2) Carol doesn't settle the HTLC.
9249         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9250         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9251         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9252         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9253         // 5) Carol release the preimage to Bob off-chain.
9254         // 6) Bob claims the offered output on the broadcasted commitment.
9255         let chanmon_cfgs = create_chanmon_cfgs(3);
9256         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9257         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9258         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9259
9260         // Create some initial channels
9261         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9262         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9263
9264         // Steps (1) and (2):
9265         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9266         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
9267
9268         // Check that Alice's commitment transaction now contains an output for this HTLC.
9269         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9270         check_spends!(alice_txn[0], chan_ab.3);
9271         assert_eq!(alice_txn[0].output.len(), 2);
9272         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9273         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9274         assert_eq!(alice_txn.len(), 2);
9275
9276         // Steps (3) and (4):
9277         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9278         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9279         let mut force_closing_node = 0; // Alice force-closes
9280         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
9281         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
9282         check_closed_broadcast!(nodes[force_closing_node], true);
9283         check_added_monitors!(nodes[force_closing_node], 1);
9284         if go_onchain_before_fulfill {
9285                 let txn_to_broadcast = match broadcast_alice {
9286                         true => alice_txn.clone(),
9287                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9288                 };
9289                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9290                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9291                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9292                 if broadcast_alice {
9293                         check_closed_broadcast!(nodes[1], true);
9294                         check_added_monitors!(nodes[1], 1);
9295                 }
9296                 assert_eq!(bob_txn.len(), 1);
9297                 check_spends!(bob_txn[0], chan_ab.3);
9298         }
9299
9300         // Step (5):
9301         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9302         // process of removing the HTLC from their commitment transactions.
9303         assert!(nodes[2].node.claim_funds(payment_preimage));
9304         check_added_monitors!(nodes[2], 1);
9305         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9306         assert!(carol_updates.update_add_htlcs.is_empty());
9307         assert!(carol_updates.update_fail_htlcs.is_empty());
9308         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9309         assert!(carol_updates.update_fee.is_none());
9310         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9311
9312         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9313         expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
9314         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9315         if !go_onchain_before_fulfill && broadcast_alice {
9316                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9317                 assert_eq!(events.len(), 1);
9318                 match events[0] {
9319                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9320                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9321                         },
9322                         _ => panic!("Unexpected event"),
9323                 };
9324         }
9325         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9326         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9327         // Carol<->Bob's updated commitment transaction info.
9328         check_added_monitors!(nodes[1], 2);
9329
9330         let events = nodes[1].node.get_and_clear_pending_msg_events();
9331         assert_eq!(events.len(), 2);
9332         let bob_revocation = match events[0] {
9333                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9334                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9335                         (*msg).clone()
9336                 },
9337                 _ => panic!("Unexpected event"),
9338         };
9339         let bob_updates = match events[1] {
9340                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9341                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9342                         (*updates).clone()
9343                 },
9344                 _ => panic!("Unexpected event"),
9345         };
9346
9347         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9348         check_added_monitors!(nodes[2], 1);
9349         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9350         check_added_monitors!(nodes[2], 1);
9351
9352         let events = nodes[2].node.get_and_clear_pending_msg_events();
9353         assert_eq!(events.len(), 1);
9354         let carol_revocation = match events[0] {
9355                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9356                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9357                         (*msg).clone()
9358                 },
9359                 _ => panic!("Unexpected event"),
9360         };
9361         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9362         check_added_monitors!(nodes[1], 1);
9363
9364         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9365         // here's where we put said channel's commitment tx on-chain.
9366         let mut txn_to_broadcast = alice_txn.clone();
9367         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9368         if !go_onchain_before_fulfill {
9369                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9370                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9371                 // If Bob was the one to force-close, he will have already passed these checks earlier.
9372                 if broadcast_alice {
9373                         check_closed_broadcast!(nodes[1], true);
9374                         check_added_monitors!(nodes[1], 1);
9375                 }
9376                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9377                 if broadcast_alice {
9378                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9379                         // new block being connected. The ChannelManager being notified triggers a monitor update,
9380                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9381                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9382                         // broadcasted.
9383                         assert_eq!(bob_txn.len(), 3);
9384                         check_spends!(bob_txn[1], chan_ab.3);
9385                 } else {
9386                         assert_eq!(bob_txn.len(), 2);
9387                         check_spends!(bob_txn[0], chan_ab.3);
9388                 }
9389         }
9390
9391         // Step (6):
9392         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9393         // broadcasted commitment transaction.
9394         {
9395                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9396                 if go_onchain_before_fulfill {
9397                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9398                         assert_eq!(bob_txn.len(), 2);
9399                 }
9400                 let script_weight = match broadcast_alice {
9401                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
9402                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9403                 };
9404                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9405                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9406                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9407                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9408                 if broadcast_alice && !go_onchain_before_fulfill {
9409                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
9410                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9411                 } else {
9412                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
9413                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9414                 }
9415         }
9416 }
9417
9418 #[test]
9419 fn test_onchain_htlc_settlement_after_close() {
9420         do_test_onchain_htlc_settlement_after_close(true, true);
9421         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9422         do_test_onchain_htlc_settlement_after_close(true, false);
9423         do_test_onchain_htlc_settlement_after_close(false, false);
9424 }
9425
9426 #[test]
9427 fn test_duplicate_chan_id() {
9428         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9429         // already open we reject it and keep the old channel.
9430         //
9431         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9432         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9433         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9434         // updating logic for the existing channel.
9435         let chanmon_cfgs = create_chanmon_cfgs(2);
9436         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9437         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9438         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9439
9440         // Create an initial channel
9441         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9442         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9443         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9444         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()));
9445
9446         // Try to create a second channel with the same temporary_channel_id as the first and check
9447         // that it is rejected.
9448         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9449         {
9450                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9451                 assert_eq!(events.len(), 1);
9452                 match events[0] {
9453                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9454                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9455                                 // first (valid) and second (invalid) channels are closed, given they both have
9456                                 // the same non-temporary channel_id. However, currently we do not, so we just
9457                                 // move forward with it.
9458                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9459                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9460                         },
9461                         _ => panic!("Unexpected event"),
9462                 }
9463         }
9464
9465         // Move the first channel through the funding flow...
9466         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
9467
9468         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9469         check_added_monitors!(nodes[0], 0);
9470
9471         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9472         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9473         {
9474                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9475                 assert_eq!(added_monitors.len(), 1);
9476                 assert_eq!(added_monitors[0].0, funding_output);
9477                 added_monitors.clear();
9478         }
9479         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9480
9481         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9482         let channel_id = funding_outpoint.to_channel_id();
9483
9484         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9485         // temporary one).
9486
9487         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9488         // Technically this is allowed by the spec, but we don't support it and there's little reason
9489         // to. Still, it shouldn't cause any other issues.
9490         open_chan_msg.temporary_channel_id = channel_id;
9491         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9492         {
9493                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9494                 assert_eq!(events.len(), 1);
9495                 match events[0] {
9496                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9497                                 // Technically, at this point, nodes[1] would be justified in thinking both
9498                                 // channels are closed, but currently we do not, so we just move forward with it.
9499                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9500                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9501                         },
9502                         _ => panic!("Unexpected event"),
9503                 }
9504         }
9505
9506         // Now try to create a second channel which has a duplicate funding output.
9507         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9508         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9509         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9510         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()));
9511         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
9512
9513         let funding_created = {
9514                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9515                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
9516                 let logger = test_utils::TestLogger::new();
9517                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9518         };
9519         check_added_monitors!(nodes[0], 0);
9520         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9521         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9522         // still needs to be cleared here.
9523         check_added_monitors!(nodes[1], 1);
9524
9525         // ...still, nodes[1] will reject the duplicate channel.
9526         {
9527                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9528                 assert_eq!(events.len(), 1);
9529                 match events[0] {
9530                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9531                                 // Technically, at this point, nodes[1] would be justified in thinking both
9532                                 // channels are closed, but currently we do not, so we just move forward with it.
9533                                 assert_eq!(msg.channel_id, channel_id);
9534                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9535                         },
9536                         _ => panic!("Unexpected event"),
9537                 }
9538         }
9539
9540         // finally, finish creating the original channel and send a payment over it to make sure
9541         // everything is functional.
9542         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9543         {
9544                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9545                 assert_eq!(added_monitors.len(), 1);
9546                 assert_eq!(added_monitors[0].0, funding_output);
9547                 added_monitors.clear();
9548         }
9549
9550         let events_4 = nodes[0].node.get_and_clear_pending_events();
9551         assert_eq!(events_4.len(), 0);
9552         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9553         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
9554
9555         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9556         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9557         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9558         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9559 }
9560
9561 #[test]
9562 fn test_error_chans_closed() {
9563         // Test that we properly handle error messages, closing appropriate channels.
9564         //
9565         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9566         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9567         // we can test various edge cases around it to ensure we don't regress.
9568         let chanmon_cfgs = create_chanmon_cfgs(3);
9569         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9570         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9571         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9572
9573         // Create some initial channels
9574         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9575         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9576         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9577
9578         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9579         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9580         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9581
9582         // Closing a channel from a different peer has no effect
9583         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9584         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9585
9586         // Closing one channel doesn't impact others
9587         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9588         check_added_monitors!(nodes[0], 1);
9589         check_closed_broadcast!(nodes[0], false);
9590         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9591         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9592         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);
9593         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);
9594
9595         // A null channel ID should close all channels
9596         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9597         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9598         check_added_monitors!(nodes[0], 2);
9599         let events = nodes[0].node.get_and_clear_pending_msg_events();
9600         assert_eq!(events.len(), 2);
9601         match events[0] {
9602                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9603                         assert_eq!(msg.contents.flags & 2, 2);
9604                 },
9605                 _ => panic!("Unexpected event"),
9606         }
9607         match events[1] {
9608                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9609                         assert_eq!(msg.contents.flags & 2, 2);
9610                 },
9611                 _ => panic!("Unexpected event"),
9612         }
9613         // Note that at this point users of a standard PeerHandler will end up calling
9614         // peer_disconnected with no_connection_possible set to false, duplicating the
9615         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9616         // users with their own peer handling logic. We duplicate the call here, however.
9617         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9618         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9619
9620         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9621         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9622         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9623 }
9624
9625 #[test]
9626 fn test_invalid_funding_tx() {
9627         // Test that we properly handle invalid funding transactions sent to us from a peer.
9628         //
9629         // Previously, all other major lightning implementations had failed to properly sanitize
9630         // funding transactions from their counterparties, leading to a multi-implementation critical
9631         // security vulnerability (though we always sanitized properly, we've previously had
9632         // un-released crashes in the sanitization process).
9633         let chanmon_cfgs = create_chanmon_cfgs(2);
9634         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9635         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9636         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9637
9638         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9639         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()));
9640         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()));
9641
9642         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
9643         for output in tx.output.iter_mut() {
9644                 // Make the confirmed funding transaction have a bogus script_pubkey
9645                 output.script_pubkey = bitcoin::Script::new();
9646         }
9647
9648         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
9649         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id()));
9650         check_added_monitors!(nodes[1], 1);
9651
9652         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id()));
9653         check_added_monitors!(nodes[0], 1);
9654
9655         let events_1 = nodes[0].node.get_and_clear_pending_events();
9656         assert_eq!(events_1.len(), 0);
9657
9658         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9659         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9660         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9661
9662         confirm_transaction_at(&nodes[1], &tx, 1);
9663         check_added_monitors!(nodes[1], 1);
9664         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9665         assert_eq!(events_2.len(), 1);
9666         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9667                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9668                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9669                         assert_eq!(msg.data, "funding tx had wrong script/value or output index");
9670                 } else { panic!(); }
9671         } else { panic!(); }
9672         assert_eq!(nodes[1].node.list_channels().len(), 0);
9673 }
9674
9675 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9676         // In the first version of the chain::Confirm interface, after a refactor was made to not
9677         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9678         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9679         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9680         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9681         // spending transaction until height N+1 (or greater). This was due to the way
9682         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9683         // spending transaction at the height the input transaction was confirmed at, not whether we
9684         // should broadcast a spending transaction at the current height.
9685         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9686         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9687         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9688         // until we learned about an additional block.
9689         //
9690         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9691         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9692         let chanmon_cfgs = create_chanmon_cfgs(3);
9693         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9694         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9695         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9696         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9697
9698         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9699         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9700         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9701         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9702         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9703
9704         nodes[1].node.force_close_channel(&channel_id).unwrap();
9705         check_closed_broadcast!(nodes[1], true);
9706         check_added_monitors!(nodes[1], 1);
9707         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9708         assert_eq!(node_txn.len(), 1);
9709
9710         let conf_height = nodes[1].best_block_info().1;
9711         if !test_height_before_timelock {
9712                 connect_blocks(&nodes[1], 24 * 6);
9713         }
9714         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9715                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9716         if test_height_before_timelock {
9717                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9718                 // generate any events or broadcast any transactions
9719                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9720                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9721         } else {
9722                 // We should broadcast an HTLC transaction spending our funding transaction first
9723                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9724                 assert_eq!(spending_txn.len(), 2);
9725                 assert_eq!(spending_txn[0], node_txn[0]);
9726                 check_spends!(spending_txn[1], node_txn[0]);
9727                 // We should also generate a SpendableOutputs event with the to_self output (as its
9728                 // timelock is up).
9729                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9730                 assert_eq!(descriptor_spend_txn.len(), 1);
9731
9732                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9733                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9734                 // additional block built on top of the current chain.
9735                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9736                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9737                 expect_pending_htlcs_forwardable!(nodes[1]);
9738                 check_added_monitors!(nodes[1], 1);
9739
9740                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9741                 assert!(updates.update_add_htlcs.is_empty());
9742                 assert!(updates.update_fulfill_htlcs.is_empty());
9743                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9744                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9745                 assert!(updates.update_fee.is_none());
9746                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9747                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9748                 expect_payment_failed!(nodes[0], payment_hash, false);
9749                 expect_payment_failure_chan_update!(nodes[0], chan_announce.contents.short_channel_id, true);
9750         }
9751 }
9752
9753 #[test]
9754 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9755         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9756         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9757 }
9758
9759 #[test]
9760 fn test_keysend_payments_to_public_node() {
9761         let chanmon_cfgs = create_chanmon_cfgs(2);
9762         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9763         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9764         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9765
9766         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9767         let network_graph = nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
9768         let payer_pubkey = nodes[0].node.get_our_node_id();
9769         let payee_pubkey = nodes[1].node.get_our_node_id();
9770         let route = get_route(&payer_pubkey, &network_graph, &payee_pubkey, None,
9771                         None, &vec![], 10000, 40,
9772                         nodes[0].logger).unwrap();
9773
9774         let test_preimage = PaymentPreimage([42; 32]);
9775         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9776         check_added_monitors!(nodes[0], 1);
9777         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9778         assert_eq!(events.len(), 1);
9779         let event = events.pop().unwrap();
9780         let path = vec![&nodes[1]];
9781         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9782         claim_payment(&nodes[0], &path, test_preimage);
9783 }
9784
9785 #[test]
9786 fn test_keysend_payments_to_private_node() {
9787         let chanmon_cfgs = create_chanmon_cfgs(2);
9788         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9789         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9790         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9791
9792         let payer_pubkey = nodes[0].node.get_our_node_id();
9793         let payee_pubkey = nodes[1].node.get_our_node_id();
9794         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known() });
9795         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known() });
9796
9797         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9798         let network_graph = nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
9799         let first_hops = nodes[0].node.list_usable_channels();
9800         let route = get_keysend_route(&payer_pubkey, &network_graph, &payee_pubkey,
9801                                 Some(&first_hops.iter().collect::<Vec<_>>()), &vec![], 10000, 40,
9802                                 nodes[0].logger).unwrap();
9803
9804         let test_preimage = PaymentPreimage([42; 32]);
9805         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9806         check_added_monitors!(nodes[0], 1);
9807         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9808         assert_eq!(events.len(), 1);
9809         let event = events.pop().unwrap();
9810         let path = vec![&nodes[1]];
9811         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9812         claim_payment(&nodes[0], &path, test_preimage);
9813 }
9814
9815 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, at_forward: bool, on_holder_tx: bool) {
9816         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat` policy.
9817         //
9818         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9819         // trimmed-to-dust HTLC outbound balance and this new payment as included on next counterparty
9820         // commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the update.
9821         // At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC inbound
9822         // and trimmed-to-dust HTLC outbound balance and this new received HTLC as included on next
9823         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail the update.
9824         // Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel might be
9825         // available again for HTLC processing once the dust bandwidth has cleared up.
9826
9827         let chanmon_cfgs = create_chanmon_cfgs(2);
9828         let mut config = test_default_channel_config();
9829         config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9830         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9831         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(config)]);
9832         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9833
9834         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9835         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9836         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9837         open_channel.max_accepted_htlcs = 60;
9838         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
9839         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9840         if on_holder_tx {
9841                 accept_channel.dust_limit_satoshis = 660;
9842         }
9843         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
9844
9845         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 1_000_000, 42);
9846
9847         if on_holder_tx {
9848                 if let Some(mut chan) = nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9849                         chan.holder_dust_limit_satoshis = 660;
9850                 }
9851         }
9852
9853         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9854         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id()));
9855         check_added_monitors!(nodes[1], 1);
9856
9857         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id()));
9858         check_added_monitors!(nodes[0], 1);
9859
9860         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9861         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9862         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9863
9864         if on_holder_tx {
9865                 if dust_outbound_balance {
9866                         for i in 0..2 {
9867                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 2_300_000);
9868                                 if let Err(_) = nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9869                         }
9870                 } else {
9871                         for _ in 0..2 {
9872                                 route_payment(&nodes[0], &[&nodes[1]], 2_300_000);
9873                         }
9874                 }
9875         } else {
9876                 if dust_outbound_balance {
9877                         for i in 0..25 {
9878                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 200_000); // + 177_000 msat of HTLC-success tx at 253 sats/kWU
9879                                 if let Err(_) = nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9880                         }
9881                 } else {
9882                         for _ in 0..25 {
9883                                 route_payment(&nodes[0], &[&nodes[1]], 200_000); // + 167_000 msat of HTLC-timeout tx at 253 sats/kWU
9884                         }
9885                 }
9886         }
9887
9888         if at_forward {
9889                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], if on_holder_tx { 2_300_000 } else { 200_000 });
9890                 let mut config = UserConfig::default();
9891                 if on_holder_tx {
9892                         unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", 6_900_000, config.channel_options.max_dust_htlc_exposure_msat)));
9893                 } else {
9894                         unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", 5_200_000, config.channel_options.max_dust_htlc_exposure_msat)));
9895                 }
9896         } else {
9897                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1 ], if on_holder_tx { 2_300_000 } else { 200_000 });
9898                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9899                 check_added_monitors!(nodes[0], 1);
9900                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9901                 assert_eq!(events.len(), 1);
9902                 let payment_event = SendEvent::from_event(events.remove(0));
9903                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9904                 if on_holder_tx {
9905                         nodes[1].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", 6_900_000, config.channel_options.max_dust_htlc_exposure_msat), 1);
9906                 } else {
9907                         nodes[1].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", 5_200_000, config.channel_options.max_dust_htlc_exposure_msat), 1);
9908                 }
9909         }
9910
9911         let _ = nodes[1].node.get_and_clear_pending_msg_events();
9912         let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9913         added_monitors.clear();
9914 }
9915
9916 #[test]
9917 fn test_max_dust_htlc_exposure() {
9918         do_test_max_dust_htlc_exposure(true, true, true);
9919         do_test_max_dust_htlc_exposure(false, true, true);
9920         do_test_max_dust_htlc_exposure(false, false, true);
9921         do_test_max_dust_htlc_exposure(false, false, false);
9922         do_test_max_dust_htlc_exposure(true, true, false);
9923         do_test_max_dust_htlc_exposure(true, false, false);
9924         do_test_max_dust_htlc_exposure(true, false, true);
9925         do_test_max_dust_htlc_exposure(false, true, false);
9926 }