Add some basic test coverage of monitor payment data reloading
[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, ChannelMonitorUpdateErr};
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::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, PaymentId, 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::network_graph::{NetworkUpdate, RoutingFees};
27 use routing::router::{Route, RouteHop, RouteHint, RouteHintHop, get_route, get_keysend_route};
28 use routing::scorer::Scorer;
29 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
30 use ln::msgs;
31 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
32 use util::enforcing_trait_impls::EnforcingSigner;
33 use util::{byte_utils, test_utils};
34 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
35 use util::errors::APIError;
36 use util::ser::{Writeable, ReadableArgs};
37 use util::config::UserConfig;
38
39 use bitcoin::hash_types::BlockHash;
40 use bitcoin::blockdata::block::{Block, BlockHeader};
41 use bitcoin::blockdata::script::Builder;
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45
46 use bitcoin::hashes::sha256::Hash as Sha256;
47 use bitcoin::hashes::Hash;
48
49 use bitcoin::secp256k1::Secp256k1;
50 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
51
52 use regex;
53
54 use io;
55 use prelude::*;
56 use alloc::collections::BTreeSet;
57 use core::default::Default;
58 use sync::{Arc, Mutex};
59
60 use ln::functional_test_utils::*;
61 use ln::chan_utils::CommitmentTransaction;
62
63 #[test]
64 fn test_insane_channel_opens() {
65         // Stand up a network of 2 nodes
66         let chanmon_cfgs = create_chanmon_cfgs(2);
67         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
68         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
69         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
70
71         // Instantiate channel parameters where we push the maximum msats given our
72         // funding satoshis
73         let channel_value_sat = 31337; // same as funding satoshis
74         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
75         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
76
77         // Have node0 initiate a channel to node1 with aforementioned parameters
78         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
79
80         // Extract the channel open message from node0 to node1
81         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
82
83         // Test helper that asserts we get the correct error string given a mutator
84         // that supposedly makes the channel open message insane
85         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
86                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
87                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
88                 assert_eq!(msg_events.len(), 1);
89                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
90                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
91                         match action {
92                                 &ErrorAction::SendErrorMessage { .. } => {
93                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
94                                 },
95                                 _ => panic!("unexpected event!"),
96                         }
97                 } else { assert!(false); }
98         };
99
100         use ln::channel::MAX_FUNDING_SATOSHIS;
101         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
102
103         // Test all mutations that would make the channel open message insane
104         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 });
105
106         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
107
108         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 });
109
110         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
111
112         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 });
113
114         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 });
115
116         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 });
117
118         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
119
120         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
121 }
122
123 #[test]
124 fn test_async_inbound_update_fee() {
125         let chanmon_cfgs = create_chanmon_cfgs(2);
126         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
127         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
128         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
129         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
130
131         // balancing
132         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
133
134         // A                                        B
135         // update_fee                            ->
136         // send (1) commitment_signed            -.
137         //                                       <- update_add_htlc/commitment_signed
138         // send (2) RAA (awaiting remote revoke) -.
139         // (1) commitment_signed is delivered    ->
140         //                                       .- send (3) RAA (awaiting remote revoke)
141         // (2) RAA is delivered                  ->
142         //                                       .- send (4) commitment_signed
143         //                                       <- (3) RAA is delivered
144         // send (5) commitment_signed            -.
145         //                                       <- (4) commitment_signed is delivered
146         // send (6) RAA                          -.
147         // (5) commitment_signed is delivered    ->
148         //                                       <- RAA
149         // (6) RAA is delivered                  ->
150
151         // First nodes[0] generates an update_fee
152         {
153                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
154                 *feerate_lock += 20;
155         }
156         nodes[0].node.timer_tick_occurred();
157         check_added_monitors!(nodes[0], 1);
158
159         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
160         assert_eq!(events_0.len(), 1);
161         let (update_msg, commitment_signed) = match events_0[0] { // (1)
162                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
163                         (update_fee.as_ref(), commitment_signed)
164                 },
165                 _ => panic!("Unexpected event"),
166         };
167
168         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
169
170         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
171         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
172         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
173         check_added_monitors!(nodes[1], 1);
174
175         let payment_event = {
176                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
177                 assert_eq!(events_1.len(), 1);
178                 SendEvent::from_event(events_1.remove(0))
179         };
180         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
181         assert_eq!(payment_event.msgs.len(), 1);
182
183         // ...now when the messages get delivered everyone should be happy
184         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
185         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
186         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
187         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
188         check_added_monitors!(nodes[0], 1);
189
190         // deliver(1), generate (3):
191         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
192         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
193         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
194         check_added_monitors!(nodes[1], 1);
195
196         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
197         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
198         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
199         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
200         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
201         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
202         assert!(bs_update.update_fee.is_none()); // (4)
203         check_added_monitors!(nodes[1], 1);
204
205         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
206         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
207         assert!(as_update.update_add_htlcs.is_empty()); // (5)
208         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
209         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
210         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
211         assert!(as_update.update_fee.is_none()); // (5)
212         check_added_monitors!(nodes[0], 1);
213
214         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
215         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
216         // only (6) so get_event_msg's assert(len == 1) passes
217         check_added_monitors!(nodes[0], 1);
218
219         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
220         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
221         check_added_monitors!(nodes[1], 1);
222
223         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
224         check_added_monitors!(nodes[0], 1);
225
226         let events_2 = nodes[0].node.get_and_clear_pending_events();
227         assert_eq!(events_2.len(), 1);
228         match events_2[0] {
229                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
230                 _ => panic!("Unexpected event"),
231         }
232
233         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
234         check_added_monitors!(nodes[1], 1);
235 }
236
237 #[test]
238 fn test_update_fee_unordered_raa() {
239         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
240         // crash in an earlier version of the update_fee patch)
241         let chanmon_cfgs = create_chanmon_cfgs(2);
242         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
243         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
244         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
245         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
246
247         // balancing
248         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
249
250         // First nodes[0] generates an update_fee
251         {
252                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
253                 *feerate_lock += 20;
254         }
255         nodes[0].node.timer_tick_occurred();
256         check_added_monitors!(nodes[0], 1);
257
258         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
259         assert_eq!(events_0.len(), 1);
260         let update_msg = match events_0[0] { // (1)
261                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
262                         update_fee.as_ref()
263                 },
264                 _ => panic!("Unexpected event"),
265         };
266
267         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
268
269         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
270         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
271         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
272         check_added_monitors!(nodes[1], 1);
273
274         let payment_event = {
275                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
276                 assert_eq!(events_1.len(), 1);
277                 SendEvent::from_event(events_1.remove(0))
278         };
279         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
280         assert_eq!(payment_event.msgs.len(), 1);
281
282         // ...now when the messages get delivered everyone should be happy
283         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
284         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
285         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
286         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
287         check_added_monitors!(nodes[0], 1);
288
289         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
290         check_added_monitors!(nodes[1], 1);
291
292         // We can't continue, sadly, because our (1) now has a bogus signature
293 }
294
295 #[test]
296 fn test_multi_flight_update_fee() {
297         let chanmon_cfgs = create_chanmon_cfgs(2);
298         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
299         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
300         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
301         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
302
303         // A                                        B
304         // update_fee/commitment_signed          ->
305         //                                       .- send (1) RAA and (2) commitment_signed
306         // update_fee (never committed)          ->
307         // (3) update_fee                        ->
308         // We have to manually generate the above update_fee, it is allowed by the protocol but we
309         // don't track which updates correspond to which revoke_and_ack responses so we're in
310         // AwaitingRAA mode and will not generate the update_fee yet.
311         //                                       <- (1) RAA delivered
312         // (3) is generated and send (4) CS      -.
313         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
314         // know the per_commitment_point to use for it.
315         //                                       <- (2) commitment_signed delivered
316         // revoke_and_ack                        ->
317         //                                          B should send no response here
318         // (4) commitment_signed delivered       ->
319         //                                       <- RAA/commitment_signed delivered
320         // revoke_and_ack                        ->
321
322         // First nodes[0] generates an update_fee
323         let initial_feerate;
324         {
325                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
326                 initial_feerate = *feerate_lock;
327                 *feerate_lock = initial_feerate + 20;
328         }
329         nodes[0].node.timer_tick_occurred();
330         check_added_monitors!(nodes[0], 1);
331
332         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
333         assert_eq!(events_0.len(), 1);
334         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
335                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
336                         (update_fee.as_ref().unwrap(), commitment_signed)
337                 },
338                 _ => panic!("Unexpected event"),
339         };
340
341         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
342         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
343         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
344         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
345         check_added_monitors!(nodes[1], 1);
346
347         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
348         // transaction:
349         {
350                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
351                 *feerate_lock = initial_feerate + 40;
352         }
353         nodes[0].node.timer_tick_occurred();
354         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
355         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
356
357         // Create the (3) update_fee message that nodes[0] will generate before it does...
358         let mut update_msg_2 = msgs::UpdateFee {
359                 channel_id: update_msg_1.channel_id.clone(),
360                 feerate_per_kw: (initial_feerate + 30) as u32,
361         };
362
363         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
364
365         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
366         // Deliver (3)
367         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
368
369         // Deliver (1), generating (3) and (4)
370         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
371         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
372         check_added_monitors!(nodes[0], 1);
373         assert!(as_second_update.update_add_htlcs.is_empty());
374         assert!(as_second_update.update_fulfill_htlcs.is_empty());
375         assert!(as_second_update.update_fail_htlcs.is_empty());
376         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
377         // Check that the update_fee newly generated matches what we delivered:
378         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
379         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
380
381         // Deliver (2) commitment_signed
382         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
383         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
384         check_added_monitors!(nodes[0], 1);
385         // No commitment_signed so get_event_msg's assert(len == 1) passes
386
387         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
388         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
389         check_added_monitors!(nodes[1], 1);
390
391         // Delever (4)
392         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
393         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
394         check_added_monitors!(nodes[1], 1);
395
396         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
397         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
398         check_added_monitors!(nodes[0], 1);
399
400         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
401         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
402         // No commitment_signed so get_event_msg's assert(len == 1) passes
403         check_added_monitors!(nodes[0], 1);
404
405         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
406         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
407         check_added_monitors!(nodes[1], 1);
408 }
409
410 fn do_test_1_conf_open(connect_style: ConnectStyle) {
411         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
412         // tests that we properly send one in that case.
413         let mut alice_config = UserConfig::default();
414         alice_config.own_channel_config.minimum_depth = 1;
415         alice_config.channel_options.announced_channel = true;
416         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
417         let mut bob_config = UserConfig::default();
418         bob_config.own_channel_config.minimum_depth = 1;
419         bob_config.channel_options.announced_channel = true;
420         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
421         let chanmon_cfgs = create_chanmon_cfgs(2);
422         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
423         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
424         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
425         *nodes[0].connect_style.borrow_mut() = connect_style;
426
427         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
428         mine_transaction(&nodes[1], &tx);
429         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()));
430
431         mine_transaction(&nodes[0], &tx);
432         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
433         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
434
435         for node in nodes {
436                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
437                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
438                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
439         }
440 }
441 #[test]
442 fn test_1_conf_open() {
443         do_test_1_conf_open(ConnectStyle::BestBlockFirst);
444         do_test_1_conf_open(ConnectStyle::TransactionsFirst);
445         do_test_1_conf_open(ConnectStyle::FullBlockViaListen);
446 }
447
448 fn do_test_sanity_on_in_flight_opens(steps: u8) {
449         // Previously, we had issues deserializing channels when we hadn't connected the first block
450         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
451         // serialization round-trips and simply do steps towards opening a channel and then drop the
452         // Node objects.
453
454         let chanmon_cfgs = create_chanmon_cfgs(2);
455         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
456         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
457         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
458
459         if steps & 0b1000_0000 != 0{
460                 let block = Block {
461                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
462                         txdata: vec![],
463                 };
464                 connect_block(&nodes[0], &block);
465                 connect_block(&nodes[1], &block);
466         }
467
468         if steps & 0x0f == 0 { return; }
469         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
470         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
471
472         if steps & 0x0f == 1 { return; }
473         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
474         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
475
476         if steps & 0x0f == 2 { return; }
477         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
478
479         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
480
481         if steps & 0x0f == 3 { return; }
482         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
483         check_added_monitors!(nodes[0], 0);
484         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
485
486         if steps & 0x0f == 4 { return; }
487         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
488         {
489                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
490                 assert_eq!(added_monitors.len(), 1);
491                 assert_eq!(added_monitors[0].0, funding_output);
492                 added_monitors.clear();
493         }
494         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
495
496         if steps & 0x0f == 5 { return; }
497         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
498         {
499                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
500                 assert_eq!(added_monitors.len(), 1);
501                 assert_eq!(added_monitors[0].0, funding_output);
502                 added_monitors.clear();
503         }
504
505         let events_4 = nodes[0].node.get_and_clear_pending_events();
506         assert_eq!(events_4.len(), 0);
507
508         if steps & 0x0f == 6 { return; }
509         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
510
511         if steps & 0x0f == 7 { return; }
512         confirm_transaction_at(&nodes[0], &tx, 2);
513         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
514         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
515 }
516
517 #[test]
518 fn test_sanity_on_in_flight_opens() {
519         do_test_sanity_on_in_flight_opens(0);
520         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
521         do_test_sanity_on_in_flight_opens(1);
522         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
523         do_test_sanity_on_in_flight_opens(2);
524         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
525         do_test_sanity_on_in_flight_opens(3);
526         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
527         do_test_sanity_on_in_flight_opens(4);
528         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
529         do_test_sanity_on_in_flight_opens(5);
530         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
531         do_test_sanity_on_in_flight_opens(6);
532         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
533         do_test_sanity_on_in_flight_opens(7);
534         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
535         do_test_sanity_on_in_flight_opens(8);
536         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
537 }
538
539 #[test]
540 fn test_update_fee_vanilla() {
541         let chanmon_cfgs = create_chanmon_cfgs(2);
542         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
543         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
544         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
545         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
546
547         {
548                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
549                 *feerate_lock += 25;
550         }
551         nodes[0].node.timer_tick_occurred();
552         check_added_monitors!(nodes[0], 1);
553
554         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
555         assert_eq!(events_0.len(), 1);
556         let (update_msg, commitment_signed) = match events_0[0] {
557                         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 } } => {
558                         (update_fee.as_ref(), commitment_signed)
559                 },
560                 _ => panic!("Unexpected event"),
561         };
562         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
563
564         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
565         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
566         check_added_monitors!(nodes[1], 1);
567
568         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
569         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
570         check_added_monitors!(nodes[0], 1);
571
572         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
573         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
574         // No commitment_signed so get_event_msg's assert(len == 1) passes
575         check_added_monitors!(nodes[0], 1);
576
577         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
578         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
579         check_added_monitors!(nodes[1], 1);
580 }
581
582 #[test]
583 fn test_update_fee_that_funder_cannot_afford() {
584         let chanmon_cfgs = create_chanmon_cfgs(2);
585         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
586         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
587         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
588         let channel_value = 1888;
589         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
590         let channel_id = chan.2;
591
592         let feerate = 260;
593         {
594                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
595                 *feerate_lock = feerate;
596         }
597         nodes[0].node.timer_tick_occurred();
598         check_added_monitors!(nodes[0], 1);
599         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
600
601         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
602
603         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
604
605         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
606         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
607         {
608                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
609
610                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
611                 let num_htlcs = commitment_tx.output.len() - 2;
612                 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
613                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
614                 actual_fee = channel_value - actual_fee;
615                 assert_eq!(total_fee, actual_fee);
616         }
617
618         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
619         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
620         {
621                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
622                 *feerate_lock = feerate + 2;
623         }
624         nodes[0].node.timer_tick_occurred();
625         check_added_monitors!(nodes[0], 1);
626
627         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
628
629         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
630
631         //While producing the commitment_signed response after handling a received update_fee request the
632         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
633         //Should produce and error.
634         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
635         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
636         check_added_monitors!(nodes[1], 1);
637         check_closed_broadcast!(nodes[1], true);
638         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
639 }
640
641 #[test]
642 fn test_update_fee_with_fundee_update_add_htlc() {
643         let chanmon_cfgs = create_chanmon_cfgs(2);
644         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
645         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
646         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
647         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
648
649         // balancing
650         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
651
652         {
653                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
654                 *feerate_lock += 20;
655         }
656         nodes[0].node.timer_tick_occurred();
657         check_added_monitors!(nodes[0], 1);
658
659         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
660         assert_eq!(events_0.len(), 1);
661         let (update_msg, commitment_signed) = match events_0[0] {
662                         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 } } => {
663                         (update_fee.as_ref(), commitment_signed)
664                 },
665                 _ => panic!("Unexpected event"),
666         };
667         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
668         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
669         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
670         check_added_monitors!(nodes[1], 1);
671
672         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
673
674         // nothing happens since node[1] is in AwaitingRemoteRevoke
675         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
676         {
677                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
678                 assert_eq!(added_monitors.len(), 0);
679                 added_monitors.clear();
680         }
681         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
682         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
683         // node[1] has nothing to do
684
685         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
686         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
687         check_added_monitors!(nodes[0], 1);
688
689         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
690         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
691         // No commitment_signed so get_event_msg's assert(len == 1) passes
692         check_added_monitors!(nodes[0], 1);
693         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
694         check_added_monitors!(nodes[1], 1);
695         // AwaitingRemoteRevoke ends here
696
697         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
698         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
699         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
700         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
701         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
702         assert_eq!(commitment_update.update_fee.is_none(), true);
703
704         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
705         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
706         check_added_monitors!(nodes[0], 1);
707         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
708
709         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
710         check_added_monitors!(nodes[1], 1);
711         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
712
713         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
714         check_added_monitors!(nodes[1], 1);
715         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
716         // No commitment_signed so get_event_msg's assert(len == 1) passes
717
718         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
719         check_added_monitors!(nodes[0], 1);
720         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
721
722         expect_pending_htlcs_forwardable!(nodes[0]);
723
724         let events = nodes[0].node.get_and_clear_pending_events();
725         assert_eq!(events.len(), 1);
726         match events[0] {
727                 Event::PaymentReceived { .. } => { },
728                 _ => panic!("Unexpected event"),
729         };
730
731         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
732
733         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
734         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
735         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
736         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
737         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
738 }
739
740 #[test]
741 fn test_update_fee() {
742         let chanmon_cfgs = create_chanmon_cfgs(2);
743         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
744         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
745         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
746         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
747         let channel_id = chan.2;
748
749         // A                                        B
750         // (1) update_fee/commitment_signed      ->
751         //                                       <- (2) revoke_and_ack
752         //                                       .- send (3) commitment_signed
753         // (4) update_fee/commitment_signed      ->
754         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
755         //                                       <- (3) commitment_signed delivered
756         // send (6) revoke_and_ack               -.
757         //                                       <- (5) deliver revoke_and_ack
758         // (6) deliver revoke_and_ack            ->
759         //                                       .- send (7) commitment_signed in response to (4)
760         //                                       <- (7) deliver commitment_signed
761         // revoke_and_ack                        ->
762
763         // Create and deliver (1)...
764         let feerate;
765         {
766                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
767                 feerate = *feerate_lock;
768                 *feerate_lock = feerate + 20;
769         }
770         nodes[0].node.timer_tick_occurred();
771         check_added_monitors!(nodes[0], 1);
772
773         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
774         assert_eq!(events_0.len(), 1);
775         let (update_msg, commitment_signed) = match events_0[0] {
776                         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 } } => {
777                         (update_fee.as_ref(), commitment_signed)
778                 },
779                 _ => panic!("Unexpected event"),
780         };
781         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
782
783         // Generate (2) and (3):
784         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
785         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
786         check_added_monitors!(nodes[1], 1);
787
788         // Deliver (2):
789         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
790         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
791         check_added_monitors!(nodes[0], 1);
792
793         // Create and deliver (4)...
794         {
795                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
796                 *feerate_lock = feerate + 30;
797         }
798         nodes[0].node.timer_tick_occurred();
799         check_added_monitors!(nodes[0], 1);
800         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
801         assert_eq!(events_0.len(), 1);
802         let (update_msg, commitment_signed) = match events_0[0] {
803                         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 } } => {
804                         (update_fee.as_ref(), commitment_signed)
805                 },
806                 _ => panic!("Unexpected event"),
807         };
808
809         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
810         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
811         check_added_monitors!(nodes[1], 1);
812         // ... creating (5)
813         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
814         // No commitment_signed so get_event_msg's assert(len == 1) passes
815
816         // Handle (3), creating (6):
817         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
818         check_added_monitors!(nodes[0], 1);
819         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
820         // No commitment_signed so get_event_msg's assert(len == 1) passes
821
822         // Deliver (5):
823         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
824         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
825         check_added_monitors!(nodes[0], 1);
826
827         // Deliver (6), creating (7):
828         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
829         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
830         assert!(commitment_update.update_add_htlcs.is_empty());
831         assert!(commitment_update.update_fulfill_htlcs.is_empty());
832         assert!(commitment_update.update_fail_htlcs.is_empty());
833         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
834         assert!(commitment_update.update_fee.is_none());
835         check_added_monitors!(nodes[1], 1);
836
837         // Deliver (7)
838         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
839         check_added_monitors!(nodes[0], 1);
840         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
841         // No commitment_signed so get_event_msg's assert(len == 1) passes
842
843         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
844         check_added_monitors!(nodes[1], 1);
845         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
846
847         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
848         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
849         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
850         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
851         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
852 }
853
854 #[test]
855 fn fake_network_test() {
856         // Simple test which builds a network of ChannelManagers, connects them to each other, and
857         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
858         let chanmon_cfgs = create_chanmon_cfgs(4);
859         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
860         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
861         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
862
863         // Create some initial channels
864         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
865         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
866         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
867
868         // Rebalance the network a bit by relaying one payment through all the channels...
869         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
870         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
871         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
872         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
873
874         // Send some more payments
875         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
876         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
877         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
878
879         // Test failure packets
880         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
881         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
882
883         // Add a new channel that skips 3
884         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
885
886         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
887         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
888         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
889         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
890         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
891         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
892         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
893
894         // Do some rebalance loop payments, simultaneously
895         let mut hops = Vec::with_capacity(3);
896         hops.push(RouteHop {
897                 pubkey: nodes[2].node.get_our_node_id(),
898                 node_features: NodeFeatures::empty(),
899                 short_channel_id: chan_2.0.contents.short_channel_id,
900                 channel_features: ChannelFeatures::empty(),
901                 fee_msat: 0,
902                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
903         });
904         hops.push(RouteHop {
905                 pubkey: nodes[3].node.get_our_node_id(),
906                 node_features: NodeFeatures::empty(),
907                 short_channel_id: chan_3.0.contents.short_channel_id,
908                 channel_features: ChannelFeatures::empty(),
909                 fee_msat: 0,
910                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
911         });
912         hops.push(RouteHop {
913                 pubkey: nodes[1].node.get_our_node_id(),
914                 node_features: NodeFeatures::known(),
915                 short_channel_id: chan_4.0.contents.short_channel_id,
916                 channel_features: ChannelFeatures::known(),
917                 fee_msat: 1000000,
918                 cltv_expiry_delta: TEST_FINAL_CLTV,
919         });
920         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;
921         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;
922         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
923
924         let mut hops = Vec::with_capacity(3);
925         hops.push(RouteHop {
926                 pubkey: nodes[3].node.get_our_node_id(),
927                 node_features: NodeFeatures::empty(),
928                 short_channel_id: chan_4.0.contents.short_channel_id,
929                 channel_features: ChannelFeatures::empty(),
930                 fee_msat: 0,
931                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
932         });
933         hops.push(RouteHop {
934                 pubkey: nodes[2].node.get_our_node_id(),
935                 node_features: NodeFeatures::empty(),
936                 short_channel_id: chan_3.0.contents.short_channel_id,
937                 channel_features: ChannelFeatures::empty(),
938                 fee_msat: 0,
939                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
940         });
941         hops.push(RouteHop {
942                 pubkey: nodes[1].node.get_our_node_id(),
943                 node_features: NodeFeatures::known(),
944                 short_channel_id: chan_2.0.contents.short_channel_id,
945                 channel_features: ChannelFeatures::known(),
946                 fee_msat: 1000000,
947                 cltv_expiry_delta: TEST_FINAL_CLTV,
948         });
949         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;
950         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;
951         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
952
953         // Claim the rebalances...
954         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
955         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
956
957         // Add a duplicate new channel from 2 to 4
958         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
959
960         // Send some payments across both channels
961         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
962         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
963         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
964
965
966         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
967         let events = nodes[0].node.get_and_clear_pending_msg_events();
968         assert_eq!(events.len(), 0);
969         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);
970
971         //TODO: Test that routes work again here as we've been notified that the channel is full
972
973         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
974         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
975         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
976
977         // Close down the channels...
978         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
979         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
980         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
981         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
982         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
983         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
984         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
985         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
986         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
987         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
988         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
989         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
990         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
991         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
992         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
993 }
994
995 #[test]
996 fn holding_cell_htlc_counting() {
997         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
998         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
999         // commitment dance rounds.
1000         let chanmon_cfgs = create_chanmon_cfgs(3);
1001         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1002         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1003         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1004         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1005         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1006
1007         let mut payments = Vec::new();
1008         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1009                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1010                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1011                 payments.push((payment_preimage, payment_hash));
1012         }
1013         check_added_monitors!(nodes[1], 1);
1014
1015         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1016         assert_eq!(events.len(), 1);
1017         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1018         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1019
1020         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1021         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1022         // another HTLC.
1023         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1024         {
1025                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1026                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1027                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1028                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1029         }
1030
1031         // This should also be true if we try to forward a payment.
1032         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1033         {
1034                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1035                 check_added_monitors!(nodes[0], 1);
1036         }
1037
1038         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1039         assert_eq!(events.len(), 1);
1040         let payment_event = SendEvent::from_event(events.pop().unwrap());
1041         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1042
1043         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1044         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1045         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1046         // fails), the second will process the resulting failure and fail the HTLC backward.
1047         expect_pending_htlcs_forwardable!(nodes[1]);
1048         expect_pending_htlcs_forwardable!(nodes[1]);
1049         check_added_monitors!(nodes[1], 1);
1050
1051         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1052         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1053         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1054
1055         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1056
1057         // Now forward all the pending HTLCs and claim them back
1058         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1059         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1060         check_added_monitors!(nodes[2], 1);
1061
1062         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1063         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1064         check_added_monitors!(nodes[1], 1);
1065         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1066
1067         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1068         check_added_monitors!(nodes[1], 1);
1069         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1070
1071         for ref update in as_updates.update_add_htlcs.iter() {
1072                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1073         }
1074         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1075         check_added_monitors!(nodes[2], 1);
1076         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1077         check_added_monitors!(nodes[2], 1);
1078         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1079
1080         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1081         check_added_monitors!(nodes[1], 1);
1082         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1083         check_added_monitors!(nodes[1], 1);
1084         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1085
1086         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1087         check_added_monitors!(nodes[2], 1);
1088
1089         expect_pending_htlcs_forwardable!(nodes[2]);
1090
1091         let events = nodes[2].node.get_and_clear_pending_events();
1092         assert_eq!(events.len(), payments.len());
1093         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1094                 match event {
1095                         &Event::PaymentReceived { ref payment_hash, .. } => {
1096                                 assert_eq!(*payment_hash, *hash);
1097                         },
1098                         _ => panic!("Unexpected event"),
1099                 };
1100         }
1101
1102         for (preimage, _) in payments.drain(..) {
1103                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1104         }
1105
1106         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1107 }
1108
1109 #[test]
1110 fn duplicate_htlc_test() {
1111         // Test that we accept duplicate payment_hash HTLCs across the network and that
1112         // claiming/failing them are all separate and don't affect each other
1113         let chanmon_cfgs = create_chanmon_cfgs(6);
1114         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1115         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1116         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1117
1118         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1119         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1120         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1121         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1122         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1123         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1124
1125         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1126
1127         *nodes[0].network_payment_count.borrow_mut() -= 1;
1128         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1129
1130         *nodes[0].network_payment_count.borrow_mut() -= 1;
1131         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1132
1133         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1134         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1135         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1136 }
1137
1138 #[test]
1139 fn test_duplicate_htlc_different_direction_onchain() {
1140         // Test that ChannelMonitor doesn't generate 2 preimage txn
1141         // when we have 2 HTLCs with same preimage that go across a node
1142         // in opposite directions, even with the same payment secret.
1143         let chanmon_cfgs = create_chanmon_cfgs(2);
1144         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1145         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1146         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1147
1148         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1149
1150         // balancing
1151         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1152
1153         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1154
1155         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1156         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, 0).unwrap();
1157         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1158
1159         // Provide preimage to node 0 by claiming payment
1160         nodes[0].node.claim_funds(payment_preimage);
1161         check_added_monitors!(nodes[0], 1);
1162
1163         // Broadcast node 1 commitment txn
1164         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1165
1166         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1167         let mut has_both_htlcs = 0; // check htlcs match ones committed
1168         for outp in remote_txn[0].output.iter() {
1169                 if outp.value == 800_000 / 1000 {
1170                         has_both_htlcs += 1;
1171                 } else if outp.value == 900_000 / 1000 {
1172                         has_both_htlcs += 1;
1173                 }
1174         }
1175         assert_eq!(has_both_htlcs, 2);
1176
1177         mine_transaction(&nodes[0], &remote_txn[0]);
1178         check_added_monitors!(nodes[0], 1);
1179         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1180         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1181
1182         // Check we only broadcast 1 timeout tx
1183         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1184         assert_eq!(claim_txn.len(), 8);
1185         assert_eq!(claim_txn[1], claim_txn[4]);
1186         assert_eq!(claim_txn[2], claim_txn[5]);
1187         check_spends!(claim_txn[1], chan_1.3);
1188         check_spends!(claim_txn[2], claim_txn[1]);
1189         check_spends!(claim_txn[7], claim_txn[1]);
1190
1191         assert_eq!(claim_txn[0].input.len(), 1);
1192         assert_eq!(claim_txn[3].input.len(), 1);
1193         assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1194
1195         assert_eq!(claim_txn[0].input.len(), 1);
1196         assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1197         check_spends!(claim_txn[0], remote_txn[0]);
1198         assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1199         assert_eq!(claim_txn[6].input.len(), 1);
1200         assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1201         check_spends!(claim_txn[6], remote_txn[0]);
1202         assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1203
1204         let events = nodes[0].node.get_and_clear_pending_msg_events();
1205         assert_eq!(events.len(), 3);
1206         for e in events {
1207                 match e {
1208                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1209                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1210                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1211                                 assert_eq!(msg.data, "Commitment or closing transaction was confirmed on chain.");
1212                         },
1213                         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, .. } } => {
1214                                 assert!(update_add_htlcs.is_empty());
1215                                 assert!(update_fail_htlcs.is_empty());
1216                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1217                                 assert!(update_fail_malformed_htlcs.is_empty());
1218                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1219                         },
1220                         _ => panic!("Unexpected event"),
1221                 }
1222         }
1223 }
1224
1225 #[test]
1226 fn test_basic_channel_reserve() {
1227         let chanmon_cfgs = create_chanmon_cfgs(2);
1228         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1229         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1230         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1231         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1232
1233         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1234         let channel_reserve = chan_stat.channel_reserve_msat;
1235
1236         // The 2* and +1 are for the fee spike reserve.
1237         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1238         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1239         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1240         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1241         match err {
1242                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1243                         match &fails[0] {
1244                                 &APIError::ChannelUnavailable{ref err} =>
1245                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1246                                 _ => panic!("Unexpected error variant"),
1247                         }
1248                 },
1249                 _ => panic!("Unexpected error variant"),
1250         }
1251         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1252         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);
1253
1254         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1255 }
1256
1257 #[test]
1258 fn test_fee_spike_violation_fails_htlc() {
1259         let chanmon_cfgs = create_chanmon_cfgs(2);
1260         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1261         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1262         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1263         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1264
1265         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1266         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1267         let secp_ctx = Secp256k1::new();
1268         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1269
1270         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1271
1272         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1273         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1274         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1275         let msg = msgs::UpdateAddHTLC {
1276                 channel_id: chan.2,
1277                 htlc_id: 0,
1278                 amount_msat: htlc_msat,
1279                 payment_hash: payment_hash,
1280                 cltv_expiry: htlc_cltv,
1281                 onion_routing_packet: onion_packet,
1282         };
1283
1284         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1285
1286         // Now manually create the commitment_signed message corresponding to the update_add
1287         // nodes[0] just sent. In the code for construction of this message, "local" refers
1288         // to the sender of the message, and "remote" refers to the receiver.
1289
1290         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1291
1292         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1293
1294         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1295         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1296         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1297                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1298                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1299                 let chan_signer = local_chan.get_signer();
1300                 // Make the signer believe we validated another commitment, so we can release the secret
1301                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1302
1303                 let pubkeys = chan_signer.pubkeys();
1304                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1305                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1306                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1307                  chan_signer.pubkeys().funding_pubkey)
1308         };
1309         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1310                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1311                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1312                 let chan_signer = remote_chan.get_signer();
1313                 let pubkeys = chan_signer.pubkeys();
1314                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1315                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1316                  chan_signer.pubkeys().funding_pubkey)
1317         };
1318
1319         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1320         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1321                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1322
1323         // Build the remote commitment transaction so we can sign it, and then later use the
1324         // signature for the commitment_signed message.
1325         let local_chan_balance = 1313;
1326
1327         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1328                 offered: false,
1329                 amount_msat: 3460001,
1330                 cltv_expiry: htlc_cltv,
1331                 payment_hash,
1332                 transaction_output_index: Some(1),
1333         };
1334
1335         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1336
1337         let res = {
1338                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1339                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1340                 let local_chan_signer = local_chan.get_signer();
1341                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1342                         commitment_number,
1343                         95000,
1344                         local_chan_balance,
1345                         false, local_funding, remote_funding,
1346                         commit_tx_keys.clone(),
1347                         feerate_per_kw,
1348                         &mut vec![(accepted_htlc_info, ())],
1349                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1350                 );
1351                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1352         };
1353
1354         let commit_signed_msg = msgs::CommitmentSigned {
1355                 channel_id: chan.2,
1356                 signature: res.0,
1357                 htlc_signatures: res.1
1358         };
1359
1360         // Send the commitment_signed message to the nodes[1].
1361         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1362         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1363
1364         // Send the RAA to nodes[1].
1365         let raa_msg = msgs::RevokeAndACK {
1366                 channel_id: chan.2,
1367                 per_commitment_secret: local_secret,
1368                 next_per_commitment_point: next_local_point
1369         };
1370         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1371
1372         let events = nodes[1].node.get_and_clear_pending_msg_events();
1373         assert_eq!(events.len(), 1);
1374         // Make sure the HTLC failed in the way we expect.
1375         match events[0] {
1376                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1377                         assert_eq!(update_fail_htlcs.len(), 1);
1378                         update_fail_htlcs[0].clone()
1379                 },
1380                 _ => panic!("Unexpected event"),
1381         };
1382         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1383                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1384
1385         check_added_monitors!(nodes[1], 2);
1386 }
1387
1388 #[test]
1389 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1390         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1391         // Set the fee rate for the channel very high, to the point where the fundee
1392         // sending any above-dust amount would result in a channel reserve violation.
1393         // In this test we check that we would be prevented from sending an HTLC in
1394         // this situation.
1395         let feerate_per_kw = 253;
1396         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1397         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1398         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1399         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1400         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1401
1402         let mut push_amt = 100_000_000;
1403         push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT + COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
1404         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1405
1406         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1407
1408         // Sending exactly enough to hit the reserve amount should be accepted
1409         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1410
1411         // However one more HTLC should be significantly over the reserve amount and fail.
1412         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1413         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1414                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1415         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1416         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);
1417 }
1418
1419 #[test]
1420 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1421         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1422         // Set the fee rate for the channel very high, to the point where the funder
1423         // receiving 1 update_add_htlc would result in them closing the channel due
1424         // to channel reserve violation. This close could also happen if the fee went
1425         // up a more realistic amount, but many HTLCs were outstanding at the time of
1426         // the update_add_htlc.
1427         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1428         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1429         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1430         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1431         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1432         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1433
1434         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1435         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1436         let secp_ctx = Secp256k1::new();
1437         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1438         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1439         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1440         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &Some(payment_secret), cur_height, &None).unwrap();
1441         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1442         let msg = msgs::UpdateAddHTLC {
1443                 channel_id: chan.2,
1444                 htlc_id: 1,
1445                 amount_msat: htlc_msat + 1,
1446                 payment_hash: payment_hash,
1447                 cltv_expiry: htlc_cltv,
1448                 onion_routing_packet: onion_packet,
1449         };
1450
1451         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1452         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1453         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);
1454         assert_eq!(nodes[0].node.list_channels().len(), 0);
1455         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1456         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1457         check_added_monitors!(nodes[0], 1);
1458         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string() });
1459 }
1460
1461 #[test]
1462 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1463         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1464         // calculating our commitment transaction fee (this was previously broken).
1465         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1466         let feerate_per_kw = 253;
1467         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1468         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1469
1470         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1471         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1472         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1473
1474         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1475         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1476         // transaction fee with 0 HTLCs (183 sats)).
1477         let mut push_amt = 100_000_000;
1478         push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT) / 1000 * 1000;
1479         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1480         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1481
1482         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1483                 + feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000 * 1000 - 1;
1484         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1485         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1486         // commitment transaction fee.
1487         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1488
1489         // One more than the dust amt should fail, however.
1490         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1491         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1492                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1493 }
1494
1495 #[test]
1496 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1497         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1498         // calculating our counterparty's commitment transaction fee (this was previously broken).
1499         let chanmon_cfgs = create_chanmon_cfgs(2);
1500         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1501         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1502         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1503         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1504
1505         let payment_amt = 46000; // Dust amount
1506         // In the previous code, these first four payments would succeed.
1507         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1508         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1509         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1510         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1511
1512         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1513         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1514         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1515         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1516         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1517         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1518
1519         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1520         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1521         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1522         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1523 }
1524
1525 #[test]
1526 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1527         let chanmon_cfgs = create_chanmon_cfgs(3);
1528         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1529         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1530         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1531         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1532         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1533
1534         let feemsat = 239;
1535         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1536         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1537         let feerate = get_feerate!(nodes[0], chan.2);
1538
1539         // Add a 2* and +1 for the fee spike reserve.
1540         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1541         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;
1542         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1543
1544         // Add a pending HTLC.
1545         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1546         let payment_event_1 = {
1547                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1548                 check_added_monitors!(nodes[0], 1);
1549
1550                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1551                 assert_eq!(events.len(), 1);
1552                 SendEvent::from_event(events.remove(0))
1553         };
1554         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1555
1556         // Attempt to trigger a channel reserve violation --> payment failure.
1557         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1558         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;
1559         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1560         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1561
1562         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1563         let secp_ctx = Secp256k1::new();
1564         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1565         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1566         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1567         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1568         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1569         let msg = msgs::UpdateAddHTLC {
1570                 channel_id: chan.2,
1571                 htlc_id: 1,
1572                 amount_msat: htlc_msat + 1,
1573                 payment_hash: our_payment_hash_1,
1574                 cltv_expiry: htlc_cltv,
1575                 onion_routing_packet: onion_packet,
1576         };
1577
1578         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1579         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1580         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1581         assert_eq!(nodes[1].node.list_channels().len(), 1);
1582         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1583         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1584         check_added_monitors!(nodes[1], 1);
1585         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1586 }
1587
1588 #[test]
1589 fn test_inbound_outbound_capacity_is_not_zero() {
1590         let chanmon_cfgs = create_chanmon_cfgs(2);
1591         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1592         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1593         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1594         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1595         let channels0 = node_chanmgrs[0].list_channels();
1596         let channels1 = node_chanmgrs[1].list_channels();
1597         assert_eq!(channels0.len(), 1);
1598         assert_eq!(channels1.len(), 1);
1599
1600         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1601         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1602         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1603
1604         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1605         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1606 }
1607
1608 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1609         (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1610 }
1611
1612 #[test]
1613 fn test_channel_reserve_holding_cell_htlcs() {
1614         let chanmon_cfgs = create_chanmon_cfgs(3);
1615         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1616         // When this test was written, the default base fee floated based on the HTLC count.
1617         // It is now fixed, so we simply set the fee to the expected value here.
1618         let mut config = test_default_channel_config();
1619         config.channel_options.forwarding_fee_base_msat = 239;
1620         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1621         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1622         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1623         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1624
1625         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1626         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1627
1628         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1629         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1630
1631         macro_rules! expect_forward {
1632                 ($node: expr) => {{
1633                         let mut events = $node.node.get_and_clear_pending_msg_events();
1634                         assert_eq!(events.len(), 1);
1635                         check_added_monitors!($node, 1);
1636                         let payment_event = SendEvent::from_event(events.remove(0));
1637                         payment_event
1638                 }}
1639         }
1640
1641         let feemsat = 239; // set above
1642         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1643         let feerate = get_feerate!(nodes[0], chan_1.2);
1644
1645         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1646
1647         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1648         {
1649                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1650                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1651                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1652                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1653                         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)));
1654                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1655                 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);
1656         }
1657
1658         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1659         // nodes[0]'s wealth
1660         loop {
1661                 let amt_msat = recv_value_0 + total_fee_msat;
1662                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1663                 // Also, ensure that each payment has enough to be over the dust limit to
1664                 // ensure it'll be included in each commit tx fee calculation.
1665                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1666                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1667                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1668                         break;
1669                 }
1670                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1671
1672                 let (stat01_, stat11_, stat12_, stat22_) = (
1673                         get_channel_value_stat!(nodes[0], chan_1.2),
1674                         get_channel_value_stat!(nodes[1], chan_1.2),
1675                         get_channel_value_stat!(nodes[1], chan_2.2),
1676                         get_channel_value_stat!(nodes[2], chan_2.2),
1677                 );
1678
1679                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1680                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1681                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1682                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1683                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1684         }
1685
1686         // adding pending output.
1687         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1688         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1689         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1690         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1691         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1692         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1693         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1694         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1695         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1696         // policy.
1697         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
1698         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1699         let amt_msat_1 = recv_value_1 + total_fee_msat;
1700
1701         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);
1702         let payment_event_1 = {
1703                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1704                 check_added_monitors!(nodes[0], 1);
1705
1706                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1707                 assert_eq!(events.len(), 1);
1708                 SendEvent::from_event(events.remove(0))
1709         };
1710         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1711
1712         // channel reserve test with htlc pending output > 0
1713         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1714         {
1715                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1716                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1717                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1718                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1719         }
1720
1721         // split the rest to test holding cell
1722         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1723         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1724         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1725         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1726         {
1727                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1728                 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);
1729         }
1730
1731         // now see if they go through on both sides
1732         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);
1733         // but this will stuck in the holding cell
1734         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1735         check_added_monitors!(nodes[0], 0);
1736         let events = nodes[0].node.get_and_clear_pending_events();
1737         assert_eq!(events.len(), 0);
1738
1739         // test with outbound holding cell amount > 0
1740         {
1741                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1742                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1743                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1744                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1745                 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);
1746         }
1747
1748         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);
1749         // this will also stuck in the holding cell
1750         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1751         check_added_monitors!(nodes[0], 0);
1752         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1753         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1754
1755         // flush the pending htlc
1756         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1757         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1758         check_added_monitors!(nodes[1], 1);
1759
1760         // the pending htlc should be promoted to committed
1761         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1762         check_added_monitors!(nodes[0], 1);
1763         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1764
1765         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1766         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1767         // No commitment_signed so get_event_msg's assert(len == 1) passes
1768         check_added_monitors!(nodes[0], 1);
1769
1770         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1771         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1772         check_added_monitors!(nodes[1], 1);
1773
1774         expect_pending_htlcs_forwardable!(nodes[1]);
1775
1776         let ref payment_event_11 = expect_forward!(nodes[1]);
1777         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1778         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1779
1780         expect_pending_htlcs_forwardable!(nodes[2]);
1781         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1782
1783         // flush the htlcs in the holding cell
1784         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1785         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1786         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1787         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1788         expect_pending_htlcs_forwardable!(nodes[1]);
1789
1790         let ref payment_event_3 = expect_forward!(nodes[1]);
1791         assert_eq!(payment_event_3.msgs.len(), 2);
1792         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1793         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1794
1795         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1796         expect_pending_htlcs_forwardable!(nodes[2]);
1797
1798         let events = nodes[2].node.get_and_clear_pending_events();
1799         assert_eq!(events.len(), 2);
1800         match events[0] {
1801                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1802                         assert_eq!(our_payment_hash_21, *payment_hash);
1803                         assert_eq!(recv_value_21, amt);
1804                         match &purpose {
1805                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1806                                         assert!(payment_preimage.is_none());
1807                                         assert_eq!(our_payment_secret_21, *payment_secret);
1808                                 },
1809                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1810                         }
1811                 },
1812                 _ => panic!("Unexpected event"),
1813         }
1814         match events[1] {
1815                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1816                         assert_eq!(our_payment_hash_22, *payment_hash);
1817                         assert_eq!(recv_value_22, amt);
1818                         match &purpose {
1819                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1820                                         assert!(payment_preimage.is_none());
1821                                         assert_eq!(our_payment_secret_22, *payment_secret);
1822                                 },
1823                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1824                         }
1825                 },
1826                 _ => panic!("Unexpected event"),
1827         }
1828
1829         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1830         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1831         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1832
1833         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
1834         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1835         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1836
1837         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
1838         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);
1839         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1840         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1841         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1842
1843         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1844         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
1845 }
1846
1847 #[test]
1848 fn channel_reserve_in_flight_removes() {
1849         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1850         // can send to its counterparty, but due to update ordering, the other side may not yet have
1851         // considered those HTLCs fully removed.
1852         // This tests that we don't count HTLCs which will not be included in the next remote
1853         // commitment transaction towards the reserve value (as it implies no commitment transaction
1854         // will be generated which violates the remote reserve value).
1855         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1856         // To test this we:
1857         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1858         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1859         //    you only consider the value of the first HTLC, it may not),
1860         //  * start routing a third HTLC from A to B,
1861         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1862         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1863         //  * deliver the first fulfill from B
1864         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1865         //    claim,
1866         //  * deliver A's response CS and RAA.
1867         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1868         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
1869         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1870         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1871         let chanmon_cfgs = create_chanmon_cfgs(2);
1872         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1873         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1874         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1875         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1876
1877         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1878         // Route the first two HTLCs.
1879         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1880         let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1881
1882         // Start routing the third HTLC (this is just used to get everyone in the right state).
1883         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
1884         let send_1 = {
1885                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
1886                 check_added_monitors!(nodes[0], 1);
1887                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1888                 assert_eq!(events.len(), 1);
1889                 SendEvent::from_event(events.remove(0))
1890         };
1891
1892         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1893         // initial fulfill/CS.
1894         assert!(nodes[1].node.claim_funds(payment_preimage_1));
1895         check_added_monitors!(nodes[1], 1);
1896         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1897
1898         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1899         // remove the second HTLC when we send the HTLC back from B to A.
1900         assert!(nodes[1].node.claim_funds(payment_preimage_2));
1901         check_added_monitors!(nodes[1], 1);
1902         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1903
1904         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1905         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1906         check_added_monitors!(nodes[0], 1);
1907         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1908         expect_payment_sent!(nodes[0], payment_preimage_1);
1909
1910         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1911         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1912         check_added_monitors!(nodes[1], 1);
1913         // B is already AwaitingRAA, so cant generate a CS here
1914         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1915
1916         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1917         check_added_monitors!(nodes[1], 1);
1918         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1919
1920         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1921         check_added_monitors!(nodes[0], 1);
1922         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1923
1924         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1925         check_added_monitors!(nodes[1], 1);
1926         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1927
1928         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1929         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1930         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1931         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1932         // on-chain as necessary).
1933         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1934         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1935         check_added_monitors!(nodes[0], 1);
1936         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1937         expect_payment_sent!(nodes[0], payment_preimage_2);
1938
1939         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1940         check_added_monitors!(nodes[1], 1);
1941         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1942
1943         expect_pending_htlcs_forwardable!(nodes[1]);
1944         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
1945
1946         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1947         // resolve the second HTLC from A's point of view.
1948         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1949         check_added_monitors!(nodes[0], 1);
1950         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1951
1952         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1953         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1954         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
1955         let send_2 = {
1956                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
1957                 check_added_monitors!(nodes[1], 1);
1958                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1959                 assert_eq!(events.len(), 1);
1960                 SendEvent::from_event(events.remove(0))
1961         };
1962
1963         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1964         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1965         check_added_monitors!(nodes[0], 1);
1966         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1967
1968         // Now just resolve all the outstanding messages/HTLCs for completeness...
1969
1970         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1971         check_added_monitors!(nodes[1], 1);
1972         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1973
1974         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1975         check_added_monitors!(nodes[1], 1);
1976
1977         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1978         check_added_monitors!(nodes[0], 1);
1979         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1980
1981         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1982         check_added_monitors!(nodes[1], 1);
1983         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1984
1985         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1986         check_added_monitors!(nodes[0], 1);
1987
1988         expect_pending_htlcs_forwardable!(nodes[0]);
1989         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
1990
1991         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
1992         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
1993 }
1994
1995 #[test]
1996 fn channel_monitor_network_test() {
1997         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1998         // tests that ChannelMonitor is able to recover from various states.
1999         let chanmon_cfgs = create_chanmon_cfgs(5);
2000         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2001         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2002         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2003
2004         // Create some initial channels
2005         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2006         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2007         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2008         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2009
2010         // Make sure all nodes are at the same starting height
2011         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2012         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2013         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2014         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2015         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2016
2017         // Rebalance the network a bit by relaying one payment through all the channels...
2018         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2019         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2020         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2021         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2022
2023         // Simple case with no pending HTLCs:
2024         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2025         check_added_monitors!(nodes[1], 1);
2026         check_closed_broadcast!(nodes[1], false);
2027         {
2028                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2029                 assert_eq!(node_txn.len(), 1);
2030                 mine_transaction(&nodes[0], &node_txn[0]);
2031                 check_added_monitors!(nodes[0], 1);
2032                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2033         }
2034         check_closed_broadcast!(nodes[0], true);
2035         assert_eq!(nodes[0].node.list_channels().len(), 0);
2036         assert_eq!(nodes[1].node.list_channels().len(), 1);
2037         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2038         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2039
2040         // One pending HTLC is discarded by the force-close:
2041         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2042
2043         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2044         // broadcasted until we reach the timelock time).
2045         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2046         check_closed_broadcast!(nodes[1], false);
2047         check_added_monitors!(nodes[1], 1);
2048         {
2049                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2050                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2051                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2052                 mine_transaction(&nodes[2], &node_txn[0]);
2053                 check_added_monitors!(nodes[2], 1);
2054                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2055         }
2056         check_closed_broadcast!(nodes[2], true);
2057         assert_eq!(nodes[1].node.list_channels().len(), 0);
2058         assert_eq!(nodes[2].node.list_channels().len(), 1);
2059         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2060         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2061
2062         macro_rules! claim_funds {
2063                 ($node: expr, $prev_node: expr, $preimage: expr) => {
2064                         {
2065                                 assert!($node.node.claim_funds($preimage));
2066                                 check_added_monitors!($node, 1);
2067
2068                                 let events = $node.node.get_and_clear_pending_msg_events();
2069                                 assert_eq!(events.len(), 1);
2070                                 match events[0] {
2071                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2072                                                 assert!(update_add_htlcs.is_empty());
2073                                                 assert!(update_fail_htlcs.is_empty());
2074                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2075                                         },
2076                                         _ => panic!("Unexpected event"),
2077                                 };
2078                         }
2079                 }
2080         }
2081
2082         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2083         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2084         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2085         check_added_monitors!(nodes[2], 1);
2086         check_closed_broadcast!(nodes[2], false);
2087         let node2_commitment_txid;
2088         {
2089                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2090                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2091                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2092                 node2_commitment_txid = node_txn[0].txid();
2093
2094                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2095                 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2096                 mine_transaction(&nodes[3], &node_txn[0]);
2097                 check_added_monitors!(nodes[3], 1);
2098                 check_preimage_claim(&nodes[3], &node_txn);
2099         }
2100         check_closed_broadcast!(nodes[3], true);
2101         assert_eq!(nodes[2].node.list_channels().len(), 0);
2102         assert_eq!(nodes[3].node.list_channels().len(), 1);
2103         check_closed_event!(nodes[2], 1, ClosureReason::DisconnectedPeer);
2104         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2105
2106         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2107         // confusing us in the following tests.
2108         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2109
2110         // One pending HTLC to time out:
2111         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2112         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2113         // buffer space).
2114
2115         let (close_chan_update_1, close_chan_update_2) = {
2116                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2117                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2118                 assert_eq!(events.len(), 2);
2119                 let close_chan_update_1 = match events[0] {
2120                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2121                                 msg.clone()
2122                         },
2123                         _ => panic!("Unexpected event"),
2124                 };
2125                 match events[1] {
2126                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2127                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2128                         },
2129                         _ => panic!("Unexpected event"),
2130                 }
2131                 check_added_monitors!(nodes[3], 1);
2132
2133                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2134                 {
2135                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2136                         node_txn.retain(|tx| {
2137                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2138                                         false
2139                                 } else { true }
2140                         });
2141                 }
2142
2143                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2144
2145                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2146                 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2147
2148                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2149                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2150                 assert_eq!(events.len(), 2);
2151                 let close_chan_update_2 = match events[0] {
2152                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2153                                 msg.clone()
2154                         },
2155                         _ => panic!("Unexpected event"),
2156                 };
2157                 match events[1] {
2158                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2159                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2160                         },
2161                         _ => panic!("Unexpected event"),
2162                 }
2163                 check_added_monitors!(nodes[4], 1);
2164                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2165
2166                 mine_transaction(&nodes[4], &node_txn[0]);
2167                 check_preimage_claim(&nodes[4], &node_txn);
2168                 (close_chan_update_1, close_chan_update_2)
2169         };
2170         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2171         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2172         assert_eq!(nodes[3].node.list_channels().len(), 0);
2173         assert_eq!(nodes[4].node.list_channels().len(), 0);
2174
2175         nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2176         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2177         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2178 }
2179
2180 #[test]
2181 fn test_justice_tx() {
2182         // Test justice txn built on revoked HTLC-Success tx, against both sides
2183         let mut alice_config = UserConfig::default();
2184         alice_config.channel_options.announced_channel = true;
2185         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2186         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2187         let mut bob_config = UserConfig::default();
2188         bob_config.channel_options.announced_channel = true;
2189         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2190         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2191         let user_cfgs = [Some(alice_config), Some(bob_config)];
2192         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2193         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2194         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2195         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2196         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2197         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2198         // Create some new channels:
2199         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2200
2201         // A pending HTLC which will be revoked:
2202         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2203         // Get the will-be-revoked local txn from nodes[0]
2204         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2205         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2206         assert_eq!(revoked_local_txn[0].input.len(), 1);
2207         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2208         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2209         assert_eq!(revoked_local_txn[1].input.len(), 1);
2210         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2211         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2212         // Revoke the old state
2213         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2214
2215         {
2216                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2217                 {
2218                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2219                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2220                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2221
2222                         check_spends!(node_txn[0], revoked_local_txn[0]);
2223                         node_txn.swap_remove(0);
2224                         node_txn.truncate(1);
2225                 }
2226                 check_added_monitors!(nodes[1], 1);
2227                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2228                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2229
2230                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2231                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2232                 // Verify broadcast of revoked HTLC-timeout
2233                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2234                 check_added_monitors!(nodes[0], 1);
2235                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2236                 // Broadcast revoked HTLC-timeout on node 1
2237                 mine_transaction(&nodes[1], &node_txn[1]);
2238                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2239         }
2240         get_announce_close_broadcast_events(&nodes, 0, 1);
2241
2242         assert_eq!(nodes[0].node.list_channels().len(), 0);
2243         assert_eq!(nodes[1].node.list_channels().len(), 0);
2244
2245         // We test justice_tx build by A on B's revoked HTLC-Success tx
2246         // Create some new channels:
2247         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2248         {
2249                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2250                 node_txn.clear();
2251         }
2252
2253         // A pending HTLC which will be revoked:
2254         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2255         // Get the will-be-revoked local txn from B
2256         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2257         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2258         assert_eq!(revoked_local_txn[0].input.len(), 1);
2259         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2260         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2261         // Revoke the old state
2262         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2263         {
2264                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2265                 {
2266                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2267                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2268                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2269
2270                         check_spends!(node_txn[0], revoked_local_txn[0]);
2271                         node_txn.swap_remove(0);
2272                 }
2273                 check_added_monitors!(nodes[0], 1);
2274                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2275
2276                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2277                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2278                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2279                 check_added_monitors!(nodes[1], 1);
2280                 mine_transaction(&nodes[0], &node_txn[1]);
2281                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2282                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2283         }
2284         get_announce_close_broadcast_events(&nodes, 0, 1);
2285         assert_eq!(nodes[0].node.list_channels().len(), 0);
2286         assert_eq!(nodes[1].node.list_channels().len(), 0);
2287 }
2288
2289 #[test]
2290 fn revoked_output_claim() {
2291         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2292         // transaction is broadcast by its counterparty
2293         let chanmon_cfgs = create_chanmon_cfgs(2);
2294         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2295         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2296         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2297         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2298         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2299         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2300         assert_eq!(revoked_local_txn.len(), 1);
2301         // Only output is the full channel value back to nodes[0]:
2302         assert_eq!(revoked_local_txn[0].output.len(), 1);
2303         // Send a payment through, updating everyone's latest commitment txn
2304         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2305
2306         // Inform nodes[1] that nodes[0] broadcast a stale tx
2307         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2308         check_added_monitors!(nodes[1], 1);
2309         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2310         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2311         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2312
2313         check_spends!(node_txn[0], revoked_local_txn[0]);
2314         check_spends!(node_txn[1], chan_1.3);
2315
2316         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2317         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2318         get_announce_close_broadcast_events(&nodes, 0, 1);
2319         check_added_monitors!(nodes[0], 1);
2320         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2321 }
2322
2323 #[test]
2324 fn claim_htlc_outputs_shared_tx() {
2325         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2326         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2327         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2328         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2329         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2330         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2331
2332         // Create some new channel:
2333         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2334
2335         // Rebalance the network to generate htlc in the two directions
2336         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2337         // 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
2338         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2339         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2340
2341         // Get the will-be-revoked local txn from node[0]
2342         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2343         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2344         assert_eq!(revoked_local_txn[0].input.len(), 1);
2345         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2346         assert_eq!(revoked_local_txn[1].input.len(), 1);
2347         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2348         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2349         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2350
2351         //Revoke the old state
2352         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2353
2354         {
2355                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2356                 check_added_monitors!(nodes[0], 1);
2357                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2358                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2359                 check_added_monitors!(nodes[1], 1);
2360                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2361                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2362                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2363
2364                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2365                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2366
2367                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2368                 check_spends!(node_txn[0], revoked_local_txn[0]);
2369
2370                 let mut witness_lens = BTreeSet::new();
2371                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2372                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2373                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2374                 assert_eq!(witness_lens.len(), 3);
2375                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2376                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2377                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2378
2379                 // Next nodes[1] broadcasts its current local tx state:
2380                 assert_eq!(node_txn[1].input.len(), 1);
2381                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2382         }
2383         get_announce_close_broadcast_events(&nodes, 0, 1);
2384         assert_eq!(nodes[0].node.list_channels().len(), 0);
2385         assert_eq!(nodes[1].node.list_channels().len(), 0);
2386 }
2387
2388 #[test]
2389 fn claim_htlc_outputs_single_tx() {
2390         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2391         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2392         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2393         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2394         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2395         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2396
2397         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2398
2399         // Rebalance the network to generate htlc in the two directions
2400         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2401         // 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
2402         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2403         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2404         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2405
2406         // Get the will-be-revoked local txn from node[0]
2407         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2408
2409         //Revoke the old state
2410         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2411
2412         {
2413                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2414                 check_added_monitors!(nodes[0], 1);
2415                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2416                 check_added_monitors!(nodes[1], 1);
2417                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2418                 let mut events = nodes[0].node.get_and_clear_pending_events();
2419                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2420                 match events[1] {
2421                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2422                         _ => panic!("Unexpected event"),
2423                 }
2424
2425                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2426                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2427
2428                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2429                 assert_eq!(node_txn.len(), 9);
2430                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2431                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2432                 // 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)
2433                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2434
2435                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2436                 assert_eq!(node_txn[0].input.len(), 1);
2437                 check_spends!(node_txn[0], chan_1.3);
2438                 assert_eq!(node_txn[1].input.len(), 1);
2439                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2440                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2441                 check_spends!(node_txn[1], node_txn[0]);
2442
2443                 // Justice transactions are indices 1-2-4
2444                 assert_eq!(node_txn[2].input.len(), 1);
2445                 assert_eq!(node_txn[3].input.len(), 1);
2446                 assert_eq!(node_txn[4].input.len(), 1);
2447
2448                 check_spends!(node_txn[2], revoked_local_txn[0]);
2449                 check_spends!(node_txn[3], revoked_local_txn[0]);
2450                 check_spends!(node_txn[4], revoked_local_txn[0]);
2451
2452                 let mut witness_lens = BTreeSet::new();
2453                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2454                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2455                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2456                 assert_eq!(witness_lens.len(), 3);
2457                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2458                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2459                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2460         }
2461         get_announce_close_broadcast_events(&nodes, 0, 1);
2462         assert_eq!(nodes[0].node.list_channels().len(), 0);
2463         assert_eq!(nodes[1].node.list_channels().len(), 0);
2464 }
2465
2466 #[test]
2467 fn test_htlc_on_chain_success() {
2468         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2469         // the preimage backward accordingly. So here we test that ChannelManager is
2470         // broadcasting the right event to other nodes in payment path.
2471         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2472         // A --------------------> B ----------------------> C (preimage)
2473         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2474         // commitment transaction was broadcast.
2475         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2476         // towards B.
2477         // B should be able to claim via preimage if A then broadcasts its local tx.
2478         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2479         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2480         // PaymentSent event).
2481
2482         let chanmon_cfgs = create_chanmon_cfgs(3);
2483         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2484         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2485         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2486
2487         // Create some initial channels
2488         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2489         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2490
2491         // Ensure all nodes are at the same height
2492         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2493         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2494         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2495         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2496
2497         // Rebalance the network a bit by relaying one payment through all the channels...
2498         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2499         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2500
2501         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2502         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2503
2504         // Broadcast legit commitment tx from C on B's chain
2505         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2506         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2507         assert_eq!(commitment_tx.len(), 1);
2508         check_spends!(commitment_tx[0], chan_2.3);
2509         nodes[2].node.claim_funds(our_payment_preimage);
2510         nodes[2].node.claim_funds(our_payment_preimage_2);
2511         check_added_monitors!(nodes[2], 2);
2512         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2513         assert!(updates.update_add_htlcs.is_empty());
2514         assert!(updates.update_fail_htlcs.is_empty());
2515         assert!(updates.update_fail_malformed_htlcs.is_empty());
2516         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2517
2518         mine_transaction(&nodes[2], &commitment_tx[0]);
2519         check_closed_broadcast!(nodes[2], true);
2520         check_added_monitors!(nodes[2], 1);
2521         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2522         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)
2523         assert_eq!(node_txn.len(), 5);
2524         assert_eq!(node_txn[0], node_txn[3]);
2525         assert_eq!(node_txn[1], node_txn[4]);
2526         assert_eq!(node_txn[2], commitment_tx[0]);
2527         check_spends!(node_txn[0], commitment_tx[0]);
2528         check_spends!(node_txn[1], commitment_tx[0]);
2529         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2530         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2531         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2532         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2533         assert_eq!(node_txn[0].lock_time, 0);
2534         assert_eq!(node_txn[1].lock_time, 0);
2535
2536         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2537         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2538         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2539         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2540         {
2541                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2542                 assert_eq!(added_monitors.len(), 1);
2543                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2544                 added_monitors.clear();
2545         }
2546         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2547         assert_eq!(forwarded_events.len(), 3);
2548         match forwarded_events[0] {
2549                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2550                 _ => panic!("Unexpected event"),
2551         }
2552         if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[1] {
2553                 } else { panic!(); }
2554         if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[2] {
2555                 } else { panic!(); }
2556         let events = nodes[1].node.get_and_clear_pending_msg_events();
2557         {
2558                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2559                 assert_eq!(added_monitors.len(), 2);
2560                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2561                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2562                 added_monitors.clear();
2563         }
2564         assert_eq!(events.len(), 3);
2565         match events[0] {
2566                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2567                 _ => panic!("Unexpected event"),
2568         }
2569         match events[1] {
2570                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2571                 _ => panic!("Unexpected event"),
2572         }
2573
2574         match events[2] {
2575                 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, .. } } => {
2576                         assert!(update_add_htlcs.is_empty());
2577                         assert!(update_fail_htlcs.is_empty());
2578                         assert_eq!(update_fulfill_htlcs.len(), 1);
2579                         assert!(update_fail_malformed_htlcs.is_empty());
2580                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2581                 },
2582                 _ => panic!("Unexpected event"),
2583         };
2584         macro_rules! check_tx_local_broadcast {
2585                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2586                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2587                         assert_eq!(node_txn.len(), 3);
2588                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2589                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2590                         check_spends!(node_txn[1], $commitment_tx);
2591                         check_spends!(node_txn[2], $commitment_tx);
2592                         assert_ne!(node_txn[1].lock_time, 0);
2593                         assert_ne!(node_txn[2].lock_time, 0);
2594                         if $htlc_offered {
2595                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2596                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2597                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2598                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2599                         } else {
2600                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2601                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2602                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2603                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2604                         }
2605                         check_spends!(node_txn[0], $chan_tx);
2606                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2607                         node_txn.clear();
2608                 } }
2609         }
2610         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2611         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2612         // timeout-claim of the output that nodes[2] just claimed via success.
2613         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2614
2615         // Broadcast legit commitment tx from A on B's chain
2616         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2617         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2618         check_spends!(node_a_commitment_tx[0], chan_1.3);
2619         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2620         check_closed_broadcast!(nodes[1], true);
2621         check_added_monitors!(nodes[1], 1);
2622         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2623         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2624         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2625         let commitment_spend =
2626                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2627                         check_spends!(node_txn[1], commitment_tx[0]);
2628                         check_spends!(node_txn[2], commitment_tx[0]);
2629                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2630                         &node_txn[0]
2631                 } else {
2632                         check_spends!(node_txn[0], commitment_tx[0]);
2633                         check_spends!(node_txn[1], commitment_tx[0]);
2634                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2635                         &node_txn[2]
2636                 };
2637
2638         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2639         assert_eq!(commitment_spend.input.len(), 2);
2640         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2641         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2642         assert_eq!(commitment_spend.lock_time, 0);
2643         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2644         check_spends!(node_txn[3], chan_1.3);
2645         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2646         check_spends!(node_txn[4], node_txn[3]);
2647         check_spends!(node_txn[5], node_txn[3]);
2648         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2649         // we already checked the same situation with A.
2650
2651         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2652         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2653         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2654         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2655         check_closed_broadcast!(nodes[0], true);
2656         check_added_monitors!(nodes[0], 1);
2657         let events = nodes[0].node.get_and_clear_pending_events();
2658         assert_eq!(events.len(), 3);
2659         let mut first_claimed = false;
2660         for event in events {
2661                 match event {
2662                         Event::PaymentSent { payment_preimage, payment_hash } => {
2663                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2664                                         assert!(!first_claimed);
2665                                         first_claimed = true;
2666                                 } else {
2667                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2668                                         assert_eq!(payment_hash, payment_hash_2);
2669                                 }
2670                         },
2671                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2672                         _ => panic!("Unexpected event"),
2673                 }
2674         }
2675         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2676 }
2677
2678 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2679         // Test that in case of a unilateral close onchain, we detect the state of output and
2680         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2681         // broadcasting the right event to other nodes in payment path.
2682         // A ------------------> B ----------------------> C (timeout)
2683         //    B's commitment tx                 C's commitment tx
2684         //            \                                  \
2685         //         B's HTLC timeout tx               B's timeout tx
2686
2687         let chanmon_cfgs = create_chanmon_cfgs(3);
2688         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2689         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2690         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2691         *nodes[0].connect_style.borrow_mut() = connect_style;
2692         *nodes[1].connect_style.borrow_mut() = connect_style;
2693         *nodes[2].connect_style.borrow_mut() = connect_style;
2694
2695         // Create some intial channels
2696         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2697         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2698
2699         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2700         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2701         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2702
2703         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2704
2705         // Broadcast legit commitment tx from C on B's chain
2706         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2707         check_spends!(commitment_tx[0], chan_2.3);
2708         nodes[2].node.fail_htlc_backwards(&payment_hash);
2709         check_added_monitors!(nodes[2], 0);
2710         expect_pending_htlcs_forwardable!(nodes[2]);
2711         check_added_monitors!(nodes[2], 1);
2712
2713         let events = nodes[2].node.get_and_clear_pending_msg_events();
2714         assert_eq!(events.len(), 1);
2715         match events[0] {
2716                 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, .. } } => {
2717                         assert!(update_add_htlcs.is_empty());
2718                         assert!(!update_fail_htlcs.is_empty());
2719                         assert!(update_fulfill_htlcs.is_empty());
2720                         assert!(update_fail_malformed_htlcs.is_empty());
2721                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2722                 },
2723                 _ => panic!("Unexpected event"),
2724         };
2725         mine_transaction(&nodes[2], &commitment_tx[0]);
2726         check_closed_broadcast!(nodes[2], true);
2727         check_added_monitors!(nodes[2], 1);
2728         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2729         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2730         assert_eq!(node_txn.len(), 1);
2731         check_spends!(node_txn[0], chan_2.3);
2732         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2733
2734         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2735         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2736         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2737         mine_transaction(&nodes[1], &commitment_tx[0]);
2738         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2739         let timeout_tx;
2740         {
2741                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2742                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2743                 assert_eq!(node_txn[0], node_txn[3]);
2744                 assert_eq!(node_txn[1], node_txn[4]);
2745
2746                 check_spends!(node_txn[2], commitment_tx[0]);
2747                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2748
2749                 check_spends!(node_txn[0], chan_2.3);
2750                 check_spends!(node_txn[1], node_txn[0]);
2751                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2752                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2753
2754                 timeout_tx = node_txn[2].clone();
2755                 node_txn.clear();
2756         }
2757
2758         mine_transaction(&nodes[1], &timeout_tx);
2759         check_added_monitors!(nodes[1], 1);
2760         check_closed_broadcast!(nodes[1], true);
2761         {
2762                 // B will rebroadcast a fee-bumped timeout transaction here.
2763                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2764                 assert_eq!(node_txn.len(), 1);
2765                 check_spends!(node_txn[0], commitment_tx[0]);
2766         }
2767
2768         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2769         {
2770                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2771                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2772                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2773                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2774                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2775                 if node_txn.len() == 1 {
2776                         check_spends!(node_txn[0], chan_2.3);
2777                 } else {
2778                         assert_eq!(node_txn.len(), 0);
2779                 }
2780         }
2781
2782         expect_pending_htlcs_forwardable!(nodes[1]);
2783         check_added_monitors!(nodes[1], 1);
2784         let events = nodes[1].node.get_and_clear_pending_msg_events();
2785         assert_eq!(events.len(), 1);
2786         match events[0] {
2787                 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, .. } } => {
2788                         assert!(update_add_htlcs.is_empty());
2789                         assert!(!update_fail_htlcs.is_empty());
2790                         assert!(update_fulfill_htlcs.is_empty());
2791                         assert!(update_fail_malformed_htlcs.is_empty());
2792                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2793                 },
2794                 _ => panic!("Unexpected event"),
2795         };
2796
2797         // Broadcast legit commitment tx from B on A's chain
2798         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2799         check_spends!(commitment_tx[0], chan_1.3);
2800
2801         mine_transaction(&nodes[0], &commitment_tx[0]);
2802         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2803
2804         check_closed_broadcast!(nodes[0], true);
2805         check_added_monitors!(nodes[0], 1);
2806         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2807         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2808         assert_eq!(node_txn.len(), 2);
2809         check_spends!(node_txn[0], chan_1.3);
2810         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2811         check_spends!(node_txn[1], commitment_tx[0]);
2812         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2813 }
2814
2815 #[test]
2816 fn test_htlc_on_chain_timeout() {
2817         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2818         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2819         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2820 }
2821
2822 #[test]
2823 fn test_simple_commitment_revoked_fail_backward() {
2824         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2825         // and fail backward accordingly.
2826
2827         let chanmon_cfgs = create_chanmon_cfgs(3);
2828         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2829         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2830         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2831
2832         // Create some initial channels
2833         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2834         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2835
2836         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2837         // Get the will-be-revoked local txn from nodes[2]
2838         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2839         // Revoke the old state
2840         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2841
2842         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2843
2844         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2845         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2846         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2847         check_added_monitors!(nodes[1], 1);
2848         check_closed_broadcast!(nodes[1], true);
2849
2850         expect_pending_htlcs_forwardable!(nodes[1]);
2851         check_added_monitors!(nodes[1], 1);
2852         let events = nodes[1].node.get_and_clear_pending_msg_events();
2853         assert_eq!(events.len(), 1);
2854         match events[0] {
2855                 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, .. } } => {
2856                         assert!(update_add_htlcs.is_empty());
2857                         assert_eq!(update_fail_htlcs.len(), 1);
2858                         assert!(update_fulfill_htlcs.is_empty());
2859                         assert!(update_fail_malformed_htlcs.is_empty());
2860                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2861
2862                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2863                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2864                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
2865                 },
2866                 _ => panic!("Unexpected event"),
2867         }
2868 }
2869
2870 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2871         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2872         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2873         // commitment transaction anymore.
2874         // To do this, we have the peer which will broadcast a revoked commitment transaction send
2875         // a number of update_fail/commitment_signed updates without ever sending the RAA in
2876         // response to our commitment_signed. This is somewhat misbehavior-y, though not
2877         // technically disallowed and we should probably handle it reasonably.
2878         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2879         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2880         // transactions:
2881         // * Once we move it out of our holding cell/add it, we will immediately include it in a
2882         //   commitment_signed (implying it will be in the latest remote commitment transaction).
2883         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2884         //   and once they revoke the previous commitment transaction (allowing us to send a new
2885         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2886         let chanmon_cfgs = create_chanmon_cfgs(3);
2887         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2888         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2889         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2890
2891         // Create some initial channels
2892         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2893         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2894
2895         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 });
2896         // Get the will-be-revoked local txn from nodes[2]
2897         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2898         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2899         // Revoke the old state
2900         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2901
2902         let value = if use_dust {
2903                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2904                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2905                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
2906         } else { 3000000 };
2907
2908         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2909         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2910         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2911
2912         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2913         expect_pending_htlcs_forwardable!(nodes[2]);
2914         check_added_monitors!(nodes[2], 1);
2915         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2916         assert!(updates.update_add_htlcs.is_empty());
2917         assert!(updates.update_fulfill_htlcs.is_empty());
2918         assert!(updates.update_fail_malformed_htlcs.is_empty());
2919         assert_eq!(updates.update_fail_htlcs.len(), 1);
2920         assert!(updates.update_fee.is_none());
2921         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2922         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2923         // Drop the last RAA from 3 -> 2
2924
2925         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2926         expect_pending_htlcs_forwardable!(nodes[2]);
2927         check_added_monitors!(nodes[2], 1);
2928         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2929         assert!(updates.update_add_htlcs.is_empty());
2930         assert!(updates.update_fulfill_htlcs.is_empty());
2931         assert!(updates.update_fail_malformed_htlcs.is_empty());
2932         assert_eq!(updates.update_fail_htlcs.len(), 1);
2933         assert!(updates.update_fee.is_none());
2934         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2935         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2936         check_added_monitors!(nodes[1], 1);
2937         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2938         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2939         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2940         check_added_monitors!(nodes[2], 1);
2941
2942         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
2943         expect_pending_htlcs_forwardable!(nodes[2]);
2944         check_added_monitors!(nodes[2], 1);
2945         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2946         assert!(updates.update_add_htlcs.is_empty());
2947         assert!(updates.update_fulfill_htlcs.is_empty());
2948         assert!(updates.update_fail_malformed_htlcs.is_empty());
2949         assert_eq!(updates.update_fail_htlcs.len(), 1);
2950         assert!(updates.update_fee.is_none());
2951         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2952         // At this point first_payment_hash has dropped out of the latest two commitment
2953         // transactions that nodes[1] is tracking...
2954         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2955         check_added_monitors!(nodes[1], 1);
2956         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2957         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2958         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2959         check_added_monitors!(nodes[2], 1);
2960
2961         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2962         // on nodes[2]'s RAA.
2963         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
2964         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
2965         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2966         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2967         check_added_monitors!(nodes[1], 0);
2968
2969         if deliver_bs_raa {
2970                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
2971                 // One monitor for the new revocation preimage, no second on as we won't generate a new
2972                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2973                 check_added_monitors!(nodes[1], 1);
2974                 let events = nodes[1].node.get_and_clear_pending_events();
2975                 assert_eq!(events.len(), 1);
2976                 match events[0] {
2977                         Event::PendingHTLCsForwardable { .. } => { },
2978                         _ => panic!("Unexpected event"),
2979                 };
2980                 // Deliberately don't process the pending fail-back so they all fail back at once after
2981                 // block connection just like the !deliver_bs_raa case
2982         }
2983
2984         let mut failed_htlcs = HashSet::new();
2985         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2986
2987         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2988         check_added_monitors!(nodes[1], 1);
2989         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2990
2991         let events = nodes[1].node.get_and_clear_pending_events();
2992         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
2993         match events[0] {
2994                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
2995                 _ => panic!("Unexepected event"),
2996         }
2997         match events[1] {
2998                 Event::PaymentPathFailed { ref payment_hash, .. } => {
2999                         assert_eq!(*payment_hash, fourth_payment_hash);
3000                 },
3001                 _ => panic!("Unexpected event"),
3002         }
3003         if !deliver_bs_raa {
3004                 match events[2] {
3005                         Event::PendingHTLCsForwardable { .. } => { },
3006                         _ => panic!("Unexpected event"),
3007                 };
3008         }
3009         nodes[1].node.process_pending_htlc_forwards();
3010         check_added_monitors!(nodes[1], 1);
3011
3012         let events = nodes[1].node.get_and_clear_pending_msg_events();
3013         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3014         match events[if deliver_bs_raa { 1 } else { 0 }] {
3015                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3016                 _ => panic!("Unexpected event"),
3017         }
3018         match events[if deliver_bs_raa { 2 } else { 1 }] {
3019                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3020                         assert_eq!(channel_id, chan_2.2);
3021                         assert_eq!(data.as_str(), "Commitment or closing transaction was confirmed on chain.");
3022                 },
3023                 _ => panic!("Unexpected event"),
3024         }
3025         if deliver_bs_raa {
3026                 match events[0] {
3027                         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, .. } } => {
3028                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3029                                 assert_eq!(update_add_htlcs.len(), 1);
3030                                 assert!(update_fulfill_htlcs.is_empty());
3031                                 assert!(update_fail_htlcs.is_empty());
3032                                 assert!(update_fail_malformed_htlcs.is_empty());
3033                         },
3034                         _ => panic!("Unexpected event"),
3035                 }
3036         }
3037         match events[if deliver_bs_raa { 3 } else { 2 }] {
3038                 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, .. } } => {
3039                         assert!(update_add_htlcs.is_empty());
3040                         assert_eq!(update_fail_htlcs.len(), 3);
3041                         assert!(update_fulfill_htlcs.is_empty());
3042                         assert!(update_fail_malformed_htlcs.is_empty());
3043                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3044
3045                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3046                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3047                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3048
3049                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3050
3051                         let events = nodes[0].node.get_and_clear_pending_events();
3052                         assert_eq!(events.len(), 3);
3053                         match events[0] {
3054                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3055                                         assert!(failed_htlcs.insert(payment_hash.0));
3056                                         // If we delivered B's RAA we got an unknown preimage error, not something
3057                                         // that we should update our routing table for.
3058                                         if !deliver_bs_raa {
3059                                                 assert!(network_update.is_some());
3060                                         }
3061                                 },
3062                                 _ => panic!("Unexpected event"),
3063                         }
3064                         match events[1] {
3065                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3066                                         assert!(failed_htlcs.insert(payment_hash.0));
3067                                         assert!(network_update.is_some());
3068                                 },
3069                                 _ => panic!("Unexpected event"),
3070                         }
3071                         match events[2] {
3072                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3073                                         assert!(failed_htlcs.insert(payment_hash.0));
3074                                         assert!(network_update.is_some());
3075                                 },
3076                                 _ => panic!("Unexpected event"),
3077                         }
3078                 },
3079                 _ => panic!("Unexpected event"),
3080         }
3081
3082         assert!(failed_htlcs.contains(&first_payment_hash.0));
3083         assert!(failed_htlcs.contains(&second_payment_hash.0));
3084         assert!(failed_htlcs.contains(&third_payment_hash.0));
3085 }
3086
3087 #[test]
3088 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3089         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3090         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3091         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3092         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3093 }
3094
3095 #[test]
3096 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3097         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3098         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3099         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3100         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3101 }
3102
3103 #[test]
3104 fn fail_backward_pending_htlc_upon_channel_failure() {
3105         let chanmon_cfgs = create_chanmon_cfgs(2);
3106         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3107         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3108         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3109         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3110
3111         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3112         {
3113                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3114                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3115                 check_added_monitors!(nodes[0], 1);
3116
3117                 let payment_event = {
3118                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3119                         assert_eq!(events.len(), 1);
3120                         SendEvent::from_event(events.remove(0))
3121                 };
3122                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3123                 assert_eq!(payment_event.msgs.len(), 1);
3124         }
3125
3126         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3127         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3128         {
3129                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3130                 check_added_monitors!(nodes[0], 0);
3131
3132                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3133         }
3134
3135         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3136         {
3137                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3138
3139                 let secp_ctx = Secp256k1::new();
3140                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3141                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3142                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3143                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3144                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3145
3146                 // Send a 0-msat update_add_htlc to fail the channel.
3147                 let update_add_htlc = msgs::UpdateAddHTLC {
3148                         channel_id: chan.2,
3149                         htlc_id: 0,
3150                         amount_msat: 0,
3151                         payment_hash,
3152                         cltv_expiry,
3153                         onion_routing_packet,
3154                 };
3155                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3156         }
3157         let events = nodes[0].node.get_and_clear_pending_events();
3158         assert_eq!(events.len(), 2);
3159         // Check that Alice fails backward the pending HTLC from the second payment.
3160         match events[0] {
3161                 Event::PaymentPathFailed { payment_hash, .. } => {
3162                         assert_eq!(payment_hash, failed_payment_hash);
3163                 },
3164                 _ => panic!("Unexpected event"),
3165         }
3166         match events[1] {
3167                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3168                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3169                 },
3170                 _ => panic!("Unexpected event {:?}", events[1]),
3171         }
3172         check_closed_broadcast!(nodes[0], true);
3173         check_added_monitors!(nodes[0], 1);
3174 }
3175
3176 #[test]
3177 fn test_htlc_ignore_latest_remote_commitment() {
3178         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3179         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3180         let chanmon_cfgs = create_chanmon_cfgs(2);
3181         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3182         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3183         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3184         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3185
3186         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3187         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3188         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3189         check_closed_broadcast!(nodes[0], true);
3190         check_added_monitors!(nodes[0], 1);
3191         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3192
3193         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3194         assert_eq!(node_txn.len(), 3);
3195         assert_eq!(node_txn[0], node_txn[1]);
3196
3197         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3198         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3199         check_closed_broadcast!(nodes[1], true);
3200         check_added_monitors!(nodes[1], 1);
3201         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3202
3203         // Duplicate the connect_block call since this may happen due to other listeners
3204         // registering new transactions
3205         header.prev_blockhash = header.block_hash();
3206         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3207 }
3208
3209 #[test]
3210 fn test_force_close_fail_back() {
3211         // Check which HTLCs are failed-backwards on channel force-closure
3212         let chanmon_cfgs = create_chanmon_cfgs(3);
3213         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3214         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3215         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3216         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3217         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3218
3219         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3220
3221         let mut payment_event = {
3222                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3223                 check_added_monitors!(nodes[0], 1);
3224
3225                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3226                 assert_eq!(events.len(), 1);
3227                 SendEvent::from_event(events.remove(0))
3228         };
3229
3230         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3231         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3232
3233         expect_pending_htlcs_forwardable!(nodes[1]);
3234
3235         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3236         assert_eq!(events_2.len(), 1);
3237         payment_event = SendEvent::from_event(events_2.remove(0));
3238         assert_eq!(payment_event.msgs.len(), 1);
3239
3240         check_added_monitors!(nodes[1], 1);
3241         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3242         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3243         check_added_monitors!(nodes[2], 1);
3244         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3245
3246         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3247         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3248         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3249
3250         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3251         check_closed_broadcast!(nodes[2], true);
3252         check_added_monitors!(nodes[2], 1);
3253         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3254         let tx = {
3255                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3256                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3257                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3258                 // back to nodes[1] upon timeout otherwise.
3259                 assert_eq!(node_txn.len(), 1);
3260                 node_txn.remove(0)
3261         };
3262
3263         mine_transaction(&nodes[1], &tx);
3264
3265         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3266         check_closed_broadcast!(nodes[1], true);
3267         check_added_monitors!(nodes[1], 1);
3268         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3269
3270         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3271         {
3272                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3273                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3274         }
3275         mine_transaction(&nodes[2], &tx);
3276         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3277         assert_eq!(node_txn.len(), 1);
3278         assert_eq!(node_txn[0].input.len(), 1);
3279         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3280         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3281         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3282
3283         check_spends!(node_txn[0], tx);
3284 }
3285
3286 #[test]
3287 fn test_dup_events_on_peer_disconnect() {
3288         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3289         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3290         // as we used to generate the event immediately upon receipt of the payment preimage in the
3291         // update_fulfill_htlc message.
3292
3293         let chanmon_cfgs = create_chanmon_cfgs(2);
3294         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3295         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3296         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3297         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3298
3299         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3300
3301         assert!(nodes[1].node.claim_funds(payment_preimage));
3302         check_added_monitors!(nodes[1], 1);
3303         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3304         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3305         expect_payment_sent!(nodes[0], payment_preimage);
3306
3307         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3308         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3309
3310         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3311         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3312 }
3313
3314 #[test]
3315 fn test_simple_peer_disconnect() {
3316         // Test that we can reconnect when there are no lost messages
3317         let chanmon_cfgs = create_chanmon_cfgs(3);
3318         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3319         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3320         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3321         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3322         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3323
3324         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3325         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3326         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3327
3328         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3329         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3330         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3331         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3332
3333         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3334         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3335         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3336
3337         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3338         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3339         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3340         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3341
3342         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3343         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3344
3345         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3346         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3347
3348         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3349         {
3350                 let events = nodes[0].node.get_and_clear_pending_events();
3351                 assert_eq!(events.len(), 2);
3352                 match events[0] {
3353                         Event::PaymentSent { payment_preimage, payment_hash } => {
3354                                 assert_eq!(payment_preimage, payment_preimage_3);
3355                                 assert_eq!(payment_hash, payment_hash_3);
3356                         },
3357                         _ => panic!("Unexpected event"),
3358                 }
3359                 match events[1] {
3360                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3361                                 assert_eq!(payment_hash, payment_hash_5);
3362                                 assert!(rejected_by_dest);
3363                         },
3364                         _ => panic!("Unexpected event"),
3365                 }
3366         }
3367
3368         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3369         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3370 }
3371
3372 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3373         // Test that we can reconnect when in-flight HTLC updates get dropped
3374         let chanmon_cfgs = create_chanmon_cfgs(2);
3375         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3376         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3377         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3378
3379         let mut as_funding_locked = None;
3380         if messages_delivered == 0 {
3381                 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3382                 as_funding_locked = Some(funding_locked);
3383                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3384                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3385                 // it before the channel_reestablish message.
3386         } else {
3387                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3388         }
3389
3390         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3391
3392         let payment_event = {
3393                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3394                 check_added_monitors!(nodes[0], 1);
3395
3396                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3397                 assert_eq!(events.len(), 1);
3398                 SendEvent::from_event(events.remove(0))
3399         };
3400         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3401
3402         if messages_delivered < 2 {
3403                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3404         } else {
3405                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3406                 if messages_delivered >= 3 {
3407                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3408                         check_added_monitors!(nodes[1], 1);
3409                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3410
3411                         if messages_delivered >= 4 {
3412                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3413                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3414                                 check_added_monitors!(nodes[0], 1);
3415
3416                                 if messages_delivered >= 5 {
3417                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3418                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3419                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3420                                         check_added_monitors!(nodes[0], 1);
3421
3422                                         if messages_delivered >= 6 {
3423                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3424                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3425                                                 check_added_monitors!(nodes[1], 1);
3426                                         }
3427                                 }
3428                         }
3429                 }
3430         }
3431
3432         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3433         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3434         if messages_delivered < 3 {
3435                 if simulate_broken_lnd {
3436                         // lnd has a long-standing bug where they send a funding_locked prior to a
3437                         // channel_reestablish if you reconnect prior to funding_locked time.
3438                         //
3439                         // Here we simulate that behavior, delivering a funding_locked immediately on
3440                         // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3441                         // in `reconnect_nodes` but we currently don't fail based on that.
3442                         //
3443                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3444                         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3445                 }
3446                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3447                 // received on either side, both sides will need to resend them.
3448                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3449         } else if messages_delivered == 3 {
3450                 // nodes[0] still wants its RAA + commitment_signed
3451                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3452         } else if messages_delivered == 4 {
3453                 // nodes[0] still wants its commitment_signed
3454                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3455         } else if messages_delivered == 5 {
3456                 // nodes[1] still wants its final RAA
3457                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3458         } else if messages_delivered == 6 {
3459                 // Everything was delivered...
3460                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3461         }
3462
3463         let events_1 = nodes[1].node.get_and_clear_pending_events();
3464         assert_eq!(events_1.len(), 1);
3465         match events_1[0] {
3466                 Event::PendingHTLCsForwardable { .. } => { },
3467                 _ => panic!("Unexpected event"),
3468         };
3469
3470         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3471         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3472         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3473
3474         nodes[1].node.process_pending_htlc_forwards();
3475
3476         let events_2 = nodes[1].node.get_and_clear_pending_events();
3477         assert_eq!(events_2.len(), 1);
3478         match events_2[0] {
3479                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3480                         assert_eq!(payment_hash_1, *payment_hash);
3481                         assert_eq!(amt, 1000000);
3482                         match &purpose {
3483                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3484                                         assert!(payment_preimage.is_none());
3485                                         assert_eq!(payment_secret_1, *payment_secret);
3486                                 },
3487                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3488                         }
3489                 },
3490                 _ => panic!("Unexpected event"),
3491         }
3492
3493         nodes[1].node.claim_funds(payment_preimage_1);
3494         check_added_monitors!(nodes[1], 1);
3495
3496         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3497         assert_eq!(events_3.len(), 1);
3498         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3499                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3500                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3501                         assert!(updates.update_add_htlcs.is_empty());
3502                         assert!(updates.update_fail_htlcs.is_empty());
3503                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3504                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3505                         assert!(updates.update_fee.is_none());
3506                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3507                 },
3508                 _ => panic!("Unexpected event"),
3509         };
3510
3511         if messages_delivered >= 1 {
3512                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3513
3514                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3515                 assert_eq!(events_4.len(), 1);
3516                 match events_4[0] {
3517                         Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
3518                                 assert_eq!(payment_preimage_1, *payment_preimage);
3519                                 assert_eq!(payment_hash_1, *payment_hash);
3520                         },
3521                         _ => panic!("Unexpected event"),
3522                 }
3523
3524                 if messages_delivered >= 2 {
3525                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3526                         check_added_monitors!(nodes[0], 1);
3527                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3528
3529                         if messages_delivered >= 3 {
3530                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3531                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3532                                 check_added_monitors!(nodes[1], 1);
3533
3534                                 if messages_delivered >= 4 {
3535                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3536                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3537                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3538                                         check_added_monitors!(nodes[1], 1);
3539
3540                                         if messages_delivered >= 5 {
3541                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3542                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3543                                                 check_added_monitors!(nodes[0], 1);
3544                                         }
3545                                 }
3546                         }
3547                 }
3548         }
3549
3550         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3551         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3552         if messages_delivered < 2 {
3553                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3554                 if messages_delivered < 1 {
3555                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3556                         assert_eq!(events_4.len(), 1);
3557                         match events_4[0] {
3558                                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
3559                                         assert_eq!(payment_preimage_1, *payment_preimage);
3560                                         assert_eq!(payment_hash_1, *payment_hash);
3561                                 },
3562                                 _ => panic!("Unexpected event"),
3563                         }
3564                 } else {
3565                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3566                 }
3567         } else if messages_delivered == 2 {
3568                 // nodes[0] still wants its RAA + commitment_signed
3569                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3570         } else if messages_delivered == 3 {
3571                 // nodes[0] still wants its commitment_signed
3572                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3573         } else if messages_delivered == 4 {
3574                 // nodes[1] still wants its final RAA
3575                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3576         } else if messages_delivered == 5 {
3577                 // Everything was delivered...
3578                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3579         }
3580
3581         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3582         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3583         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3584
3585         // Channel should still work fine...
3586         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3587         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3588         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3589 }
3590
3591 #[test]
3592 fn test_drop_messages_peer_disconnect_a() {
3593         do_test_drop_messages_peer_disconnect(0, true);
3594         do_test_drop_messages_peer_disconnect(0, false);
3595         do_test_drop_messages_peer_disconnect(1, false);
3596         do_test_drop_messages_peer_disconnect(2, false);
3597 }
3598
3599 #[test]
3600 fn test_drop_messages_peer_disconnect_b() {
3601         do_test_drop_messages_peer_disconnect(3, false);
3602         do_test_drop_messages_peer_disconnect(4, false);
3603         do_test_drop_messages_peer_disconnect(5, false);
3604         do_test_drop_messages_peer_disconnect(6, false);
3605 }
3606
3607 #[test]
3608 fn test_funding_peer_disconnect() {
3609         // Test that we can lock in our funding tx while disconnected
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 persister: test_utils::TestPersister;
3614         let new_chain_monitor: test_utils::TestChainMonitor;
3615         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3616         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3617         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3618
3619         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3620         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3621
3622         confirm_transaction(&nodes[0], &tx);
3623         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3624         let chan_id;
3625         assert_eq!(events_1.len(), 1);
3626         match events_1[0] {
3627                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3628                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3629                         chan_id = msg.channel_id;
3630                 },
3631                 _ => panic!("Unexpected event"),
3632         }
3633
3634         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3635
3636         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3637         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3638
3639         confirm_transaction(&nodes[1], &tx);
3640         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3641         assert_eq!(events_2.len(), 2);
3642         let funding_locked = match events_2[0] {
3643                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3644                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3645                         msg.clone()
3646                 },
3647                 _ => panic!("Unexpected event"),
3648         };
3649         let bs_announcement_sigs = match events_2[1] {
3650                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3651                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3652                         msg.clone()
3653                 },
3654                 _ => panic!("Unexpected event"),
3655         };
3656
3657         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3658
3659         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3660         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3661         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3662         assert_eq!(events_3.len(), 2);
3663         let as_announcement_sigs = match events_3[0] {
3664                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3665                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3666                         msg.clone()
3667                 },
3668                 _ => panic!("Unexpected event"),
3669         };
3670         let (as_announcement, as_update) = match events_3[1] {
3671                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3672                         (msg.clone(), update_msg.clone())
3673                 },
3674                 _ => panic!("Unexpected event"),
3675         };
3676
3677         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3678         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3679         assert_eq!(events_4.len(), 1);
3680         let (_, bs_update) = match events_4[0] {
3681                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3682                         (msg.clone(), update_msg.clone())
3683                 },
3684                 _ => panic!("Unexpected event"),
3685         };
3686
3687         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3688         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3689         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3690
3691         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3692         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3693         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3694
3695         // Check that after deserialization and reconnection we can still generate an identical
3696         // channel_announcement from the cached signatures.
3697         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3698
3699         let nodes_0_serialized = nodes[0].node.encode();
3700         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3701         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3702
3703         persister = test_utils::TestPersister::new();
3704         let keys_manager = &chanmon_cfgs[0].keys_manager;
3705         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);
3706         nodes[0].chain_monitor = &new_chain_monitor;
3707         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3708         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3709                 &mut chan_0_monitor_read, keys_manager).unwrap();
3710         assert!(chan_0_monitor_read.is_empty());
3711
3712         let mut nodes_0_read = &nodes_0_serialized[..];
3713         let (_, nodes_0_deserialized_tmp) = {
3714                 let mut channel_monitors = HashMap::new();
3715                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3716                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3717                         default_config: UserConfig::default(),
3718                         keys_manager,
3719                         fee_estimator: node_cfgs[0].fee_estimator,
3720                         chain_monitor: nodes[0].chain_monitor,
3721                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3722                         logger: nodes[0].logger,
3723                         channel_monitors,
3724                 }).unwrap()
3725         };
3726         nodes_0_deserialized = nodes_0_deserialized_tmp;
3727         assert!(nodes_0_read.is_empty());
3728
3729         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3730         nodes[0].node = &nodes_0_deserialized;
3731         check_added_monitors!(nodes[0], 1);
3732
3733         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3734
3735         // as_announcement should be re-generated exactly by broadcast_node_announcement.
3736         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3737         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3738         let mut found_announcement = false;
3739         for event in msgs.iter() {
3740                 match event {
3741                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3742                                 if *msg == as_announcement { found_announcement = true; }
3743                         },
3744                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3745                         _ => panic!("Unexpected event"),
3746                 }
3747         }
3748         assert!(found_announcement);
3749 }
3750
3751 #[test]
3752 fn test_drop_messages_peer_disconnect_dual_htlc() {
3753         // Test that we can handle reconnecting when both sides of a channel have pending
3754         // commitment_updates when we disconnect.
3755         let chanmon_cfgs = create_chanmon_cfgs(2);
3756         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3757         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3758         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3759         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3760
3761         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3762
3763         // Now try to send a second payment which will fail to send
3764         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3765         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
3766         check_added_monitors!(nodes[0], 1);
3767
3768         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3769         assert_eq!(events_1.len(), 1);
3770         match events_1[0] {
3771                 MessageSendEvent::UpdateHTLCs { .. } => {},
3772                 _ => panic!("Unexpected event"),
3773         }
3774
3775         assert!(nodes[1].node.claim_funds(payment_preimage_1));
3776         check_added_monitors!(nodes[1], 1);
3777
3778         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3779         assert_eq!(events_2.len(), 1);
3780         match events_2[0] {
3781                 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 } } => {
3782                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3783                         assert!(update_add_htlcs.is_empty());
3784                         assert_eq!(update_fulfill_htlcs.len(), 1);
3785                         assert!(update_fail_htlcs.is_empty());
3786                         assert!(update_fail_malformed_htlcs.is_empty());
3787                         assert!(update_fee.is_none());
3788
3789                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3790                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3791                         assert_eq!(events_3.len(), 1);
3792                         match events_3[0] {
3793                                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
3794                                         assert_eq!(*payment_preimage, payment_preimage_1);
3795                                         assert_eq!(*payment_hash, payment_hash_1);
3796                                 },
3797                                 _ => panic!("Unexpected event"),
3798                         }
3799
3800                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3801                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3802                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3803                         check_added_monitors!(nodes[0], 1);
3804                 },
3805                 _ => panic!("Unexpected event"),
3806         }
3807
3808         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3809         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3810
3811         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3812         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3813         assert_eq!(reestablish_1.len(), 1);
3814         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3815         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3816         assert_eq!(reestablish_2.len(), 1);
3817
3818         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3819         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3820         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3821         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3822
3823         assert!(as_resp.0.is_none());
3824         assert!(bs_resp.0.is_none());
3825
3826         assert!(bs_resp.1.is_none());
3827         assert!(bs_resp.2.is_none());
3828
3829         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3830
3831         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3832         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3833         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3834         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3835         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3836         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3837         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3838         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3839         // No commitment_signed so get_event_msg's assert(len == 1) passes
3840         check_added_monitors!(nodes[1], 1);
3841
3842         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3843         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3844         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3845         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3846         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3847         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3848         assert!(bs_second_commitment_signed.update_fee.is_none());
3849         check_added_monitors!(nodes[1], 1);
3850
3851         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3852         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3853         assert!(as_commitment_signed.update_add_htlcs.is_empty());
3854         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3855         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3856         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3857         assert!(as_commitment_signed.update_fee.is_none());
3858         check_added_monitors!(nodes[0], 1);
3859
3860         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3861         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3862         // No commitment_signed so get_event_msg's assert(len == 1) passes
3863         check_added_monitors!(nodes[0], 1);
3864
3865         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3866         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3867         // No commitment_signed so get_event_msg's assert(len == 1) passes
3868         check_added_monitors!(nodes[1], 1);
3869
3870         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3871         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3872         check_added_monitors!(nodes[1], 1);
3873
3874         expect_pending_htlcs_forwardable!(nodes[1]);
3875
3876         let events_5 = nodes[1].node.get_and_clear_pending_events();
3877         assert_eq!(events_5.len(), 1);
3878         match events_5[0] {
3879                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
3880                         assert_eq!(payment_hash_2, *payment_hash);
3881                         match &purpose {
3882                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3883                                         assert!(payment_preimage.is_none());
3884                                         assert_eq!(payment_secret_2, *payment_secret);
3885                                 },
3886                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3887                         }
3888                 },
3889                 _ => panic!("Unexpected event"),
3890         }
3891
3892         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3893         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3894         check_added_monitors!(nodes[0], 1);
3895
3896         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3897 }
3898
3899 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3900         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3901         // to avoid our counterparty failing the channel.
3902         let chanmon_cfgs = create_chanmon_cfgs(2);
3903         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3904         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3905         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3906
3907         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3908
3909         let our_payment_hash = if send_partial_mpp {
3910                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
3911                 // Use the utility function send_payment_along_path to send the payment with MPP data which
3912                 // indicates there are more HTLCs coming.
3913                 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.
3914                 let payment_id = PaymentId([42; 32]);
3915                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height, payment_id, &None).unwrap();
3916                 check_added_monitors!(nodes[0], 1);
3917                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3918                 assert_eq!(events.len(), 1);
3919                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3920                 // hop should *not* yet generate any PaymentReceived event(s).
3921                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
3922                 our_payment_hash
3923         } else {
3924                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3925         };
3926
3927         let mut block = Block {
3928                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3929                 txdata: vec![],
3930         };
3931         connect_block(&nodes[0], &block);
3932         connect_block(&nodes[1], &block);
3933         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
3934         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
3935                 block.header.prev_blockhash = block.block_hash();
3936                 connect_block(&nodes[0], &block);
3937                 connect_block(&nodes[1], &block);
3938         }
3939
3940         expect_pending_htlcs_forwardable!(nodes[1]);
3941
3942         check_added_monitors!(nodes[1], 1);
3943         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3944         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3945         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3946         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3947         assert!(htlc_timeout_updates.update_fee.is_none());
3948
3949         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3950         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3951         // 100_000 msat as u64, followed by the height at which we failed back above
3952         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
3953         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
3954         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
3955 }
3956
3957 #[test]
3958 fn test_htlc_timeout() {
3959         do_test_htlc_timeout(true);
3960         do_test_htlc_timeout(false);
3961 }
3962
3963 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
3964         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
3965         let chanmon_cfgs = create_chanmon_cfgs(3);
3966         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3967         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3968         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3969         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3970         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3971
3972         // Make sure all nodes are at the same starting height
3973         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
3974         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
3975         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
3976
3977         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
3978         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
3979         {
3980                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
3981         }
3982         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
3983         check_added_monitors!(nodes[1], 1);
3984
3985         // Now attempt to route a second payment, which should be placed in the holding cell
3986         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
3987         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
3988         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
3989         if forwarded_htlc {
3990                 check_added_monitors!(nodes[0], 1);
3991                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
3992                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3993                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3994                 expect_pending_htlcs_forwardable!(nodes[1]);
3995         }
3996         check_added_monitors!(nodes[1], 0);
3997
3998         connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
3999         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4000         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4001         connect_blocks(&nodes[1], 1);
4002
4003         if forwarded_htlc {
4004                 expect_pending_htlcs_forwardable!(nodes[1]);
4005                 check_added_monitors!(nodes[1], 1);
4006                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4007                 assert_eq!(fail_commit.len(), 1);
4008                 match fail_commit[0] {
4009                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4010                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4011                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4012                         },
4013                         _ => unreachable!(),
4014                 }
4015                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4016         } else {
4017                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4018         }
4019 }
4020
4021 #[test]
4022 fn test_holding_cell_htlc_add_timeouts() {
4023         do_test_holding_cell_htlc_add_timeouts(false);
4024         do_test_holding_cell_htlc_add_timeouts(true);
4025 }
4026
4027 #[test]
4028 fn test_no_txn_manager_serialize_deserialize() {
4029         let chanmon_cfgs = create_chanmon_cfgs(2);
4030         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4031         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4032         let logger: test_utils::TestLogger;
4033         let fee_estimator: test_utils::TestFeeEstimator;
4034         let persister: test_utils::TestPersister;
4035         let new_chain_monitor: test_utils::TestChainMonitor;
4036         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4037         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4038
4039         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4040
4041         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4042
4043         let nodes_0_serialized = nodes[0].node.encode();
4044         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4045         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4046                 .write(&mut chan_0_monitor_serialized).unwrap();
4047
4048         logger = test_utils::TestLogger::new();
4049         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4050         persister = test_utils::TestPersister::new();
4051         let keys_manager = &chanmon_cfgs[0].keys_manager;
4052         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4053         nodes[0].chain_monitor = &new_chain_monitor;
4054         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4055         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4056                 &mut chan_0_monitor_read, keys_manager).unwrap();
4057         assert!(chan_0_monitor_read.is_empty());
4058
4059         let mut nodes_0_read = &nodes_0_serialized[..];
4060         let config = UserConfig::default();
4061         let (_, nodes_0_deserialized_tmp) = {
4062                 let mut channel_monitors = HashMap::new();
4063                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4064                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4065                         default_config: config,
4066                         keys_manager,
4067                         fee_estimator: &fee_estimator,
4068                         chain_monitor: nodes[0].chain_monitor,
4069                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4070                         logger: &logger,
4071                         channel_monitors,
4072                 }).unwrap()
4073         };
4074         nodes_0_deserialized = nodes_0_deserialized_tmp;
4075         assert!(nodes_0_read.is_empty());
4076
4077         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4078         nodes[0].node = &nodes_0_deserialized;
4079         assert_eq!(nodes[0].node.list_channels().len(), 1);
4080         check_added_monitors!(nodes[0], 1);
4081
4082         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4083         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4084         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4085         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4086
4087         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4088         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4089         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4090         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4091
4092         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4093         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4094         for node in nodes.iter() {
4095                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4096                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4097                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4098         }
4099
4100         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4101 }
4102
4103 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
4104         // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
4105         // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
4106         // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
4107         // the ChannelMonitor tells it to.
4108         //
4109         // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
4110         // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
4111         // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
4112         let chanmon_cfgs = create_chanmon_cfgs(2);
4113         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4114         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4115         let persister: test_utils::TestPersister;
4116         let new_chain_monitor: test_utils::TestChainMonitor;
4117         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4118         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4119
4120         let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4121
4122         // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
4123         // nodes[0].
4124         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10000000);
4125         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
4126         check_closed_broadcast!(nodes[0], true);
4127         check_added_monitors!(nodes[0], 1);
4128         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4129
4130         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4131         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4132
4133         // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
4134         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
4135         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4136         assert_eq!(node_txn.len(), 3);
4137         assert_eq!(node_txn[0], node_txn[1]);
4138         check_spends!(node_txn[1], funding_tx);
4139         check_spends!(node_txn[2], node_txn[1]);
4140         let timeout_txn = vec![node_txn[2].clone()];
4141
4142         assert!(nodes[1].node.claim_funds(payment_preimage));
4143         check_added_monitors!(nodes[1], 1);
4144
4145         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4146         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()]});
4147         check_closed_broadcast!(nodes[1], true);
4148         check_added_monitors!(nodes[1], 1);
4149         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4150         let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4151
4152         header.prev_blockhash = nodes[0].best_block_hash();
4153         connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()]});
4154
4155         if confirm_commitment_tx {
4156                 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
4157         }
4158
4159         header.prev_blockhash = nodes[0].best_block_hash();
4160         let claim_block = Block { header, txdata: if payment_timeout { timeout_txn } else { claim_txn } };
4161
4162         if payment_timeout {
4163                 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
4164                 connect_block(&nodes[0], &claim_block);
4165                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
4166         }
4167
4168         // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
4169         // returning TemporaryFailure. This should cause the claim event to never make its way to the
4170         // ChannelManager.
4171         chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
4172         chanmon_cfgs[0].persister.set_update_ret(Err(ChannelMonitorUpdateErr::TemporaryFailure));
4173
4174         if payment_timeout {
4175                 connect_blocks(&nodes[0], 1);
4176         } else {
4177                 connect_block(&nodes[0], &claim_block);
4178         }
4179
4180         let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
4181         let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
4182                 .get_mut(&funding_txo).unwrap().drain().collect();
4183         assert_eq!(mon_updates.len(), 1);
4184         assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
4185         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4186
4187         // If we persist the ChannelManager here, we should get the PaymentSent event after
4188         // deserialization.
4189         let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
4190         if !persist_manager_post_event {
4191                 nodes[0].node.write(&mut chan_manager_serialized).unwrap();
4192         }
4193
4194         // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
4195         // payment sent event.
4196         chanmon_cfgs[0].persister.set_update_ret(Ok(()));
4197         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4198         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4199         nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, mon_updates[0]).unwrap();
4200         if payment_timeout {
4201                 expect_payment_failed!(nodes[0], payment_hash, true);
4202         } else {
4203                 expect_payment_sent!(nodes[0], payment_preimage);
4204         }
4205
4206         // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
4207         // twice.
4208         if persist_manager_post_event {
4209                 nodes[0].node.write(&mut chan_manager_serialized).unwrap();
4210         }
4211
4212         // Now reload nodes[0]...
4213         persister = test_utils::TestPersister::new();
4214         let keys_manager = &chanmon_cfgs[0].keys_manager;
4215         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);
4216         nodes[0].chain_monitor = &new_chain_monitor;
4217         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4218         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4219                 &mut chan_0_monitor_read, keys_manager).unwrap();
4220         assert!(chan_0_monitor_read.is_empty());
4221
4222         let (_, nodes_0_deserialized_tmp) = {
4223                 let mut channel_monitors = HashMap::new();
4224                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4225                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
4226                         ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
4227                                 default_config: Default::default(),
4228                                 keys_manager,
4229                                 fee_estimator: node_cfgs[0].fee_estimator,
4230                                 chain_monitor: nodes[0].chain_monitor,
4231                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4232                                 logger: nodes[0].logger,
4233                                 channel_monitors,
4234                         }).unwrap()
4235         };
4236         nodes_0_deserialized = nodes_0_deserialized_tmp;
4237
4238         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4239         check_added_monitors!(nodes[0], 1);
4240         nodes[0].node = &nodes_0_deserialized;
4241
4242         if persist_manager_post_event {
4243                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4244         } else if payment_timeout {
4245                 expect_payment_failed!(nodes[0], payment_hash, true);
4246         } else {
4247                 expect_payment_sent!(nodes[0], payment_preimage);
4248         }
4249
4250         // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
4251         // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
4252         // payment events should kick in, leaving us with no pending events here.
4253         let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
4254         nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
4255         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4256 }
4257
4258 #[test]
4259 fn test_dup_htlc_onchain_fails_on_reload() {
4260         do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
4261         do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
4262         do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
4263         do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
4264         do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
4265         do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
4266 }
4267
4268 #[test]
4269 fn test_manager_serialize_deserialize_events() {
4270         // This test makes sure the events field in ChannelManager survives de/serialization
4271         let chanmon_cfgs = create_chanmon_cfgs(2);
4272         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4273         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4274         let fee_estimator: test_utils::TestFeeEstimator;
4275         let persister: test_utils::TestPersister;
4276         let logger: test_utils::TestLogger;
4277         let new_chain_monitor: test_utils::TestChainMonitor;
4278         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4279         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4280
4281         // Start creating a channel, but stop right before broadcasting the funding transaction
4282         let channel_value = 100000;
4283         let push_msat = 10001;
4284         let a_flags = InitFeatures::known();
4285         let b_flags = InitFeatures::known();
4286         let node_a = nodes.remove(0);
4287         let node_b = nodes.remove(0);
4288         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4289         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()));
4290         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()));
4291
4292         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4293
4294         node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4295         check_added_monitors!(node_a, 0);
4296
4297         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()));
4298         {
4299                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4300                 assert_eq!(added_monitors.len(), 1);
4301                 assert_eq!(added_monitors[0].0, funding_output);
4302                 added_monitors.clear();
4303         }
4304
4305         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4306         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4307         {
4308                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4309                 assert_eq!(added_monitors.len(), 1);
4310                 assert_eq!(added_monitors[0].0, funding_output);
4311                 added_monitors.clear();
4312         }
4313         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4314
4315         nodes.push(node_a);
4316         nodes.push(node_b);
4317
4318         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4319         let nodes_0_serialized = nodes[0].node.encode();
4320         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4321         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4322
4323         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4324         logger = test_utils::TestLogger::new();
4325         persister = test_utils::TestPersister::new();
4326         let keys_manager = &chanmon_cfgs[0].keys_manager;
4327         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4328         nodes[0].chain_monitor = &new_chain_monitor;
4329         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4330         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4331                 &mut chan_0_monitor_read, keys_manager).unwrap();
4332         assert!(chan_0_monitor_read.is_empty());
4333
4334         let mut nodes_0_read = &nodes_0_serialized[..];
4335         let config = UserConfig::default();
4336         let (_, nodes_0_deserialized_tmp) = {
4337                 let mut channel_monitors = HashMap::new();
4338                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4339                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4340                         default_config: config,
4341                         keys_manager,
4342                         fee_estimator: &fee_estimator,
4343                         chain_monitor: nodes[0].chain_monitor,
4344                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4345                         logger: &logger,
4346                         channel_monitors,
4347                 }).unwrap()
4348         };
4349         nodes_0_deserialized = nodes_0_deserialized_tmp;
4350         assert!(nodes_0_read.is_empty());
4351
4352         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4353
4354         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4355         nodes[0].node = &nodes_0_deserialized;
4356
4357         // After deserializing, make sure the funding_transaction is still held by the channel manager
4358         let events_4 = nodes[0].node.get_and_clear_pending_events();
4359         assert_eq!(events_4.len(), 0);
4360         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4361         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4362
4363         // Make sure the channel is functioning as though the de/serialization never happened
4364         assert_eq!(nodes[0].node.list_channels().len(), 1);
4365         check_added_monitors!(nodes[0], 1);
4366
4367         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4368         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4369         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4370         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4371
4372         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4373         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4374         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4375         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4376
4377         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4378         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4379         for node in nodes.iter() {
4380                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4381                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4382                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4383         }
4384
4385         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4386 }
4387
4388 #[test]
4389 fn test_simple_manager_serialize_deserialize() {
4390         let chanmon_cfgs = create_chanmon_cfgs(2);
4391         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4392         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4393         let logger: test_utils::TestLogger;
4394         let fee_estimator: test_utils::TestFeeEstimator;
4395         let persister: test_utils::TestPersister;
4396         let new_chain_monitor: test_utils::TestChainMonitor;
4397         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4398         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4399         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4400
4401         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4402         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4403
4404         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4405
4406         let nodes_0_serialized = nodes[0].node.encode();
4407         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4408         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4409
4410         logger = test_utils::TestLogger::new();
4411         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4412         persister = test_utils::TestPersister::new();
4413         let keys_manager = &chanmon_cfgs[0].keys_manager;
4414         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4415         nodes[0].chain_monitor = &new_chain_monitor;
4416         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4417         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4418                 &mut chan_0_monitor_read, keys_manager).unwrap();
4419         assert!(chan_0_monitor_read.is_empty());
4420
4421         let mut nodes_0_read = &nodes_0_serialized[..];
4422         let (_, nodes_0_deserialized_tmp) = {
4423                 let mut channel_monitors = HashMap::new();
4424                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4425                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4426                         default_config: UserConfig::default(),
4427                         keys_manager,
4428                         fee_estimator: &fee_estimator,
4429                         chain_monitor: nodes[0].chain_monitor,
4430                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4431                         logger: &logger,
4432                         channel_monitors,
4433                 }).unwrap()
4434         };
4435         nodes_0_deserialized = nodes_0_deserialized_tmp;
4436         assert!(nodes_0_read.is_empty());
4437
4438         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4439         nodes[0].node = &nodes_0_deserialized;
4440         check_added_monitors!(nodes[0], 1);
4441
4442         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4443
4444         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4445         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4446 }
4447
4448 #[test]
4449 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4450         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4451         let chanmon_cfgs = create_chanmon_cfgs(4);
4452         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4453         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4454         let logger: test_utils::TestLogger;
4455         let fee_estimator: test_utils::TestFeeEstimator;
4456         let persister: test_utils::TestPersister;
4457         let new_chain_monitor: test_utils::TestChainMonitor;
4458         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4459         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4460         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4461         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4462         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4463
4464         let mut node_0_stale_monitors_serialized = Vec::new();
4465         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4466                 let mut writer = test_utils::TestVecWriter(Vec::new());
4467                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4468                 node_0_stale_monitors_serialized.push(writer.0);
4469         }
4470
4471         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4472
4473         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4474         let nodes_0_serialized = nodes[0].node.encode();
4475
4476         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4477         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4478         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4479         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4480
4481         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4482         // nodes[3])
4483         let mut node_0_monitors_serialized = Vec::new();
4484         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4485                 let mut writer = test_utils::TestVecWriter(Vec::new());
4486                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4487                 node_0_monitors_serialized.push(writer.0);
4488         }
4489
4490         logger = test_utils::TestLogger::new();
4491         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4492         persister = test_utils::TestPersister::new();
4493         let keys_manager = &chanmon_cfgs[0].keys_manager;
4494         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4495         nodes[0].chain_monitor = &new_chain_monitor;
4496
4497
4498         let mut node_0_stale_monitors = Vec::new();
4499         for serialized in node_0_stale_monitors_serialized.iter() {
4500                 let mut read = &serialized[..];
4501                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4502                 assert!(read.is_empty());
4503                 node_0_stale_monitors.push(monitor);
4504         }
4505
4506         let mut node_0_monitors = Vec::new();
4507         for serialized in node_0_monitors_serialized.iter() {
4508                 let mut read = &serialized[..];
4509                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4510                 assert!(read.is_empty());
4511                 node_0_monitors.push(monitor);
4512         }
4513
4514         let mut nodes_0_read = &nodes_0_serialized[..];
4515         if let Err(msgs::DecodeError::InvalidValue) =
4516                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4517                 default_config: UserConfig::default(),
4518                 keys_manager,
4519                 fee_estimator: &fee_estimator,
4520                 chain_monitor: nodes[0].chain_monitor,
4521                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4522                 logger: &logger,
4523                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4524         }) { } else {
4525                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4526         };
4527
4528         let mut nodes_0_read = &nodes_0_serialized[..];
4529         let (_, nodes_0_deserialized_tmp) =
4530                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4531                 default_config: UserConfig::default(),
4532                 keys_manager,
4533                 fee_estimator: &fee_estimator,
4534                 chain_monitor: nodes[0].chain_monitor,
4535                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4536                 logger: &logger,
4537                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4538         }).unwrap();
4539         nodes_0_deserialized = nodes_0_deserialized_tmp;
4540         assert!(nodes_0_read.is_empty());
4541
4542         { // Channel close should result in a commitment tx
4543                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4544                 assert_eq!(txn.len(), 1);
4545                 check_spends!(txn[0], funding_tx);
4546                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4547         }
4548
4549         for monitor in node_0_monitors.drain(..) {
4550                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4551                 check_added_monitors!(nodes[0], 1);
4552         }
4553         nodes[0].node = &nodes_0_deserialized;
4554         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4555
4556         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4557         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4558         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4559         //... and we can even still claim the payment!
4560         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4561
4562         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4563         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4564         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4565         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4566         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4567         assert_eq!(msg_events.len(), 1);
4568         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4569                 match action {
4570                         &ErrorAction::SendErrorMessage { ref msg } => {
4571                                 assert_eq!(msg.channel_id, channel_id);
4572                         },
4573                         _ => panic!("Unexpected event!"),
4574                 }
4575         }
4576 }
4577
4578 macro_rules! check_spendable_outputs {
4579         ($node: expr, $keysinterface: expr) => {
4580                 {
4581                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4582                         let mut txn = Vec::new();
4583                         let mut all_outputs = Vec::new();
4584                         let secp_ctx = Secp256k1::new();
4585                         for event in events.drain(..) {
4586                                 match event {
4587                                         Event::SpendableOutputs { mut outputs } => {
4588                                                 for outp in outputs.drain(..) {
4589                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4590                                                         all_outputs.push(outp);
4591                                                 }
4592                                         },
4593                                         _ => panic!("Unexpected event"),
4594                                 };
4595                         }
4596                         if all_outputs.len() > 1 {
4597                                 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) {
4598                                         txn.push(tx);
4599                                 }
4600                         }
4601                         txn
4602                 }
4603         }
4604 }
4605
4606 #[test]
4607 fn test_claim_sizeable_push_msat() {
4608         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4609         let chanmon_cfgs = create_chanmon_cfgs(2);
4610         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4611         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4612         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4613
4614         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4615         nodes[1].node.force_close_channel(&chan.2).unwrap();
4616         check_closed_broadcast!(nodes[1], true);
4617         check_added_monitors!(nodes[1], 1);
4618         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4619         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4620         assert_eq!(node_txn.len(), 1);
4621         check_spends!(node_txn[0], chan.3);
4622         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
4623
4624         mine_transaction(&nodes[1], &node_txn[0]);
4625         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4626
4627         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4628         assert_eq!(spend_txn.len(), 1);
4629         assert_eq!(spend_txn[0].input.len(), 1);
4630         check_spends!(spend_txn[0], node_txn[0]);
4631         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4632 }
4633
4634 #[test]
4635 fn test_claim_on_remote_sizeable_push_msat() {
4636         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4637         // to_remote output is encumbered by a P2WPKH
4638         let chanmon_cfgs = create_chanmon_cfgs(2);
4639         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4640         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4641         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4642
4643         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4644         nodes[0].node.force_close_channel(&chan.2).unwrap();
4645         check_closed_broadcast!(nodes[0], true);
4646         check_added_monitors!(nodes[0], 1);
4647         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4648
4649         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4650         assert_eq!(node_txn.len(), 1);
4651         check_spends!(node_txn[0], chan.3);
4652         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
4653
4654         mine_transaction(&nodes[1], &node_txn[0]);
4655         check_closed_broadcast!(nodes[1], true);
4656         check_added_monitors!(nodes[1], 1);
4657         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4658         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4659
4660         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4661         assert_eq!(spend_txn.len(), 1);
4662         check_spends!(spend_txn[0], node_txn[0]);
4663 }
4664
4665 #[test]
4666 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4667         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4668         // to_remote output is encumbered by a P2WPKH
4669
4670         let chanmon_cfgs = create_chanmon_cfgs(2);
4671         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4672         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4673         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4674
4675         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4676         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4677         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4678         assert_eq!(revoked_local_txn[0].input.len(), 1);
4679         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4680
4681         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4682         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4683         check_closed_broadcast!(nodes[1], true);
4684         check_added_monitors!(nodes[1], 1);
4685         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4686
4687         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4688         mine_transaction(&nodes[1], &node_txn[0]);
4689         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4690
4691         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4692         assert_eq!(spend_txn.len(), 3);
4693         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4694         check_spends!(spend_txn[1], node_txn[0]);
4695         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4696 }
4697
4698 #[test]
4699 fn test_static_spendable_outputs_preimage_tx() {
4700         let chanmon_cfgs = create_chanmon_cfgs(2);
4701         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4702         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4703         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4704
4705         // Create some initial channels
4706         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4707
4708         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4709
4710         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4711         assert_eq!(commitment_tx[0].input.len(), 1);
4712         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4713
4714         // Settle A's commitment tx on B's chain
4715         assert!(nodes[1].node.claim_funds(payment_preimage));
4716         check_added_monitors!(nodes[1], 1);
4717         mine_transaction(&nodes[1], &commitment_tx[0]);
4718         check_added_monitors!(nodes[1], 1);
4719         let events = nodes[1].node.get_and_clear_pending_msg_events();
4720         match events[0] {
4721                 MessageSendEvent::UpdateHTLCs { .. } => {},
4722                 _ => panic!("Unexpected event"),
4723         }
4724         match events[1] {
4725                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4726                 _ => panic!("Unexepected event"),
4727         }
4728
4729         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4730         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4731         assert_eq!(node_txn.len(), 3);
4732         check_spends!(node_txn[0], commitment_tx[0]);
4733         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4734         check_spends!(node_txn[1], chan_1.3);
4735         check_spends!(node_txn[2], node_txn[1]);
4736
4737         mine_transaction(&nodes[1], &node_txn[0]);
4738         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4739         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4740
4741         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4742         assert_eq!(spend_txn.len(), 1);
4743         check_spends!(spend_txn[0], node_txn[0]);
4744 }
4745
4746 #[test]
4747 fn test_static_spendable_outputs_timeout_tx() {
4748         let chanmon_cfgs = create_chanmon_cfgs(2);
4749         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4750         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4751         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4752
4753         // Create some initial channels
4754         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4755
4756         // Rebalance the network a bit by relaying one payment through all the channels ...
4757         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4758
4759         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4760
4761         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4762         assert_eq!(commitment_tx[0].input.len(), 1);
4763         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4764
4765         // Settle A's commitment tx on B' chain
4766         mine_transaction(&nodes[1], &commitment_tx[0]);
4767         check_added_monitors!(nodes[1], 1);
4768         let events = nodes[1].node.get_and_clear_pending_msg_events();
4769         match events[0] {
4770                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4771                 _ => panic!("Unexpected event"),
4772         }
4773         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4774
4775         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4776         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4777         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4778         check_spends!(node_txn[0], chan_1.3.clone());
4779         check_spends!(node_txn[1],  commitment_tx[0].clone());
4780         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4781
4782         mine_transaction(&nodes[1], &node_txn[1]);
4783         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4784         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4785         expect_payment_failed!(nodes[1], our_payment_hash, true);
4786
4787         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4788         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4789         check_spends!(spend_txn[0], commitment_tx[0]);
4790         check_spends!(spend_txn[1], node_txn[1]);
4791         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4792 }
4793
4794 #[test]
4795 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4796         let chanmon_cfgs = create_chanmon_cfgs(2);
4797         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4798         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4799         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4800
4801         // Create some initial channels
4802         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4803
4804         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4805         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4806         assert_eq!(revoked_local_txn[0].input.len(), 1);
4807         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4808
4809         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4810
4811         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4812         check_closed_broadcast!(nodes[1], true);
4813         check_added_monitors!(nodes[1], 1);
4814         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4815
4816         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4817         assert_eq!(node_txn.len(), 2);
4818         assert_eq!(node_txn[0].input.len(), 2);
4819         check_spends!(node_txn[0], revoked_local_txn[0]);
4820
4821         mine_transaction(&nodes[1], &node_txn[0]);
4822         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4823
4824         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4825         assert_eq!(spend_txn.len(), 1);
4826         check_spends!(spend_txn[0], node_txn[0]);
4827 }
4828
4829 #[test]
4830 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4831         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4832         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4833         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4834         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4835         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4836
4837         // Create some initial channels
4838         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4839
4840         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4841         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4842         assert_eq!(revoked_local_txn[0].input.len(), 1);
4843         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4844
4845         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4846
4847         // A will generate HTLC-Timeout from revoked commitment tx
4848         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4849         check_closed_broadcast!(nodes[0], true);
4850         check_added_monitors!(nodes[0], 1);
4851         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4852         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4853
4854         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4855         assert_eq!(revoked_htlc_txn.len(), 2);
4856         check_spends!(revoked_htlc_txn[0], chan_1.3);
4857         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4858         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4859         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4860         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4861
4862         // B will generate justice tx from A's revoked commitment/HTLC tx
4863         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4864         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4865         check_closed_broadcast!(nodes[1], true);
4866         check_added_monitors!(nodes[1], 1);
4867         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4868
4869         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4870         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4871         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4872         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4873         // transactions next...
4874         assert_eq!(node_txn[0].input.len(), 3);
4875         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4876
4877         assert_eq!(node_txn[1].input.len(), 2);
4878         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4879         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4880                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4881         } else {
4882                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4883                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4884         }
4885
4886         assert_eq!(node_txn[2].input.len(), 1);
4887         check_spends!(node_txn[2], chan_1.3);
4888
4889         mine_transaction(&nodes[1], &node_txn[1]);
4890         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4891
4892         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4893         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4894         assert_eq!(spend_txn.len(), 1);
4895         assert_eq!(spend_txn[0].input.len(), 1);
4896         check_spends!(spend_txn[0], node_txn[1]);
4897 }
4898
4899 #[test]
4900 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4901         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4902         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4903         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4904         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4905         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4906
4907         // Create some initial channels
4908         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4909
4910         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4911         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4912         assert_eq!(revoked_local_txn[0].input.len(), 1);
4913         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4914
4915         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4916         assert_eq!(revoked_local_txn[0].output.len(), 2);
4917
4918         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4919
4920         // B will generate HTLC-Success from revoked commitment tx
4921         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4922         check_closed_broadcast!(nodes[1], true);
4923         check_added_monitors!(nodes[1], 1);
4924         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4925         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4926
4927         assert_eq!(revoked_htlc_txn.len(), 2);
4928         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4929         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4930         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4931
4932         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4933         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4934         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4935
4936         // A will generate justice tx from B's revoked commitment/HTLC tx
4937         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4938         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4939         check_closed_broadcast!(nodes[0], true);
4940         check_added_monitors!(nodes[0], 1);
4941         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4942
4943         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4944         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4945
4946         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4947         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4948         // transactions next...
4949         assert_eq!(node_txn[0].input.len(), 2);
4950         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4951         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4952                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4953         } else {
4954                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4955                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4956         }
4957
4958         assert_eq!(node_txn[1].input.len(), 1);
4959         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4960
4961         check_spends!(node_txn[2], chan_1.3);
4962
4963         mine_transaction(&nodes[0], &node_txn[1]);
4964         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4965
4966         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4967         // didn't try to generate any new transactions.
4968
4969         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4970         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4971         assert_eq!(spend_txn.len(), 3);
4972         assert_eq!(spend_txn[0].input.len(), 1);
4973         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4974         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4975         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4976         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4977 }
4978
4979 #[test]
4980 fn test_onchain_to_onchain_claim() {
4981         // Test that in case of channel closure, we detect the state of output and claim HTLC
4982         // on downstream peer's remote commitment tx.
4983         // First, have C claim an HTLC against its own latest commitment transaction.
4984         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4985         // channel.
4986         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4987         // gets broadcast.
4988
4989         let chanmon_cfgs = create_chanmon_cfgs(3);
4990         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4991         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4992         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4993
4994         // Create some initial channels
4995         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4996         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4997
4998         // Ensure all nodes are at the same height
4999         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5000         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5001         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5002         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5003
5004         // Rebalance the network a bit by relaying one payment through all the channels ...
5005         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5006         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5007
5008         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5009         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5010         check_spends!(commitment_tx[0], chan_2.3);
5011         nodes[2].node.claim_funds(payment_preimage);
5012         check_added_monitors!(nodes[2], 1);
5013         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5014         assert!(updates.update_add_htlcs.is_empty());
5015         assert!(updates.update_fail_htlcs.is_empty());
5016         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5017         assert!(updates.update_fail_malformed_htlcs.is_empty());
5018
5019         mine_transaction(&nodes[2], &commitment_tx[0]);
5020         check_closed_broadcast!(nodes[2], true);
5021         check_added_monitors!(nodes[2], 1);
5022         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5023
5024         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5025         assert_eq!(c_txn.len(), 3);
5026         assert_eq!(c_txn[0], c_txn[2]);
5027         assert_eq!(commitment_tx[0], c_txn[1]);
5028         check_spends!(c_txn[1], chan_2.3);
5029         check_spends!(c_txn[2], c_txn[1]);
5030         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5031         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5032         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5033         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5034
5035         // 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
5036         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5037         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5038         check_added_monitors!(nodes[1], 1);
5039         let events = nodes[1].node.get_and_clear_pending_events();
5040         assert_eq!(events.len(), 2);
5041         match events[0] {
5042                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5043                 _ => panic!("Unexpected event"),
5044         }
5045         match events[1] {
5046                 Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
5047                         assert_eq!(fee_earned_msat, Some(1000));
5048                         assert_eq!(claim_from_onchain_tx, true);
5049                 },
5050                 _ => panic!("Unexpected event"),
5051         }
5052         {
5053                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5054                 // ChannelMonitor: claim tx
5055                 assert_eq!(b_txn.len(), 1);
5056                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5057                 b_txn.clear();
5058         }
5059         check_added_monitors!(nodes[1], 1);
5060         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5061         assert_eq!(msg_events.len(), 3);
5062         match msg_events[0] {
5063                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5064                 _ => panic!("Unexpected event"),
5065         }
5066         match msg_events[1] {
5067                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5068                 _ => panic!("Unexpected event"),
5069         }
5070         match msg_events[2] {
5071                 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, .. } } => {
5072                         assert!(update_add_htlcs.is_empty());
5073                         assert!(update_fail_htlcs.is_empty());
5074                         assert_eq!(update_fulfill_htlcs.len(), 1);
5075                         assert!(update_fail_malformed_htlcs.is_empty());
5076                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5077                 },
5078                 _ => panic!("Unexpected event"),
5079         };
5080         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5081         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5082         mine_transaction(&nodes[1], &commitment_tx[0]);
5083         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5084         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5085         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5086         assert_eq!(b_txn.len(), 3);
5087         check_spends!(b_txn[1], chan_1.3);
5088         check_spends!(b_txn[2], b_txn[1]);
5089         check_spends!(b_txn[0], commitment_tx[0]);
5090         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5091         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5092         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5093
5094         check_closed_broadcast!(nodes[1], true);
5095         check_added_monitors!(nodes[1], 1);
5096 }
5097
5098 #[test]
5099 fn test_duplicate_payment_hash_one_failure_one_success() {
5100         // Topology : A --> B --> C --> D
5101         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5102         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5103         // we forward one of the payments onwards to D.
5104         let chanmon_cfgs = create_chanmon_cfgs(4);
5105         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5106         // When this test was written, the default base fee floated based on the HTLC count.
5107         // It is now fixed, so we simply set the fee to the expected value here.
5108         let mut config = test_default_channel_config();
5109         config.channel_options.forwarding_fee_base_msat = 196;
5110         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5111                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5112         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5113
5114         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5115         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5116         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5117
5118         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5119         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5120         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5121         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5122         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5123
5124         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5125
5126         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, 0).unwrap();
5127         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5128         // script push size limit so that the below script length checks match
5129         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5130         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], vec![], 900000, TEST_FINAL_CLTV - 40);
5131         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5132
5133         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5134         assert_eq!(commitment_txn[0].input.len(), 1);
5135         check_spends!(commitment_txn[0], chan_2.3);
5136
5137         mine_transaction(&nodes[1], &commitment_txn[0]);
5138         check_closed_broadcast!(nodes[1], true);
5139         check_added_monitors!(nodes[1], 1);
5140         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5141         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5142
5143         let htlc_timeout_tx;
5144         { // Extract one of the two HTLC-Timeout transaction
5145                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5146                 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5147                 assert_eq!(node_txn.len(), 4);
5148                 check_spends!(node_txn[0], chan_2.3);
5149
5150                 check_spends!(node_txn[1], commitment_txn[0]);
5151                 assert_eq!(node_txn[1].input.len(), 1);
5152                 check_spends!(node_txn[2], commitment_txn[0]);
5153                 assert_eq!(node_txn[2].input.len(), 1);
5154                 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5155                 check_spends!(node_txn[3], commitment_txn[0]);
5156                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5157
5158                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5159                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5160                 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5161                 htlc_timeout_tx = node_txn[1].clone();
5162         }
5163
5164         nodes[2].node.claim_funds(our_payment_preimage);
5165         mine_transaction(&nodes[2], &commitment_txn[0]);
5166         check_added_monitors!(nodes[2], 2);
5167         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5168         let events = nodes[2].node.get_and_clear_pending_msg_events();
5169         match events[0] {
5170                 MessageSendEvent::UpdateHTLCs { .. } => {},
5171                 _ => panic!("Unexpected event"),
5172         }
5173         match events[1] {
5174                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5175                 _ => panic!("Unexepected event"),
5176         }
5177         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5178         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)
5179         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5180         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5181         assert_eq!(htlc_success_txn[0].input.len(), 1);
5182         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5183         assert_eq!(htlc_success_txn[1].input.len(), 1);
5184         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5185         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5186         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5187         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5188         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5189         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5190
5191         mine_transaction(&nodes[1], &htlc_timeout_tx);
5192         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5193         expect_pending_htlcs_forwardable!(nodes[1]);
5194         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5195         assert!(htlc_updates.update_add_htlcs.is_empty());
5196         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5197         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5198         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5199         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5200         check_added_monitors!(nodes[1], 1);
5201
5202         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5203         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5204         {
5205                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5206         }
5207         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5208
5209         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5210         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5211         // and nodes[2] fee) is rounded down and then claimed in full.
5212         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5213         expect_payment_forwarded!(nodes[1], Some(196*2), true);
5214         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5215         assert!(updates.update_add_htlcs.is_empty());
5216         assert!(updates.update_fail_htlcs.is_empty());
5217         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5218         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5219         assert!(updates.update_fail_malformed_htlcs.is_empty());
5220         check_added_monitors!(nodes[1], 1);
5221
5222         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5223         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5224
5225         let events = nodes[0].node.get_and_clear_pending_events();
5226         match events[0] {
5227                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
5228                         assert_eq!(*payment_preimage, our_payment_preimage);
5229                         assert_eq!(*payment_hash, duplicate_payment_hash);
5230                 }
5231                 _ => panic!("Unexpected event"),
5232         }
5233 }
5234
5235 #[test]
5236 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5237         let chanmon_cfgs = create_chanmon_cfgs(2);
5238         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5239         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5240         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5241
5242         // Create some initial channels
5243         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5244
5245         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5246         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5247         assert_eq!(local_txn.len(), 1);
5248         assert_eq!(local_txn[0].input.len(), 1);
5249         check_spends!(local_txn[0], chan_1.3);
5250
5251         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5252         nodes[1].node.claim_funds(payment_preimage);
5253         check_added_monitors!(nodes[1], 1);
5254         mine_transaction(&nodes[1], &local_txn[0]);
5255         check_added_monitors!(nodes[1], 1);
5256         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5257         let events = nodes[1].node.get_and_clear_pending_msg_events();
5258         match events[0] {
5259                 MessageSendEvent::UpdateHTLCs { .. } => {},
5260                 _ => panic!("Unexpected event"),
5261         }
5262         match events[1] {
5263                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5264                 _ => panic!("Unexepected event"),
5265         }
5266         let node_tx = {
5267                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5268                 assert_eq!(node_txn.len(), 3);
5269                 assert_eq!(node_txn[0], node_txn[2]);
5270                 assert_eq!(node_txn[1], local_txn[0]);
5271                 assert_eq!(node_txn[0].input.len(), 1);
5272                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5273                 check_spends!(node_txn[0], local_txn[0]);
5274                 node_txn[0].clone()
5275         };
5276
5277         mine_transaction(&nodes[1], &node_tx);
5278         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5279
5280         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5281         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5282         assert_eq!(spend_txn.len(), 1);
5283         assert_eq!(spend_txn[0].input.len(), 1);
5284         check_spends!(spend_txn[0], node_tx);
5285         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5286 }
5287
5288 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5289         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5290         // unrevoked commitment transaction.
5291         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5292         // a remote RAA before they could be failed backwards (and combinations thereof).
5293         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5294         // use the same payment hashes.
5295         // Thus, we use a six-node network:
5296         //
5297         // A \         / E
5298         //    - C - D -
5299         // B /         \ F
5300         // And test where C fails back to A/B when D announces its latest commitment transaction
5301         let chanmon_cfgs = create_chanmon_cfgs(6);
5302         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5303         // When this test was written, the default base fee floated based on the HTLC count.
5304         // It is now fixed, so we simply set the fee to the expected value here.
5305         let mut config = test_default_channel_config();
5306         config.channel_options.forwarding_fee_base_msat = 196;
5307         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5308                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5309         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5310
5311         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5312         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5313         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5314         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5315         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5316
5317         // Rebalance and check output sanity...
5318         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5319         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5320         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5321
5322         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5323         // 0th HTLC:
5324         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
5325         // 1st HTLC:
5326         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
5327         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5328         // 2nd HTLC:
5329         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
5330         // 3rd HTLC:
5331         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
5332         // 4th HTLC:
5333         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5334         // 5th HTLC:
5335         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5336         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5337         // 6th HTLC:
5338         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());
5339         // 7th HTLC:
5340         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());
5341
5342         // 8th HTLC:
5343         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5344         // 9th HTLC:
5345         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5346         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
5347
5348         // 10th HTLC:
5349         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
5350         // 11th HTLC:
5351         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5352         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());
5353
5354         // Double-check that six of the new HTLC were added
5355         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5356         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5357         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5358         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5359
5360         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5361         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5362         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5363         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5364         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5365         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5366         check_added_monitors!(nodes[4], 0);
5367         expect_pending_htlcs_forwardable!(nodes[4]);
5368         check_added_monitors!(nodes[4], 1);
5369
5370         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5371         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5372         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5373         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5374         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5375         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5376
5377         // Fail 3rd below-dust and 7th above-dust HTLCs
5378         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5379         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5380         check_added_monitors!(nodes[5], 0);
5381         expect_pending_htlcs_forwardable!(nodes[5]);
5382         check_added_monitors!(nodes[5], 1);
5383
5384         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5385         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5386         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5387         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5388
5389         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5390
5391         expect_pending_htlcs_forwardable!(nodes[3]);
5392         check_added_monitors!(nodes[3], 1);
5393         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5394         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5395         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5396         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5397         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5398         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5399         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5400         if deliver_last_raa {
5401                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5402         } else {
5403                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5404         }
5405
5406         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5407         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5408         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5409         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5410         //
5411         // We now broadcast the latest commitment transaction, which *should* result in failures for
5412         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5413         // the non-broadcast above-dust HTLCs.
5414         //
5415         // Alternatively, we may broadcast the previous commitment transaction, which should only
5416         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5417         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5418
5419         if announce_latest {
5420                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5421         } else {
5422                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5423         }
5424         let events = nodes[2].node.get_and_clear_pending_events();
5425         let close_event = if deliver_last_raa {
5426                 assert_eq!(events.len(), 2);
5427                 events[1].clone()
5428         } else {
5429                 assert_eq!(events.len(), 1);
5430                 events[0].clone()
5431         };
5432         match close_event {
5433                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5434                 _ => panic!("Unexpected event"),
5435         }
5436
5437         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5438         check_closed_broadcast!(nodes[2], true);
5439         if deliver_last_raa {
5440                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5441         } else {
5442                 expect_pending_htlcs_forwardable!(nodes[2]);
5443         }
5444         check_added_monitors!(nodes[2], 3);
5445
5446         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5447         assert_eq!(cs_msgs.len(), 2);
5448         let mut a_done = false;
5449         for msg in cs_msgs {
5450                 match msg {
5451                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5452                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5453                                 // should be failed-backwards here.
5454                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5455                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5456                                         for htlc in &updates.update_fail_htlcs {
5457                                                 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 });
5458                                         }
5459                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5460                                         assert!(!a_done);
5461                                         a_done = true;
5462                                         &nodes[0]
5463                                 } else {
5464                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5465                                         for htlc in &updates.update_fail_htlcs {
5466                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5467                                         }
5468                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5469                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5470                                         &nodes[1]
5471                                 };
5472                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5473                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5474                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5475                                 if announce_latest {
5476                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5477                                         if *node_id == nodes[0].node.get_our_node_id() {
5478                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5479                                         }
5480                                 }
5481                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5482                         },
5483                         _ => panic!("Unexpected event"),
5484                 }
5485         }
5486
5487         let as_events = nodes[0].node.get_and_clear_pending_events();
5488         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5489         let mut as_failds = HashSet::new();
5490         let mut as_updates = 0;
5491         for event in as_events.iter() {
5492                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5493                         assert!(as_failds.insert(*payment_hash));
5494                         if *payment_hash != payment_hash_2 {
5495                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5496                         } else {
5497                                 assert!(!rejected_by_dest);
5498                         }
5499                         if network_update.is_some() {
5500                                 as_updates += 1;
5501                         }
5502                 } else { panic!("Unexpected event"); }
5503         }
5504         assert!(as_failds.contains(&payment_hash_1));
5505         assert!(as_failds.contains(&payment_hash_2));
5506         if announce_latest {
5507                 assert!(as_failds.contains(&payment_hash_3));
5508                 assert!(as_failds.contains(&payment_hash_5));
5509         }
5510         assert!(as_failds.contains(&payment_hash_6));
5511
5512         let bs_events = nodes[1].node.get_and_clear_pending_events();
5513         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5514         let mut bs_failds = HashSet::new();
5515         let mut bs_updates = 0;
5516         for event in bs_events.iter() {
5517                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5518                         assert!(bs_failds.insert(*payment_hash));
5519                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5520                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5521                         } else {
5522                                 assert!(!rejected_by_dest);
5523                         }
5524                         if network_update.is_some() {
5525                                 bs_updates += 1;
5526                         }
5527                 } else { panic!("Unexpected event"); }
5528         }
5529         assert!(bs_failds.contains(&payment_hash_1));
5530         assert!(bs_failds.contains(&payment_hash_2));
5531         if announce_latest {
5532                 assert!(bs_failds.contains(&payment_hash_4));
5533         }
5534         assert!(bs_failds.contains(&payment_hash_5));
5535
5536         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5537         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5538         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5539         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5540         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5541         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5542 }
5543
5544 #[test]
5545 fn test_fail_backwards_latest_remote_announce_a() {
5546         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5547 }
5548
5549 #[test]
5550 fn test_fail_backwards_latest_remote_announce_b() {
5551         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5552 }
5553
5554 #[test]
5555 fn test_fail_backwards_previous_remote_announce() {
5556         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5557         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5558         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5559 }
5560
5561 #[test]
5562 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5563         let chanmon_cfgs = create_chanmon_cfgs(2);
5564         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5565         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5566         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5567
5568         // Create some initial channels
5569         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5570
5571         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5572         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5573         assert_eq!(local_txn[0].input.len(), 1);
5574         check_spends!(local_txn[0], chan_1.3);
5575
5576         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5577         mine_transaction(&nodes[0], &local_txn[0]);
5578         check_closed_broadcast!(nodes[0], true);
5579         check_added_monitors!(nodes[0], 1);
5580         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5581         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5582
5583         let htlc_timeout = {
5584                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5585                 assert_eq!(node_txn.len(), 2);
5586                 check_spends!(node_txn[0], chan_1.3);
5587                 assert_eq!(node_txn[1].input.len(), 1);
5588                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5589                 check_spends!(node_txn[1], local_txn[0]);
5590                 node_txn[1].clone()
5591         };
5592
5593         mine_transaction(&nodes[0], &htlc_timeout);
5594         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5595         expect_payment_failed!(nodes[0], our_payment_hash, true);
5596
5597         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5598         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5599         assert_eq!(spend_txn.len(), 3);
5600         check_spends!(spend_txn[0], local_txn[0]);
5601         assert_eq!(spend_txn[1].input.len(), 1);
5602         check_spends!(spend_txn[1], htlc_timeout);
5603         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5604         assert_eq!(spend_txn[2].input.len(), 2);
5605         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5606         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5607                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5608 }
5609
5610 #[test]
5611 fn test_key_derivation_params() {
5612         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5613         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5614         // let us re-derive the channel key set to then derive a delayed_payment_key.
5615
5616         let chanmon_cfgs = create_chanmon_cfgs(3);
5617
5618         // We manually create the node configuration to backup the seed.
5619         let seed = [42; 32];
5620         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5621         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);
5622         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() };
5623         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5624         node_cfgs.remove(0);
5625         node_cfgs.insert(0, node);
5626
5627         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5628         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5629
5630         // Create some initial channels
5631         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5632         // for node 0
5633         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5634         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5635         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5636
5637         // Ensure all nodes are at the same height
5638         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5639         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5640         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5641         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5642
5643         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5644         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5645         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5646         assert_eq!(local_txn_1[0].input.len(), 1);
5647         check_spends!(local_txn_1[0], chan_1.3);
5648
5649         // We check funding pubkey are unique
5650         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]));
5651         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]));
5652         if from_0_funding_key_0 == from_1_funding_key_0
5653             || from_0_funding_key_0 == from_1_funding_key_1
5654             || from_0_funding_key_1 == from_1_funding_key_0
5655             || from_0_funding_key_1 == from_1_funding_key_1 {
5656                 panic!("Funding pubkeys aren't unique");
5657         }
5658
5659         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5660         mine_transaction(&nodes[0], &local_txn_1[0]);
5661         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5662         check_closed_broadcast!(nodes[0], true);
5663         check_added_monitors!(nodes[0], 1);
5664         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5665
5666         let htlc_timeout = {
5667                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5668                 assert_eq!(node_txn[1].input.len(), 1);
5669                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5670                 check_spends!(node_txn[1], local_txn_1[0]);
5671                 node_txn[1].clone()
5672         };
5673
5674         mine_transaction(&nodes[0], &htlc_timeout);
5675         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5676         expect_payment_failed!(nodes[0], our_payment_hash, true);
5677
5678         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5679         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5680         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5681         assert_eq!(spend_txn.len(), 3);
5682         check_spends!(spend_txn[0], local_txn_1[0]);
5683         assert_eq!(spend_txn[1].input.len(), 1);
5684         check_spends!(spend_txn[1], htlc_timeout);
5685         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5686         assert_eq!(spend_txn[2].input.len(), 2);
5687         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5688         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5689                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5690 }
5691
5692 #[test]
5693 fn test_static_output_closing_tx() {
5694         let chanmon_cfgs = create_chanmon_cfgs(2);
5695         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5696         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5697         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5698
5699         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5700
5701         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5702         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5703
5704         mine_transaction(&nodes[0], &closing_tx);
5705         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5706         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5707
5708         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5709         assert_eq!(spend_txn.len(), 1);
5710         check_spends!(spend_txn[0], closing_tx);
5711
5712         mine_transaction(&nodes[1], &closing_tx);
5713         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5714         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5715
5716         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5717         assert_eq!(spend_txn.len(), 1);
5718         check_spends!(spend_txn[0], closing_tx);
5719 }
5720
5721 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5722         let chanmon_cfgs = create_chanmon_cfgs(2);
5723         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5724         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5725         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5726         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5727
5728         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5729
5730         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5731         // present in B's local commitment transaction, but none of A's commitment transactions.
5732         assert!(nodes[1].node.claim_funds(our_payment_preimage));
5733         check_added_monitors!(nodes[1], 1);
5734
5735         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5736         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5737         let events = nodes[0].node.get_and_clear_pending_events();
5738         assert_eq!(events.len(), 1);
5739         match events[0] {
5740                 Event::PaymentSent { payment_preimage, payment_hash } => {
5741                         assert_eq!(payment_preimage, our_payment_preimage);
5742                         assert_eq!(payment_hash, our_payment_hash);
5743                 },
5744                 _ => panic!("Unexpected event"),
5745         }
5746
5747         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5748         check_added_monitors!(nodes[0], 1);
5749         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5750         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5751         check_added_monitors!(nodes[1], 1);
5752
5753         let starting_block = nodes[1].best_block_info();
5754         let mut block = Block {
5755                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5756                 txdata: vec![],
5757         };
5758         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5759                 connect_block(&nodes[1], &block);
5760                 block.header.prev_blockhash = block.block_hash();
5761         }
5762         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5763         check_closed_broadcast!(nodes[1], true);
5764         check_added_monitors!(nodes[1], 1);
5765         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5766 }
5767
5768 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5769         let chanmon_cfgs = create_chanmon_cfgs(2);
5770         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5771         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5772         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5773         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5774
5775         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5776         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5777         check_added_monitors!(nodes[0], 1);
5778
5779         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5780
5781         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5782         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5783         // to "time out" the HTLC.
5784
5785         let starting_block = nodes[1].best_block_info();
5786         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5787
5788         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5789                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5790                 header.prev_blockhash = header.block_hash();
5791         }
5792         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5793         check_closed_broadcast!(nodes[0], true);
5794         check_added_monitors!(nodes[0], 1);
5795         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5796 }
5797
5798 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5799         let chanmon_cfgs = create_chanmon_cfgs(3);
5800         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5801         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5802         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5803         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5804
5805         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5806         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5807         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5808         // actually revoked.
5809         let htlc_value = if use_dust { 50000 } else { 3000000 };
5810         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5811         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5812         expect_pending_htlcs_forwardable!(nodes[1]);
5813         check_added_monitors!(nodes[1], 1);
5814
5815         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5816         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5817         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5818         check_added_monitors!(nodes[0], 1);
5819         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5820         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5821         check_added_monitors!(nodes[1], 1);
5822         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5823         check_added_monitors!(nodes[1], 1);
5824         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5825
5826         if check_revoke_no_close {
5827                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5828                 check_added_monitors!(nodes[0], 1);
5829         }
5830
5831         let starting_block = nodes[1].best_block_info();
5832         let mut block = Block {
5833                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5834                 txdata: vec![],
5835         };
5836         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5837                 connect_block(&nodes[0], &block);
5838                 block.header.prev_blockhash = block.block_hash();
5839         }
5840         if !check_revoke_no_close {
5841                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5842                 check_closed_broadcast!(nodes[0], true);
5843                 check_added_monitors!(nodes[0], 1);
5844                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5845         } else {
5846                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5847         }
5848 }
5849
5850 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5851 // There are only a few cases to test here:
5852 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5853 //    broadcastable commitment transactions result in channel closure,
5854 //  * its included in an unrevoked-but-previous remote commitment transaction,
5855 //  * its included in the latest remote or local commitment transactions.
5856 // We test each of the three possible commitment transactions individually and use both dust and
5857 // non-dust HTLCs.
5858 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5859 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5860 // tested for at least one of the cases in other tests.
5861 #[test]
5862 fn htlc_claim_single_commitment_only_a() {
5863         do_htlc_claim_local_commitment_only(true);
5864         do_htlc_claim_local_commitment_only(false);
5865
5866         do_htlc_claim_current_remote_commitment_only(true);
5867         do_htlc_claim_current_remote_commitment_only(false);
5868 }
5869
5870 #[test]
5871 fn htlc_claim_single_commitment_only_b() {
5872         do_htlc_claim_previous_remote_commitment_only(true, false);
5873         do_htlc_claim_previous_remote_commitment_only(false, false);
5874         do_htlc_claim_previous_remote_commitment_only(true, true);
5875         do_htlc_claim_previous_remote_commitment_only(false, true);
5876 }
5877
5878 #[test]
5879 #[should_panic]
5880 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5881         let chanmon_cfgs = create_chanmon_cfgs(2);
5882         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5883         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5884         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5885         //Force duplicate channel ids
5886         for node in nodes.iter() {
5887                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5888         }
5889
5890         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5891         let channel_value_satoshis=10000;
5892         let push_msat=10001;
5893         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5894         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5895         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5896
5897         //Create a second channel with a channel_id collision
5898         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5899 }
5900
5901 #[test]
5902 fn bolt2_open_channel_sending_node_checks_part2() {
5903         let chanmon_cfgs = create_chanmon_cfgs(2);
5904         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5905         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5906         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5907
5908         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5909         let channel_value_satoshis=2^24;
5910         let push_msat=10001;
5911         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5912
5913         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5914         let channel_value_satoshis=10000;
5915         // Test when push_msat is equal to 1000 * funding_satoshis.
5916         let push_msat=1000*channel_value_satoshis+1;
5917         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5918
5919         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5920         let channel_value_satoshis=10000;
5921         let push_msat=10001;
5922         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
5923         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5924         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5925
5926         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5927         // 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
5928         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5929
5930         // 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.
5931         assert!(BREAKDOWN_TIMEOUT>0);
5932         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5933
5934         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5935         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5936         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5937
5938         // 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.
5939         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5940         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5941         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5942         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5943         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5944 }
5945
5946 #[test]
5947 fn bolt2_open_channel_sane_dust_limit() {
5948         let chanmon_cfgs = create_chanmon_cfgs(2);
5949         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5950         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5951         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5952
5953         let channel_value_satoshis=1000000;
5954         let push_msat=10001;
5955         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5956         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5957         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5958         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5959
5960         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5961         let events = nodes[1].node.get_and_clear_pending_msg_events();
5962         let err_msg = match events[0] {
5963                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5964                         msg.clone()
5965                 },
5966                 _ => panic!("Unexpected event"),
5967         };
5968         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5969 }
5970
5971 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5972 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5973 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5974 // is no longer affordable once it's freed.
5975 #[test]
5976 fn test_fail_holding_cell_htlc_upon_free() {
5977         let chanmon_cfgs = create_chanmon_cfgs(2);
5978         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5979         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5980         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5981         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5982
5983         // First nodes[0] generates an update_fee, setting the channel's
5984         // pending_update_fee.
5985         {
5986                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5987                 *feerate_lock += 20;
5988         }
5989         nodes[0].node.timer_tick_occurred();
5990         check_added_monitors!(nodes[0], 1);
5991
5992         let events = nodes[0].node.get_and_clear_pending_msg_events();
5993         assert_eq!(events.len(), 1);
5994         let (update_msg, commitment_signed) = match events[0] {
5995                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5996                         (update_fee.as_ref(), commitment_signed)
5997                 },
5998                 _ => panic!("Unexpected event"),
5999         };
6000
6001         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6002
6003         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6004         let channel_reserve = chan_stat.channel_reserve_msat;
6005         let feerate = get_feerate!(nodes[0], chan.2);
6006
6007         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6008         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6009         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6010
6011         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6012         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6013         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6014         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6015
6016         // Flush the pending fee update.
6017         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6018         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6019         check_added_monitors!(nodes[1], 1);
6020         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6021         check_added_monitors!(nodes[0], 1);
6022
6023         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6024         // HTLC, but now that the fee has been raised the payment will now fail, causing
6025         // us to surface its failure to the user.
6026         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6027         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6028         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);
6029         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 {}",
6030                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6031         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6032
6033         // Check that the payment failed to be sent out.
6034         let events = nodes[0].node.get_and_clear_pending_events();
6035         assert_eq!(events.len(), 1);
6036         match &events[0] {
6037                 &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, path: _, ref short_channel_id, ref error_code, ref error_data } => {
6038                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6039                         assert_eq!(*rejected_by_dest, false);
6040                         assert_eq!(*all_paths_failed, true);
6041                         assert_eq!(*network_update, None);
6042                         assert_eq!(*short_channel_id, None);
6043                         assert_eq!(*error_code, None);
6044                         assert_eq!(*error_data, None);
6045                 },
6046                 _ => panic!("Unexpected event"),
6047         }
6048 }
6049
6050 // Test that if multiple HTLCs are released from the holding cell and one is
6051 // valid but the other is no longer valid upon release, the valid HTLC can be
6052 // successfully completed while the other one fails as expected.
6053 #[test]
6054 fn test_free_and_fail_holding_cell_htlcs() {
6055         let chanmon_cfgs = create_chanmon_cfgs(2);
6056         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6057         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6058         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6059         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6060
6061         // First nodes[0] generates an update_fee, setting the channel's
6062         // pending_update_fee.
6063         {
6064                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6065                 *feerate_lock += 200;
6066         }
6067         nodes[0].node.timer_tick_occurred();
6068         check_added_monitors!(nodes[0], 1);
6069
6070         let events = nodes[0].node.get_and_clear_pending_msg_events();
6071         assert_eq!(events.len(), 1);
6072         let (update_msg, commitment_signed) = match events[0] {
6073                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6074                         (update_fee.as_ref(), commitment_signed)
6075                 },
6076                 _ => panic!("Unexpected event"),
6077         };
6078
6079         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6080
6081         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6082         let channel_reserve = chan_stat.channel_reserve_msat;
6083         let feerate = get_feerate!(nodes[0], chan.2);
6084
6085         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6086         let amt_1 = 20000;
6087         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6088         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6089         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6090
6091         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6092         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6093         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6094         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6095         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6096         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6097         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6098
6099         // Flush the pending fee update.
6100         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6101         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6102         check_added_monitors!(nodes[1], 1);
6103         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6104         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6105         check_added_monitors!(nodes[0], 2);
6106
6107         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6108         // but now that the fee has been raised the second payment will now fail, causing us
6109         // to surface its failure to the user. The first payment should succeed.
6110         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6111         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6112         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);
6113         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 {}",
6114                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6115         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6116
6117         // Check that the second payment failed to be sent out.
6118         let events = nodes[0].node.get_and_clear_pending_events();
6119         assert_eq!(events.len(), 1);
6120         match &events[0] {
6121                 &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, path: _, ref short_channel_id, ref error_code, ref error_data } => {
6122                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6123                         assert_eq!(*rejected_by_dest, false);
6124                         assert_eq!(*all_paths_failed, true);
6125                         assert_eq!(*network_update, None);
6126                         assert_eq!(*short_channel_id, None);
6127                         assert_eq!(*error_code, None);
6128                         assert_eq!(*error_data, None);
6129                 },
6130                 _ => panic!("Unexpected event"),
6131         }
6132
6133         // Complete the first payment and the RAA from the fee update.
6134         let (payment_event, send_raa_event) = {
6135                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6136                 assert_eq!(msgs.len(), 2);
6137                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6138         };
6139         let raa = match send_raa_event {
6140                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6141                 _ => panic!("Unexpected event"),
6142         };
6143         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6144         check_added_monitors!(nodes[1], 1);
6145         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6146         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6147         let events = nodes[1].node.get_and_clear_pending_events();
6148         assert_eq!(events.len(), 1);
6149         match events[0] {
6150                 Event::PendingHTLCsForwardable { .. } => {},
6151                 _ => panic!("Unexpected event"),
6152         }
6153         nodes[1].node.process_pending_htlc_forwards();
6154         let events = nodes[1].node.get_and_clear_pending_events();
6155         assert_eq!(events.len(), 1);
6156         match events[0] {
6157                 Event::PaymentReceived { .. } => {},
6158                 _ => panic!("Unexpected event"),
6159         }
6160         nodes[1].node.claim_funds(payment_preimage_1);
6161         check_added_monitors!(nodes[1], 1);
6162         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6163         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6164         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6165         let events = nodes[0].node.get_and_clear_pending_events();
6166         assert_eq!(events.len(), 1);
6167         match events[0] {
6168                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
6169                         assert_eq!(*payment_preimage, payment_preimage_1);
6170                         assert_eq!(*payment_hash, payment_hash_1);
6171                 }
6172                 _ => panic!("Unexpected event"),
6173         }
6174 }
6175
6176 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6177 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6178 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6179 // once it's freed.
6180 #[test]
6181 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6182         let chanmon_cfgs = create_chanmon_cfgs(3);
6183         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6184         // When this test was written, the default base fee floated based on the HTLC count.
6185         // It is now fixed, so we simply set the fee to the expected value here.
6186         let mut config = test_default_channel_config();
6187         config.channel_options.forwarding_fee_base_msat = 196;
6188         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6189         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6190         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6191         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6192
6193         // First nodes[1] generates an update_fee, setting the channel's
6194         // pending_update_fee.
6195         {
6196                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6197                 *feerate_lock += 20;
6198         }
6199         nodes[1].node.timer_tick_occurred();
6200         check_added_monitors!(nodes[1], 1);
6201
6202         let events = nodes[1].node.get_and_clear_pending_msg_events();
6203         assert_eq!(events.len(), 1);
6204         let (update_msg, commitment_signed) = match events[0] {
6205                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6206                         (update_fee.as_ref(), commitment_signed)
6207                 },
6208                 _ => panic!("Unexpected event"),
6209         };
6210
6211         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6212
6213         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6214         let channel_reserve = chan_stat.channel_reserve_msat;
6215         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6216
6217         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6218         let feemsat = 239;
6219         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6220         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6221         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6222         let payment_event = {
6223                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6224                 check_added_monitors!(nodes[0], 1);
6225
6226                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6227                 assert_eq!(events.len(), 1);
6228
6229                 SendEvent::from_event(events.remove(0))
6230         };
6231         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6232         check_added_monitors!(nodes[1], 0);
6233         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6234         expect_pending_htlcs_forwardable!(nodes[1]);
6235
6236         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6237         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6238
6239         // Flush the pending fee update.
6240         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6241         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6242         check_added_monitors!(nodes[2], 1);
6243         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6244         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6245         check_added_monitors!(nodes[1], 2);
6246
6247         // A final RAA message is generated to finalize the fee update.
6248         let events = nodes[1].node.get_and_clear_pending_msg_events();
6249         assert_eq!(events.len(), 1);
6250
6251         let raa_msg = match &events[0] {
6252                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6253                         msg.clone()
6254                 },
6255                 _ => panic!("Unexpected event"),
6256         };
6257
6258         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6259         check_added_monitors!(nodes[2], 1);
6260         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6261
6262         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6263         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6264         assert_eq!(process_htlc_forwards_event.len(), 1);
6265         match &process_htlc_forwards_event[0] {
6266                 &Event::PendingHTLCsForwardable { .. } => {},
6267                 _ => panic!("Unexpected event"),
6268         }
6269
6270         // In response, we call ChannelManager's process_pending_htlc_forwards
6271         nodes[1].node.process_pending_htlc_forwards();
6272         check_added_monitors!(nodes[1], 1);
6273
6274         // This causes the HTLC to be failed backwards.
6275         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6276         assert_eq!(fail_event.len(), 1);
6277         let (fail_msg, commitment_signed) = match &fail_event[0] {
6278                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6279                         assert_eq!(updates.update_add_htlcs.len(), 0);
6280                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6281                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6282                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6283                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6284                 },
6285                 _ => panic!("Unexpected event"),
6286         };
6287
6288         // Pass the failure messages back to nodes[0].
6289         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6290         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6291
6292         // Complete the HTLC failure+removal process.
6293         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6294         check_added_monitors!(nodes[0], 1);
6295         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6296         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6297         check_added_monitors!(nodes[1], 2);
6298         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6299         assert_eq!(final_raa_event.len(), 1);
6300         let raa = match &final_raa_event[0] {
6301                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6302                 _ => panic!("Unexpected event"),
6303         };
6304         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6305         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6306         check_added_monitors!(nodes[0], 1);
6307 }
6308
6309 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6310 // 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.
6311 //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.
6312
6313 #[test]
6314 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6315         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6316         let chanmon_cfgs = create_chanmon_cfgs(2);
6317         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6318         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6319         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6320         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6321
6322         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6323         route.paths[0][0].fee_msat = 100;
6324
6325         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6326                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6327         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6328         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6329 }
6330
6331 #[test]
6332 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6333         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6334         let chanmon_cfgs = create_chanmon_cfgs(2);
6335         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6336         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6337         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6338         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6339
6340         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6341         route.paths[0][0].fee_msat = 0;
6342         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6343                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6344
6345         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6346         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6347 }
6348
6349 #[test]
6350 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6351         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6352         let chanmon_cfgs = create_chanmon_cfgs(2);
6353         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6354         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6355         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6356         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6357
6358         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6359         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6360         check_added_monitors!(nodes[0], 1);
6361         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6362         updates.update_add_htlcs[0].amount_msat = 0;
6363
6364         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6365         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6366         check_closed_broadcast!(nodes[1], true).unwrap();
6367         check_added_monitors!(nodes[1], 1);
6368         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6369 }
6370
6371 #[test]
6372 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6373         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6374         //It is enforced when constructing a route.
6375         let chanmon_cfgs = create_chanmon_cfgs(2);
6376         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6377         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6378         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6379         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6380
6381         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], vec![], 100000000, 500000001);
6382         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6383                 assert_eq!(err, &"Channel CLTV overflowed?"));
6384 }
6385
6386 #[test]
6387 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6388         //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.
6389         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6390         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6391         let chanmon_cfgs = create_chanmon_cfgs(2);
6392         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6393         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6394         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6395         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6396         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6397
6398         for i in 0..max_accepted_htlcs {
6399                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6400                 let payment_event = {
6401                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6402                         check_added_monitors!(nodes[0], 1);
6403
6404                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6405                         assert_eq!(events.len(), 1);
6406                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6407                                 assert_eq!(htlcs[0].htlc_id, i);
6408                         } else {
6409                                 assert!(false);
6410                         }
6411                         SendEvent::from_event(events.remove(0))
6412                 };
6413                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6414                 check_added_monitors!(nodes[1], 0);
6415                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6416
6417                 expect_pending_htlcs_forwardable!(nodes[1]);
6418                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6419         }
6420         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6421         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6422                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6423
6424         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6425         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6426 }
6427
6428 #[test]
6429 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6430         //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.
6431         let chanmon_cfgs = create_chanmon_cfgs(2);
6432         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6433         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6434         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6435         let channel_value = 100000;
6436         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6437         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6438
6439         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6440
6441         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6442         // Manually create a route over our max in flight (which our router normally automatically
6443         // limits us to.
6444         route.paths[0][0].fee_msat =  max_in_flight + 1;
6445         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6446                 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)));
6447
6448         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6449         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);
6450
6451         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6452 }
6453
6454 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6455 #[test]
6456 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6457         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6458         let chanmon_cfgs = create_chanmon_cfgs(2);
6459         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6460         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6461         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6462         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6463         let htlc_minimum_msat: u64;
6464         {
6465                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6466                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6467                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6468         }
6469
6470         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6471         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6472         check_added_monitors!(nodes[0], 1);
6473         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6474         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6475         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6476         assert!(nodes[1].node.list_channels().is_empty());
6477         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6478         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()));
6479         check_added_monitors!(nodes[1], 1);
6480         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6481 }
6482
6483 #[test]
6484 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6485         //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
6486         let chanmon_cfgs = create_chanmon_cfgs(2);
6487         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6488         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6489         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6490         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6491
6492         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6493         let channel_reserve = chan_stat.channel_reserve_msat;
6494         let feerate = get_feerate!(nodes[0], chan.2);
6495         // The 2* and +1 are for the fee spike reserve.
6496         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6497
6498         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6499         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6500         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6501         check_added_monitors!(nodes[0], 1);
6502         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6503
6504         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6505         // at this time channel-initiatee receivers are not required to enforce that senders
6506         // respect the fee_spike_reserve.
6507         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6508         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6509
6510         assert!(nodes[1].node.list_channels().is_empty());
6511         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6512         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6513         check_added_monitors!(nodes[1], 1);
6514         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6515 }
6516
6517 #[test]
6518 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6519         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6520         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6521         let chanmon_cfgs = create_chanmon_cfgs(2);
6522         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6523         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6524         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6525         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6526
6527         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6528         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6529         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6530         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6531         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6532         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6533
6534         let mut msg = msgs::UpdateAddHTLC {
6535                 channel_id: chan.2,
6536                 htlc_id: 0,
6537                 amount_msat: 1000,
6538                 payment_hash: our_payment_hash,
6539                 cltv_expiry: htlc_cltv,
6540                 onion_routing_packet: onion_packet.clone(),
6541         };
6542
6543         for i in 0..super::channel::OUR_MAX_HTLCS {
6544                 msg.htlc_id = i as u64;
6545                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6546         }
6547         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6548         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6549
6550         assert!(nodes[1].node.list_channels().is_empty());
6551         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6552         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6553         check_added_monitors!(nodes[1], 1);
6554         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6555 }
6556
6557 #[test]
6558 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6559         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6560         let chanmon_cfgs = create_chanmon_cfgs(2);
6561         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6562         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6563         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6564         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6565
6566         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6567         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6568         check_added_monitors!(nodes[0], 1);
6569         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6570         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6571         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6572
6573         assert!(nodes[1].node.list_channels().is_empty());
6574         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6575         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6576         check_added_monitors!(nodes[1], 1);
6577         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6578 }
6579
6580 #[test]
6581 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6582         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6583         let chanmon_cfgs = create_chanmon_cfgs(2);
6584         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6585         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6586         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6587
6588         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6589         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6590         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6591         check_added_monitors!(nodes[0], 1);
6592         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6593         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6594         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6595
6596         assert!(nodes[1].node.list_channels().is_empty());
6597         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6598         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6599         check_added_monitors!(nodes[1], 1);
6600         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6601 }
6602
6603 #[test]
6604 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6605         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6606         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6607         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6608         let chanmon_cfgs = create_chanmon_cfgs(2);
6609         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6610         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6611         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6612
6613         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6614         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6615         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6616         check_added_monitors!(nodes[0], 1);
6617         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6618         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6619
6620         //Disconnect and Reconnect
6621         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6622         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6623         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6624         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6625         assert_eq!(reestablish_1.len(), 1);
6626         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6627         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6628         assert_eq!(reestablish_2.len(), 1);
6629         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6630         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6631         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6632         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6633
6634         //Resend HTLC
6635         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6636         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6637         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6638         check_added_monitors!(nodes[1], 1);
6639         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6640
6641         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6642
6643         assert!(nodes[1].node.list_channels().is_empty());
6644         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6645         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6646         check_added_monitors!(nodes[1], 1);
6647         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6648 }
6649
6650 #[test]
6651 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6652         //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.
6653
6654         let chanmon_cfgs = create_chanmon_cfgs(2);
6655         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6656         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6657         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6658         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6659         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6660         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6661
6662         check_added_monitors!(nodes[0], 1);
6663         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6664         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6665
6666         let update_msg = msgs::UpdateFulfillHTLC{
6667                 channel_id: chan.2,
6668                 htlc_id: 0,
6669                 payment_preimage: our_payment_preimage,
6670         };
6671
6672         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6673
6674         assert!(nodes[0].node.list_channels().is_empty());
6675         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6676         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()));
6677         check_added_monitors!(nodes[0], 1);
6678         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6679 }
6680
6681 #[test]
6682 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6683         //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.
6684
6685         let chanmon_cfgs = create_chanmon_cfgs(2);
6686         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6687         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6688         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6689         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6690
6691         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6692         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6693         check_added_monitors!(nodes[0], 1);
6694         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6695         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6696
6697         let update_msg = msgs::UpdateFailHTLC{
6698                 channel_id: chan.2,
6699                 htlc_id: 0,
6700                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6701         };
6702
6703         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6704
6705         assert!(nodes[0].node.list_channels().is_empty());
6706         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6707         assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6708         check_added_monitors!(nodes[0], 1);
6709         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6710 }
6711
6712 #[test]
6713 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6714         //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.
6715
6716         let chanmon_cfgs = create_chanmon_cfgs(2);
6717         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6718         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6719         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6720         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6721
6722         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6723         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6724         check_added_monitors!(nodes[0], 1);
6725         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6726         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6727         let update_msg = msgs::UpdateFailMalformedHTLC{
6728                 channel_id: chan.2,
6729                 htlc_id: 0,
6730                 sha256_of_onion: [1; 32],
6731                 failure_code: 0x8000,
6732         };
6733
6734         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6735
6736         assert!(nodes[0].node.list_channels().is_empty());
6737         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6738         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()));
6739         check_added_monitors!(nodes[0], 1);
6740         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6741 }
6742
6743 #[test]
6744 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6745         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6746
6747         let chanmon_cfgs = create_chanmon_cfgs(2);
6748         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6749         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6750         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6751         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6752
6753         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6754
6755         nodes[1].node.claim_funds(our_payment_preimage);
6756         check_added_monitors!(nodes[1], 1);
6757
6758         let events = nodes[1].node.get_and_clear_pending_msg_events();
6759         assert_eq!(events.len(), 1);
6760         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6761                 match events[0] {
6762                         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, .. } } => {
6763                                 assert!(update_add_htlcs.is_empty());
6764                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6765                                 assert!(update_fail_htlcs.is_empty());
6766                                 assert!(update_fail_malformed_htlcs.is_empty());
6767                                 assert!(update_fee.is_none());
6768                                 update_fulfill_htlcs[0].clone()
6769                         },
6770                         _ => panic!("Unexpected event"),
6771                 }
6772         };
6773
6774         update_fulfill_msg.htlc_id = 1;
6775
6776         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6777
6778         assert!(nodes[0].node.list_channels().is_empty());
6779         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6780         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6781         check_added_monitors!(nodes[0], 1);
6782         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6783 }
6784
6785 #[test]
6786 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6787         //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.
6788
6789         let chanmon_cfgs = create_chanmon_cfgs(2);
6790         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6791         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6792         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6793         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6794
6795         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6796
6797         nodes[1].node.claim_funds(our_payment_preimage);
6798         check_added_monitors!(nodes[1], 1);
6799
6800         let events = nodes[1].node.get_and_clear_pending_msg_events();
6801         assert_eq!(events.len(), 1);
6802         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6803                 match events[0] {
6804                         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, .. } } => {
6805                                 assert!(update_add_htlcs.is_empty());
6806                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6807                                 assert!(update_fail_htlcs.is_empty());
6808                                 assert!(update_fail_malformed_htlcs.is_empty());
6809                                 assert!(update_fee.is_none());
6810                                 update_fulfill_htlcs[0].clone()
6811                         },
6812                         _ => panic!("Unexpected event"),
6813                 }
6814         };
6815
6816         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6817
6818         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6819
6820         assert!(nodes[0].node.list_channels().is_empty());
6821         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6822         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6823         check_added_monitors!(nodes[0], 1);
6824         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6825 }
6826
6827 #[test]
6828 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6829         //BOLT 2 Requirement: A receiving node: if the BADONION bit in failure_code is not set for update_fail_malformed_htlc MUST fail the channel.
6830
6831         let chanmon_cfgs = create_chanmon_cfgs(2);
6832         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6833         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6834         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6835         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6836
6837         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6838         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6839         check_added_monitors!(nodes[0], 1);
6840
6841         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6842         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6843
6844         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6845         check_added_monitors!(nodes[1], 0);
6846         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6847
6848         let events = nodes[1].node.get_and_clear_pending_msg_events();
6849
6850         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6851                 match events[0] {
6852                         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, .. } } => {
6853                                 assert!(update_add_htlcs.is_empty());
6854                                 assert!(update_fulfill_htlcs.is_empty());
6855                                 assert!(update_fail_htlcs.is_empty());
6856                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6857                                 assert!(update_fee.is_none());
6858                                 update_fail_malformed_htlcs[0].clone()
6859                         },
6860                         _ => panic!("Unexpected event"),
6861                 }
6862         };
6863         update_msg.failure_code &= !0x8000;
6864         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6865
6866         assert!(nodes[0].node.list_channels().is_empty());
6867         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6868         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6869         check_added_monitors!(nodes[0], 1);
6870         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6871 }
6872
6873 #[test]
6874 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6875         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6876         //    * 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.
6877
6878         let chanmon_cfgs = create_chanmon_cfgs(3);
6879         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6880         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6881         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6882         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6883         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6884
6885         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6886
6887         //First hop
6888         let mut payment_event = {
6889                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6890                 check_added_monitors!(nodes[0], 1);
6891                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6892                 assert_eq!(events.len(), 1);
6893                 SendEvent::from_event(events.remove(0))
6894         };
6895         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6896         check_added_monitors!(nodes[1], 0);
6897         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6898         expect_pending_htlcs_forwardable!(nodes[1]);
6899         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6900         assert_eq!(events_2.len(), 1);
6901         check_added_monitors!(nodes[1], 1);
6902         payment_event = SendEvent::from_event(events_2.remove(0));
6903         assert_eq!(payment_event.msgs.len(), 1);
6904
6905         //Second Hop
6906         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6907         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6908         check_added_monitors!(nodes[2], 0);
6909         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6910
6911         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6912         assert_eq!(events_3.len(), 1);
6913         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6914                 match events_3[0] {
6915                         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 } } => {
6916                                 assert!(update_add_htlcs.is_empty());
6917                                 assert!(update_fulfill_htlcs.is_empty());
6918                                 assert!(update_fail_htlcs.is_empty());
6919                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6920                                 assert!(update_fee.is_none());
6921                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6922                         },
6923                         _ => panic!("Unexpected event"),
6924                 }
6925         };
6926
6927         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6928
6929         check_added_monitors!(nodes[1], 0);
6930         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6931         expect_pending_htlcs_forwardable!(nodes[1]);
6932         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6933         assert_eq!(events_4.len(), 1);
6934
6935         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6936         match events_4[0] {
6937                 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, .. } } => {
6938                         assert!(update_add_htlcs.is_empty());
6939                         assert!(update_fulfill_htlcs.is_empty());
6940                         assert_eq!(update_fail_htlcs.len(), 1);
6941                         assert!(update_fail_malformed_htlcs.is_empty());
6942                         assert!(update_fee.is_none());
6943                 },
6944                 _ => panic!("Unexpected event"),
6945         };
6946
6947         check_added_monitors!(nodes[1], 1);
6948 }
6949
6950 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6951         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6952         // 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
6953         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6954
6955         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6956         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6957         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6958         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6959         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6960         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6961
6962         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6963
6964         // We route 2 dust-HTLCs between A and B
6965         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6966         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6967         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6968
6969         // Cache one local commitment tx as previous
6970         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6971
6972         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6973         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
6974         check_added_monitors!(nodes[1], 0);
6975         expect_pending_htlcs_forwardable!(nodes[1]);
6976         check_added_monitors!(nodes[1], 1);
6977
6978         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6979         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6980         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6981         check_added_monitors!(nodes[0], 1);
6982
6983         // Cache one local commitment tx as lastest
6984         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6985
6986         let events = nodes[0].node.get_and_clear_pending_msg_events();
6987         match events[0] {
6988                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6989                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6990                 },
6991                 _ => panic!("Unexpected event"),
6992         }
6993         match events[1] {
6994                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6995                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6996                 },
6997                 _ => panic!("Unexpected event"),
6998         }
6999
7000         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7001         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7002         if announce_latest {
7003                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7004         } else {
7005                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7006         }
7007
7008         check_closed_broadcast!(nodes[0], true);
7009         check_added_monitors!(nodes[0], 1);
7010         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7011
7012         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7013         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7014         let events = nodes[0].node.get_and_clear_pending_events();
7015         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7016         assert_eq!(events.len(), 2);
7017         let mut first_failed = false;
7018         for event in events {
7019                 match event {
7020                         Event::PaymentPathFailed { payment_hash, .. } => {
7021                                 if payment_hash == payment_hash_1 {
7022                                         assert!(!first_failed);
7023                                         first_failed = true;
7024                                 } else {
7025                                         assert_eq!(payment_hash, payment_hash_2);
7026                                 }
7027                         }
7028                         _ => panic!("Unexpected event"),
7029                 }
7030         }
7031 }
7032
7033 #[test]
7034 fn test_failure_delay_dust_htlc_local_commitment() {
7035         do_test_failure_delay_dust_htlc_local_commitment(true);
7036         do_test_failure_delay_dust_htlc_local_commitment(false);
7037 }
7038
7039 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7040         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7041         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7042         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7043         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7044         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7045         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7046
7047         let chanmon_cfgs = create_chanmon_cfgs(3);
7048         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7049         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7050         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7051         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7052
7053         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7054
7055         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7056         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7057
7058         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7059         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7060
7061         // We revoked bs_commitment_tx
7062         if revoked {
7063                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7064                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7065         }
7066
7067         let mut timeout_tx = Vec::new();
7068         if local {
7069                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7070                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7071                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7072                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7073                 expect_payment_failed!(nodes[0], dust_hash, true);
7074
7075                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7076                 check_closed_broadcast!(nodes[0], true);
7077                 check_added_monitors!(nodes[0], 1);
7078                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7079                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7080                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7081                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7082                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7083                 mine_transaction(&nodes[0], &timeout_tx[0]);
7084                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7085                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7086         } else {
7087                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7088                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7089                 check_closed_broadcast!(nodes[0], true);
7090                 check_added_monitors!(nodes[0], 1);
7091                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7092                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7093                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7094                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7095                 if !revoked {
7096                         expect_payment_failed!(nodes[0], dust_hash, true);
7097                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7098                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7099                         mine_transaction(&nodes[0], &timeout_tx[0]);
7100                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7101                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7102                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7103                 } else {
7104                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7105                         // commitment tx
7106                         let events = nodes[0].node.get_and_clear_pending_events();
7107                         assert_eq!(events.len(), 2);
7108                         let first;
7109                         match events[0] {
7110                                 Event::PaymentPathFailed { payment_hash, .. } => {
7111                                         if payment_hash == dust_hash { first = true; }
7112                                         else { first = false; }
7113                                 },
7114                                 _ => panic!("Unexpected event"),
7115                         }
7116                         match events[1] {
7117                                 Event::PaymentPathFailed { payment_hash, .. } => {
7118                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7119                                         else { assert_eq!(payment_hash, dust_hash); }
7120                                 },
7121                                 _ => panic!("Unexpected event"),
7122                         }
7123                 }
7124         }
7125 }
7126
7127 #[test]
7128 fn test_sweep_outbound_htlc_failure_update() {
7129         do_test_sweep_outbound_htlc_failure_update(false, true);
7130         do_test_sweep_outbound_htlc_failure_update(false, false);
7131         do_test_sweep_outbound_htlc_failure_update(true, false);
7132 }
7133
7134 #[test]
7135 fn test_user_configurable_csv_delay() {
7136         // We test our channel constructors yield errors when we pass them absurd csv delay
7137
7138         let mut low_our_to_self_config = UserConfig::default();
7139         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7140         let mut high_their_to_self_config = UserConfig::default();
7141         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7142         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7143         let chanmon_cfgs = create_chanmon_cfgs(2);
7144         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7145         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7146         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7147
7148         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7149         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) {
7150                 match error {
7151                         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())); },
7152                         _ => panic!("Unexpected event"),
7153                 }
7154         } else { assert!(false) }
7155
7156         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7157         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7158         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7159         open_channel.to_self_delay = 200;
7160         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) {
7161                 match error {
7162                         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()));  },
7163                         _ => panic!("Unexpected event"),
7164                 }
7165         } else { assert!(false); }
7166
7167         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7168         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7169         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()));
7170         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7171         accept_channel.to_self_delay = 200;
7172         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7173         let reason_msg;
7174         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7175                 match action {
7176                         &ErrorAction::SendErrorMessage { ref msg } => {
7177                                 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()));
7178                                 reason_msg = msg.data.clone();
7179                         },
7180                         _ => { panic!(); }
7181                 }
7182         } else { panic!(); }
7183         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7184
7185         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7186         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7187         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7188         open_channel.to_self_delay = 200;
7189         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) {
7190                 match error {
7191                         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())); },
7192                         _ => panic!("Unexpected event"),
7193                 }
7194         } else { assert!(false); }
7195 }
7196
7197 #[test]
7198 fn test_data_loss_protect() {
7199         // We want to be sure that :
7200         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7201         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7202         // * we close channel in case of detecting other being fallen behind
7203         // * we are able to claim our own outputs thanks to to_remote being static
7204         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7205         let persister;
7206         let logger;
7207         let fee_estimator;
7208         let tx_broadcaster;
7209         let chain_source;
7210         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7211         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7212         // during signing due to revoked tx
7213         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7214         let keys_manager = &chanmon_cfgs[0].keys_manager;
7215         let monitor;
7216         let node_state_0;
7217         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7218         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7219         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7220
7221         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7222
7223         // Cache node A state before any channel update
7224         let previous_node_state = nodes[0].node.encode();
7225         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7226         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7227
7228         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7229         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7230
7231         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7232         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7233
7234         // Restore node A from previous state
7235         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7236         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7237         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7238         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7239         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7240         persister = test_utils::TestPersister::new();
7241         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7242         node_state_0 = {
7243                 let mut channel_monitors = HashMap::new();
7244                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7245                 <(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 {
7246                         keys_manager: keys_manager,
7247                         fee_estimator: &fee_estimator,
7248                         chain_monitor: &monitor,
7249                         logger: &logger,
7250                         tx_broadcaster: &tx_broadcaster,
7251                         default_config: UserConfig::default(),
7252                         channel_monitors,
7253                 }).unwrap().1
7254         };
7255         nodes[0].node = &node_state_0;
7256         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7257         nodes[0].chain_monitor = &monitor;
7258         nodes[0].chain_source = &chain_source;
7259
7260         check_added_monitors!(nodes[0], 1);
7261
7262         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7263         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7264
7265         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7266
7267         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7268         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7269         check_added_monitors!(nodes[0], 1);
7270
7271         {
7272                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7273                 assert_eq!(node_txn.len(), 0);
7274         }
7275
7276         let mut reestablish_1 = Vec::with_capacity(1);
7277         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7278                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7279                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7280                         reestablish_1.push(msg.clone());
7281                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7282                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7283                         match action {
7284                                 &ErrorAction::SendErrorMessage { ref msg } => {
7285                                         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");
7286                                 },
7287                                 _ => panic!("Unexpected event!"),
7288                         }
7289                 } else {
7290                         panic!("Unexpected event")
7291                 }
7292         }
7293
7294         // Check we close channel detecting A is fallen-behind
7295         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7296         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7297         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7298         check_added_monitors!(nodes[1], 1);
7299
7300         // Check A is able to claim to_remote output
7301         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7302         assert_eq!(node_txn.len(), 1);
7303         check_spends!(node_txn[0], chan.3);
7304         assert_eq!(node_txn[0].output.len(), 2);
7305         mine_transaction(&nodes[0], &node_txn[0]);
7306         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7307         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "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".to_string() });
7308         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7309         assert_eq!(spend_txn.len(), 1);
7310         check_spends!(spend_txn[0], node_txn[0]);
7311 }
7312
7313 #[test]
7314 fn test_check_htlc_underpaying() {
7315         // Send payment through A -> B but A is maliciously
7316         // sending a probe payment (i.e less than expected value0
7317         // to B, B should refuse payment.
7318
7319         let chanmon_cfgs = create_chanmon_cfgs(2);
7320         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7321         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7322         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7323
7324         // Create some initial channels
7325         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7326
7327         let scorer = Scorer::new(0);
7328         let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, TEST_FINAL_CLTV, nodes[0].logger, &scorer).unwrap();
7329         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7330         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, 0).unwrap();
7331         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7332         check_added_monitors!(nodes[0], 1);
7333
7334         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7335         assert_eq!(events.len(), 1);
7336         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7337         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7338         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7339
7340         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7341         // and then will wait a second random delay before failing the HTLC back:
7342         expect_pending_htlcs_forwardable!(nodes[1]);
7343         expect_pending_htlcs_forwardable!(nodes[1]);
7344
7345         // Node 3 is expecting payment of 100_000 but received 10_000,
7346         // it should fail htlc like we didn't know the preimage.
7347         nodes[1].node.process_pending_htlc_forwards();
7348
7349         let events = nodes[1].node.get_and_clear_pending_msg_events();
7350         assert_eq!(events.len(), 1);
7351         let (update_fail_htlc, commitment_signed) = match events[0] {
7352                 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 } } => {
7353                         assert!(update_add_htlcs.is_empty());
7354                         assert!(update_fulfill_htlcs.is_empty());
7355                         assert_eq!(update_fail_htlcs.len(), 1);
7356                         assert!(update_fail_malformed_htlcs.is_empty());
7357                         assert!(update_fee.is_none());
7358                         (update_fail_htlcs[0].clone(), commitment_signed)
7359                 },
7360                 _ => panic!("Unexpected event"),
7361         };
7362         check_added_monitors!(nodes[1], 1);
7363
7364         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7365         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7366
7367         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7368         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7369         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7370         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7371 }
7372
7373 #[test]
7374 fn test_announce_disable_channels() {
7375         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7376         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7377
7378         let chanmon_cfgs = create_chanmon_cfgs(2);
7379         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7380         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7381         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7382
7383         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7384         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7385         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7386
7387         // Disconnect peers
7388         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7389         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7390
7391         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7392         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7393         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7394         assert_eq!(msg_events.len(), 3);
7395         let mut chans_disabled: HashSet<u64> = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7396         for e in msg_events {
7397                 match e {
7398                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7399                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7400                                 // Check that each channel gets updated exactly once
7401                                 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7402                                         panic!("Generated ChannelUpdate for wrong chan!");
7403                                 }
7404                         },
7405                         _ => panic!("Unexpected event"),
7406                 }
7407         }
7408         // Reconnect peers
7409         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7410         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7411         assert_eq!(reestablish_1.len(), 3);
7412         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7413         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7414         assert_eq!(reestablish_2.len(), 3);
7415
7416         // Reestablish chan_1
7417         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7418         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7419         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7420         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7421         // Reestablish chan_2
7422         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7423         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7424         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7425         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7426         // Reestablish chan_3
7427         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7428         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7429         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7430         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7431
7432         nodes[0].node.timer_tick_occurred();
7433         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7434         nodes[0].node.timer_tick_occurred();
7435         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7436         assert_eq!(msg_events.len(), 3);
7437         chans_disabled = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7438         for e in msg_events {
7439                 match e {
7440                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7441                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7442                                 // Check that each channel gets updated exactly once
7443                                 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7444                                         panic!("Generated ChannelUpdate for wrong chan!");
7445                                 }
7446                         },
7447                         _ => panic!("Unexpected event"),
7448                 }
7449         }
7450 }
7451
7452 #[test]
7453 fn test_priv_forwarding_rejection() {
7454         // If we have a private channel with outbound liquidity, and
7455         // UserConfig::accept_forwards_to_priv_channels is set to false, we should reject any attempts
7456         // to forward through that channel.
7457         let chanmon_cfgs = create_chanmon_cfgs(3);
7458         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7459         let mut no_announce_cfg = test_default_channel_config();
7460         no_announce_cfg.channel_options.announced_channel = false;
7461         no_announce_cfg.accept_forwards_to_priv_channels = false;
7462         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]);
7463         let persister: test_utils::TestPersister;
7464         let new_chain_monitor: test_utils::TestChainMonitor;
7465         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
7466         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7467
7468         let chan_id_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known()).2;
7469
7470         // Note that the create_*_chan functions in utils requires announcement_signatures, which we do
7471         // not send for private channels.
7472         nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
7473         let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[2].node.get_our_node_id());
7474         nodes[2].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
7475         let accept_channel = get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
7476         nodes[1].node.handle_accept_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7477
7478         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[1], 1_000_000, 42);
7479         nodes[1].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
7480         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()));
7481         check_added_monitors!(nodes[2], 1);
7482
7483         let cs_funding_signed = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[1].node.get_our_node_id());
7484         nodes[1].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &cs_funding_signed);
7485         check_added_monitors!(nodes[1], 1);
7486
7487         let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[2].best_block_info().1 + 1);
7488         confirm_transaction_at(&nodes[1], &tx, conf_height);
7489         connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
7490         confirm_transaction_at(&nodes[2], &tx, conf_height);
7491         connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
7492         let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[2].node.get_our_node_id());
7493         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()));
7494         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7495         nodes[2].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
7496         get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7497
7498         assert!(nodes[0].node.list_usable_channels()[0].is_public);
7499         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
7500         assert!(!nodes[2].node.list_usable_channels()[0].is_public);
7501
7502         // We should always be able to forward through nodes[1] as long as its out through a public
7503         // channel:
7504         send_payment(&nodes[2], &[&nodes[1], &nodes[0]], 10_000);
7505
7506         // ... however, if we send to nodes[2], we will have to pass the private channel from nodes[1]
7507         // to nodes[2], which should be rejected:
7508         let route_hint = RouteHint(vec![RouteHintHop {
7509                 src_node_id: nodes[1].node.get_our_node_id(),
7510                 short_channel_id: nodes[2].node.list_channels()[0].short_channel_id.unwrap(),
7511                 fees: RoutingFees { base_msat: 1000, proportional_millionths: 0 },
7512                 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
7513                 htlc_minimum_msat: None,
7514                 htlc_maximum_msat: None,
7515         }]);
7516         let last_hops = vec![&route_hint];
7517         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], last_hops, 10_000, TEST_FINAL_CLTV);
7518
7519         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7520         check_added_monitors!(nodes[0], 1);
7521         let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7522         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7523         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
7524
7525         let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7526         assert!(htlc_fail_updates.update_add_htlcs.is_empty());
7527         assert_eq!(htlc_fail_updates.update_fail_htlcs.len(), 1);
7528         assert!(htlc_fail_updates.update_fail_malformed_htlcs.is_empty());
7529         assert!(htlc_fail_updates.update_fee.is_none());
7530
7531         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
7532         commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, true, true);
7533         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, nodes[2].node.list_channels()[0].short_channel_id.unwrap(), true);
7534
7535         // Now disconnect nodes[1] from its peers and restart with accept_forwards_to_priv_channels set
7536         // to true. Sadly there is currently no way to change it at runtime.
7537
7538         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7539         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7540
7541         let nodes_1_serialized = nodes[1].node.encode();
7542         let mut monitor_a_serialized = test_utils::TestVecWriter(Vec::new());
7543         let mut monitor_b_serialized = test_utils::TestVecWriter(Vec::new());
7544         get_monitor!(nodes[1], chan_id_1).write(&mut monitor_a_serialized).unwrap();
7545         get_monitor!(nodes[1], cs_funding_signed.channel_id).write(&mut monitor_b_serialized).unwrap();
7546
7547         persister = test_utils::TestPersister::new();
7548         let keys_manager = &chanmon_cfgs[1].keys_manager;
7549         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);
7550         nodes[1].chain_monitor = &new_chain_monitor;
7551
7552         let mut monitor_a_read = &monitor_a_serialized.0[..];
7553         let mut monitor_b_read = &monitor_b_serialized.0[..];
7554         let (_, mut monitor_a) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_a_read, keys_manager).unwrap();
7555         let (_, mut monitor_b) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_b_read, keys_manager).unwrap();
7556         assert!(monitor_a_read.is_empty());
7557         assert!(monitor_b_read.is_empty());
7558
7559         no_announce_cfg.accept_forwards_to_priv_channels = true;
7560
7561         let mut nodes_1_read = &nodes_1_serialized[..];
7562         let (_, nodes_1_deserialized_tmp) = {
7563                 let mut channel_monitors = HashMap::new();
7564                 channel_monitors.insert(monitor_a.get_funding_txo().0, &mut monitor_a);
7565                 channel_monitors.insert(monitor_b.get_funding_txo().0, &mut monitor_b);
7566                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
7567                         default_config: no_announce_cfg,
7568                         keys_manager,
7569                         fee_estimator: node_cfgs[1].fee_estimator,
7570                         chain_monitor: nodes[1].chain_monitor,
7571                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
7572                         logger: nodes[1].logger,
7573                         channel_monitors,
7574                 }).unwrap()
7575         };
7576         assert!(nodes_1_read.is_empty());
7577         nodes_1_deserialized = nodes_1_deserialized_tmp;
7578
7579         assert!(nodes[1].chain_monitor.watch_channel(monitor_a.get_funding_txo().0, monitor_a).is_ok());
7580         assert!(nodes[1].chain_monitor.watch_channel(monitor_b.get_funding_txo().0, monitor_b).is_ok());
7581         check_added_monitors!(nodes[1], 2);
7582         nodes[1].node = &nodes_1_deserialized;
7583
7584         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7585         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7586         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7587         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
7588         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
7589         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7590         get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7591         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
7592
7593         nodes[1].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7594         nodes[2].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7595         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[2].node.get_our_node_id());
7596         let cs_reestablish = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7597         nodes[2].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7598         nodes[1].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &cs_reestablish);
7599         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7600         get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7601
7602         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7603         check_added_monitors!(nodes[0], 1);
7604         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 10_000, our_payment_hash, our_payment_secret);
7605         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage);
7606 }
7607
7608 #[test]
7609 fn test_bump_penalty_txn_on_revoked_commitment() {
7610         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7611         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7612
7613         let chanmon_cfgs = create_chanmon_cfgs(2);
7614         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7615         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7616         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7617
7618         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7619
7620         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7621         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], vec![], 3000000, 30);
7622         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7623
7624         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7625         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7626         assert_eq!(revoked_txn[0].output.len(), 4);
7627         assert_eq!(revoked_txn[0].input.len(), 1);
7628         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7629         let revoked_txid = revoked_txn[0].txid();
7630
7631         let mut penalty_sum = 0;
7632         for outp in revoked_txn[0].output.iter() {
7633                 if outp.script_pubkey.is_v0_p2wsh() {
7634                         penalty_sum += outp.value;
7635                 }
7636         }
7637
7638         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7639         let header_114 = connect_blocks(&nodes[1], 14);
7640
7641         // Actually revoke tx by claiming a HTLC
7642         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7643         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7644         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7645         check_added_monitors!(nodes[1], 1);
7646
7647         // One or more justice tx should have been broadcast, check it
7648         let penalty_1;
7649         let feerate_1;
7650         {
7651                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7652                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7653                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7654                 assert_eq!(node_txn[0].output.len(), 1);
7655                 check_spends!(node_txn[0], revoked_txn[0]);
7656                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7657                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7658                 penalty_1 = node_txn[0].txid();
7659                 node_txn.clear();
7660         };
7661
7662         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7663         connect_blocks(&nodes[1], 15);
7664         let mut penalty_2 = penalty_1;
7665         let mut feerate_2 = 0;
7666         {
7667                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7668                 assert_eq!(node_txn.len(), 1);
7669                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7670                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7671                         assert_eq!(node_txn[0].output.len(), 1);
7672                         check_spends!(node_txn[0], revoked_txn[0]);
7673                         penalty_2 = node_txn[0].txid();
7674                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7675                         assert_ne!(penalty_2, penalty_1);
7676                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7677                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7678                         // Verify 25% bump heuristic
7679                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7680                         node_txn.clear();
7681                 }
7682         }
7683         assert_ne!(feerate_2, 0);
7684
7685         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7686         connect_blocks(&nodes[1], 1);
7687         let penalty_3;
7688         let mut feerate_3 = 0;
7689         {
7690                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7691                 assert_eq!(node_txn.len(), 1);
7692                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7693                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7694                         assert_eq!(node_txn[0].output.len(), 1);
7695                         check_spends!(node_txn[0], revoked_txn[0]);
7696                         penalty_3 = node_txn[0].txid();
7697                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7698                         assert_ne!(penalty_3, penalty_2);
7699                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7700                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7701                         // Verify 25% bump heuristic
7702                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7703                         node_txn.clear();
7704                 }
7705         }
7706         assert_ne!(feerate_3, 0);
7707
7708         nodes[1].node.get_and_clear_pending_events();
7709         nodes[1].node.get_and_clear_pending_msg_events();
7710 }
7711
7712 #[test]
7713 fn test_bump_penalty_txn_on_revoked_htlcs() {
7714         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7715         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7716
7717         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7718         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7719         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7720         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7721         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7722
7723         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7724         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7725         let scorer = Scorer::new(0);
7726         let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph,
7727                 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger, &scorer).unwrap();
7728         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7729         let route = get_route(&nodes[1].node.get_our_node_id(), &nodes[1].net_graph_msg_handler.network_graph,
7730                 &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger, &scorer).unwrap();
7731         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7732
7733         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7734         assert_eq!(revoked_local_txn[0].input.len(), 1);
7735         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7736
7737         // Revoke local commitment tx
7738         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7739
7740         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7741         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7742         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7743         check_closed_broadcast!(nodes[1], true);
7744         check_added_monitors!(nodes[1], 1);
7745         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7746         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7747
7748         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7749         assert_eq!(revoked_htlc_txn.len(), 3);
7750         check_spends!(revoked_htlc_txn[1], chan.3);
7751
7752         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7753         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7754         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7755
7756         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7757         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7758         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7759         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7760
7761         // Broadcast set of revoked txn on A
7762         let hash_128 = connect_blocks(&nodes[0], 40);
7763         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7764         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7765         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7766         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7767         let events = nodes[0].node.get_and_clear_pending_events();
7768         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7769         match events[1] {
7770                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7771                 _ => panic!("Unexpected event"),
7772         }
7773         let first;
7774         let feerate_1;
7775         let penalty_txn;
7776         {
7777                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7778                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7779                 // Verify claim tx are spending revoked HTLC txn
7780
7781                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7782                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7783                 // which are included in the same block (they are broadcasted because we scan the
7784                 // transactions linearly and generate claims as we go, they likely should be removed in the
7785                 // future).
7786                 assert_eq!(node_txn[0].input.len(), 1);
7787                 check_spends!(node_txn[0], revoked_local_txn[0]);
7788                 assert_eq!(node_txn[1].input.len(), 1);
7789                 check_spends!(node_txn[1], revoked_local_txn[0]);
7790                 assert_eq!(node_txn[2].input.len(), 1);
7791                 check_spends!(node_txn[2], revoked_local_txn[0]);
7792
7793                 // Each of the three justice transactions claim a separate (single) output of the three
7794                 // available, which we check here:
7795                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7796                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7797                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7798
7799                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7800                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7801
7802                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7803                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7804                 // a remote commitment tx has already been confirmed).
7805                 check_spends!(node_txn[3], chan.3);
7806
7807                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7808                 // output, checked above).
7809                 assert_eq!(node_txn[4].input.len(), 2);
7810                 assert_eq!(node_txn[4].output.len(), 1);
7811                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7812
7813                 first = node_txn[4].txid();
7814                 // Store both feerates for later comparison
7815                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7816                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7817                 penalty_txn = vec![node_txn[2].clone()];
7818                 node_txn.clear();
7819         }
7820
7821         // Connect one more block to see if bumped penalty are issued for HTLC txn
7822         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7823         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7824         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7825         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7826         {
7827                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7828                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7829
7830                 check_spends!(node_txn[0], revoked_local_txn[0]);
7831                 check_spends!(node_txn[1], revoked_local_txn[0]);
7832                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7833                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7834                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7835                 } else {
7836                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7837                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7838                 }
7839
7840                 node_txn.clear();
7841         };
7842
7843         // Few more blocks to confirm penalty txn
7844         connect_blocks(&nodes[0], 4);
7845         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7846         let header_144 = connect_blocks(&nodes[0], 9);
7847         let node_txn = {
7848                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7849                 assert_eq!(node_txn.len(), 1);
7850
7851                 assert_eq!(node_txn[0].input.len(), 2);
7852                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7853                 // Verify bumped tx is different and 25% bump heuristic
7854                 assert_ne!(first, node_txn[0].txid());
7855                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7856                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7857                 assert!(feerate_2 * 100 > feerate_1 * 125);
7858                 let txn = vec![node_txn[0].clone()];
7859                 node_txn.clear();
7860                 txn
7861         };
7862         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7863         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7864         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7865         connect_blocks(&nodes[0], 20);
7866         {
7867                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7868                 // We verify than no new transaction has been broadcast because previously
7869                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7870                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7871                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7872                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7873                 // up bumped justice generation.
7874                 assert_eq!(node_txn.len(), 0);
7875                 node_txn.clear();
7876         }
7877         check_closed_broadcast!(nodes[0], true);
7878         check_added_monitors!(nodes[0], 1);
7879 }
7880
7881 #[test]
7882 fn test_bump_penalty_txn_on_remote_commitment() {
7883         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7884         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7885
7886         // Create 2 HTLCs
7887         // Provide preimage for one
7888         // Check aggregation
7889
7890         let chanmon_cfgs = create_chanmon_cfgs(2);
7891         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7892         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7893         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7894
7895         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7896         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7897         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7898
7899         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7900         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7901         assert_eq!(remote_txn[0].output.len(), 4);
7902         assert_eq!(remote_txn[0].input.len(), 1);
7903         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7904
7905         // Claim a HTLC without revocation (provide B monitor with preimage)
7906         nodes[1].node.claim_funds(payment_preimage);
7907         mine_transaction(&nodes[1], &remote_txn[0]);
7908         check_added_monitors!(nodes[1], 2);
7909         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7910
7911         // One or more claim tx should have been broadcast, check it
7912         let timeout;
7913         let preimage;
7914         let preimage_bump;
7915         let feerate_timeout;
7916         let feerate_preimage;
7917         {
7918                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7919                 // 9 transactions including:
7920                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7921                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7922                 // 2 * HTLC-Success (one RBF bump we'll check later)
7923                 // 1 * HTLC-Timeout
7924                 assert_eq!(node_txn.len(), 8);
7925                 assert_eq!(node_txn[0].input.len(), 1);
7926                 assert_eq!(node_txn[6].input.len(), 1);
7927                 check_spends!(node_txn[0], remote_txn[0]);
7928                 check_spends!(node_txn[6], remote_txn[0]);
7929                 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7930                 preimage_bump = node_txn[3].clone();
7931
7932                 check_spends!(node_txn[1], chan.3);
7933                 check_spends!(node_txn[2], node_txn[1]);
7934                 assert_eq!(node_txn[1], node_txn[4]);
7935                 assert_eq!(node_txn[2], node_txn[5]);
7936
7937                 timeout = node_txn[6].txid();
7938                 let index = node_txn[6].input[0].previous_output.vout;
7939                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
7940                 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
7941
7942                 preimage = node_txn[0].txid();
7943                 let index = node_txn[0].input[0].previous_output.vout;
7944                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7945                 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7946
7947                 node_txn.clear();
7948         };
7949         assert_ne!(feerate_timeout, 0);
7950         assert_ne!(feerate_preimage, 0);
7951
7952         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7953         connect_blocks(&nodes[1], 15);
7954         {
7955                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7956                 assert_eq!(node_txn.len(), 1);
7957                 assert_eq!(node_txn[0].input.len(), 1);
7958                 assert_eq!(preimage_bump.input.len(), 1);
7959                 check_spends!(node_txn[0], remote_txn[0]);
7960                 check_spends!(preimage_bump, remote_txn[0]);
7961
7962                 let index = preimage_bump.input[0].previous_output.vout;
7963                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7964                 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
7965                 assert!(new_feerate * 100 > feerate_timeout * 125);
7966                 assert_ne!(timeout, preimage_bump.txid());
7967
7968                 let index = node_txn[0].input[0].previous_output.vout;
7969                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7970                 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7971                 assert!(new_feerate * 100 > feerate_preimage * 125);
7972                 assert_ne!(preimage, node_txn[0].txid());
7973
7974                 node_txn.clear();
7975         }
7976
7977         nodes[1].node.get_and_clear_pending_events();
7978         nodes[1].node.get_and_clear_pending_msg_events();
7979 }
7980
7981 #[test]
7982 fn test_counterparty_raa_skip_no_crash() {
7983         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7984         // commitment transaction, we would have happily carried on and provided them the next
7985         // commitment transaction based on one RAA forward. This would probably eventually have led to
7986         // channel closure, but it would not have resulted in funds loss. Still, our
7987         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7988         // check simply that the channel is closed in response to such an RAA, but don't check whether
7989         // we decide to punish our counterparty for revoking their funds (as we don't currently
7990         // implement that).
7991         let chanmon_cfgs = create_chanmon_cfgs(2);
7992         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7993         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7994         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7995         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7996
7997         let mut guard = nodes[0].node.channel_state.lock().unwrap();
7998         let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7999
8000         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8001
8002         // Make signer believe we got a counterparty signature, so that it allows the revocation
8003         keys.get_enforcement_state().last_holder_commitment -= 1;
8004         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8005
8006         // Must revoke without gaps
8007         keys.get_enforcement_state().last_holder_commitment -= 1;
8008         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8009
8010         keys.get_enforcement_state().last_holder_commitment -= 1;
8011         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8012                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8013
8014         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8015                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8016         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8017         check_added_monitors!(nodes[1], 1);
8018         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8019 }
8020
8021 #[test]
8022 fn test_bump_txn_sanitize_tracking_maps() {
8023         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8024         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8025
8026         let chanmon_cfgs = create_chanmon_cfgs(2);
8027         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8028         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8029         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8030
8031         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8032         // Lock HTLC in both directions
8033         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8034         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8035
8036         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8037         assert_eq!(revoked_local_txn[0].input.len(), 1);
8038         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8039
8040         // Revoke local commitment tx
8041         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8042
8043         // Broadcast set of revoked txn on A
8044         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8045         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8046         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8047
8048         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8049         check_closed_broadcast!(nodes[0], true);
8050         check_added_monitors!(nodes[0], 1);
8051         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8052         let penalty_txn = {
8053                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8054                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8055                 check_spends!(node_txn[0], revoked_local_txn[0]);
8056                 check_spends!(node_txn[1], revoked_local_txn[0]);
8057                 check_spends!(node_txn[2], revoked_local_txn[0]);
8058                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8059                 node_txn.clear();
8060                 penalty_txn
8061         };
8062         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8063         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8064         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8065         {
8066                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8067                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8068                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8069         }
8070 }
8071
8072 #[test]
8073 fn test_override_channel_config() {
8074         let chanmon_cfgs = create_chanmon_cfgs(2);
8075         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8076         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8077         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8078
8079         // Node0 initiates a channel to node1 using the override config.
8080         let mut override_config = UserConfig::default();
8081         override_config.own_channel_config.our_to_self_delay = 200;
8082
8083         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8084
8085         // Assert the channel created by node0 is using the override config.
8086         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8087         assert_eq!(res.channel_flags, 0);
8088         assert_eq!(res.to_self_delay, 200);
8089 }
8090
8091 #[test]
8092 fn test_override_0msat_htlc_minimum() {
8093         let mut zero_config = UserConfig::default();
8094         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8095         let chanmon_cfgs = create_chanmon_cfgs(2);
8096         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8097         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8098         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8099
8100         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8101         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8102         assert_eq!(res.htlc_minimum_msat, 1);
8103
8104         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8105         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8106         assert_eq!(res.htlc_minimum_msat, 1);
8107 }
8108
8109 #[test]
8110 fn test_simple_mpp() {
8111         // Simple test of sending a multi-path payment.
8112         let chanmon_cfgs = create_chanmon_cfgs(4);
8113         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8114         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8115         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8116
8117         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8118         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8119         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8120         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8121
8122         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8123         let path = route.paths[0].clone();
8124         route.paths.push(path);
8125         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8126         route.paths[0][0].short_channel_id = chan_1_id;
8127         route.paths[0][1].short_channel_id = chan_3_id;
8128         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8129         route.paths[1][0].short_channel_id = chan_2_id;
8130         route.paths[1][1].short_channel_id = chan_4_id;
8131         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8132         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8133 }
8134
8135 #[test]
8136 fn test_preimage_storage() {
8137         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8138         let chanmon_cfgs = create_chanmon_cfgs(2);
8139         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8140         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8141         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8142
8143         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8144
8145         {
8146                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, 42);
8147                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8148                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8149                 check_added_monitors!(nodes[0], 1);
8150                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8151                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8152                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8153                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8154         }
8155         // Note that after leaving the above scope we have no knowledge of any arguments or return
8156         // values from previous calls.
8157         expect_pending_htlcs_forwardable!(nodes[1]);
8158         let events = nodes[1].node.get_and_clear_pending_events();
8159         assert_eq!(events.len(), 1);
8160         match events[0] {
8161                 Event::PaymentReceived { ref purpose, .. } => {
8162                         match &purpose {
8163                                 PaymentPurpose::InvoicePayment { payment_preimage, user_payment_id, .. } => {
8164                                         assert_eq!(*user_payment_id, 42);
8165                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8166                                 },
8167                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8168                         }
8169                 },
8170                 _ => panic!("Unexpected event"),
8171         }
8172 }
8173
8174 #[test]
8175 fn test_secret_timeout() {
8176         // Simple test of payment secret storage time outs
8177         let chanmon_cfgs = create_chanmon_cfgs(2);
8178         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8179         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8180         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8181
8182         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8183
8184         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8185
8186         // We should fail to register the same payment hash twice, at least until we've connected a
8187         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8188         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8189                 assert_eq!(err, "Duplicate payment hash");
8190         } else { panic!(); }
8191         let mut block = {
8192                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8193                 Block {
8194                         header: BlockHeader {
8195                                 version: 0x2000000,
8196                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8197                                 merkle_root: Default::default(),
8198                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8199                         txdata: vec![],
8200                 }
8201         };
8202         connect_block(&nodes[1], &block);
8203         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8204                 assert_eq!(err, "Duplicate payment hash");
8205         } else { panic!(); }
8206
8207         // If we then connect the second block, we should be able to register the same payment hash
8208         // again with a different user_payment_id (this time getting a new payment secret).
8209         block.header.prev_blockhash = block.header.block_hash();
8210         block.header.time += 1;
8211         connect_block(&nodes[1], &block);
8212         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 42).unwrap();
8213         assert_ne!(payment_secret_1, our_payment_secret);
8214
8215         {
8216                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8217                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8218                 check_added_monitors!(nodes[0], 1);
8219                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8220                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8221                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8222                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8223         }
8224         // Note that after leaving the above scope we have no knowledge of any arguments or return
8225         // values from previous calls.
8226         expect_pending_htlcs_forwardable!(nodes[1]);
8227         let events = nodes[1].node.get_and_clear_pending_events();
8228         assert_eq!(events.len(), 1);
8229         match events[0] {
8230                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, user_payment_id }, .. } => {
8231                         assert!(payment_preimage.is_none());
8232                         assert_eq!(user_payment_id, 42);
8233                         assert_eq!(payment_secret, our_payment_secret);
8234                         // We don't actually have the payment preimage with which to claim this payment!
8235                 },
8236                 _ => panic!("Unexpected event"),
8237         }
8238 }
8239
8240 #[test]
8241 fn test_bad_secret_hash() {
8242         // Simple test of unregistered payment hash/invalid payment secret handling
8243         let chanmon_cfgs = create_chanmon_cfgs(2);
8244         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8245         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8246         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8247
8248         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8249
8250         let random_payment_hash = PaymentHash([42; 32]);
8251         let random_payment_secret = PaymentSecret([43; 32]);
8252         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8253         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8254
8255         // All the below cases should end up being handled exactly identically, so we macro the
8256         // resulting events.
8257         macro_rules! handle_unknown_invalid_payment_data {
8258                 () => {
8259                         check_added_monitors!(nodes[0], 1);
8260                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8261                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8262                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8263                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8264
8265                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8266                         // again to process the pending backwards-failure of the HTLC
8267                         expect_pending_htlcs_forwardable!(nodes[1]);
8268                         expect_pending_htlcs_forwardable!(nodes[1]);
8269                         check_added_monitors!(nodes[1], 1);
8270
8271                         // We should fail the payment back
8272                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8273                         match events.pop().unwrap() {
8274                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8275                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8276                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8277                                 },
8278                                 _ => panic!("Unexpected event"),
8279                         }
8280                 }
8281         }
8282
8283         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8284         // Error data is the HTLC value (100,000) and current block height
8285         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8286
8287         // Send a payment with the right payment hash but the wrong payment secret
8288         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8289         handle_unknown_invalid_payment_data!();
8290         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8291
8292         // Send a payment with a random payment hash, but the right payment secret
8293         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8294         handle_unknown_invalid_payment_data!();
8295         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8296
8297         // Send a payment with a random payment hash and random payment secret
8298         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8299         handle_unknown_invalid_payment_data!();
8300         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8301 }
8302
8303 #[test]
8304 fn test_update_err_monitor_lockdown() {
8305         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8306         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8307         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8308         //
8309         // This scenario may happen in a watchtower setup, where watchtower process a block height
8310         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8311         // commitment at same time.
8312
8313         let chanmon_cfgs = create_chanmon_cfgs(2);
8314         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8315         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8316         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8317
8318         // Create some initial channel
8319         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8320         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8321
8322         // Rebalance the network to generate htlc in the two directions
8323         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8324
8325         // Route a HTLC from node 0 to node 1 (but don't settle)
8326         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8327
8328         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8329         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8330         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8331         let persister = test_utils::TestPersister::new();
8332         let watchtower = {
8333                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8334                 let mut w = test_utils::TestVecWriter(Vec::new());
8335                 monitor.write(&mut w).unwrap();
8336                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8337                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8338                 assert!(new_monitor == *monitor);
8339                 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);
8340                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8341                 watchtower
8342         };
8343         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8344         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8345         // transaction lock time requirements here.
8346         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8347         watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8348
8349         // Try to update ChannelMonitor
8350         assert!(nodes[1].node.claim_funds(preimage));
8351         check_added_monitors!(nodes[1], 1);
8352         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8353         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8354         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8355         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8356                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8357                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8358                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8359                 } else { assert!(false); }
8360         } else { assert!(false); };
8361         // Our local monitor is in-sync and hasn't processed yet timeout
8362         check_added_monitors!(nodes[0], 1);
8363         let events = nodes[0].node.get_and_clear_pending_events();
8364         assert_eq!(events.len(), 1);
8365 }
8366
8367 #[test]
8368 fn test_concurrent_monitor_claim() {
8369         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8370         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8371         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8372         // state N+1 confirms. Alice claims output from state N+1.
8373
8374         let chanmon_cfgs = create_chanmon_cfgs(2);
8375         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8376         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8377         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8378
8379         // Create some initial channel
8380         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8381         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8382
8383         // Rebalance the network to generate htlc in the two directions
8384         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8385
8386         // Route a HTLC from node 0 to node 1 (but don't settle)
8387         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8388
8389         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8390         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8391         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8392         let persister = test_utils::TestPersister::new();
8393         let watchtower_alice = {
8394                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8395                 let mut w = test_utils::TestVecWriter(Vec::new());
8396                 monitor.write(&mut w).unwrap();
8397                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8398                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8399                 assert!(new_monitor == *monitor);
8400                 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);
8401                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8402                 watchtower
8403         };
8404         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8405         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8406         // transaction lock time requirements here.
8407         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8408         watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8409
8410         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8411         {
8412                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8413                 assert_eq!(txn.len(), 2);
8414                 txn.clear();
8415         }
8416
8417         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8418         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8419         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8420         let persister = test_utils::TestPersister::new();
8421         let watchtower_bob = {
8422                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8423                 let mut w = test_utils::TestVecWriter(Vec::new());
8424                 monitor.write(&mut w).unwrap();
8425                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8426                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8427                 assert!(new_monitor == *monitor);
8428                 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);
8429                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8430                 watchtower
8431         };
8432         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8433         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8434
8435         // Route another payment to generate another update with still previous HTLC pending
8436         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8437         {
8438                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8439         }
8440         check_added_monitors!(nodes[1], 1);
8441
8442         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8443         assert_eq!(updates.update_add_htlcs.len(), 1);
8444         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8445         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8446                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8447                         // Watchtower Alice should already have seen the block and reject the update
8448                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8449                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8450                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8451                 } else { assert!(false); }
8452         } else { assert!(false); };
8453         // Our local monitor is in-sync and hasn't processed yet timeout
8454         check_added_monitors!(nodes[0], 1);
8455
8456         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8457         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8458         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8459
8460         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8461         let bob_state_y;
8462         {
8463                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8464                 assert_eq!(txn.len(), 2);
8465                 bob_state_y = txn[0].clone();
8466                 txn.clear();
8467         };
8468
8469         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8470         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8471         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);
8472         {
8473                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8474                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8475                 // the onchain detection of the HTLC output
8476                 assert_eq!(htlc_txn.len(), 2);
8477                 check_spends!(htlc_txn[0], bob_state_y);
8478                 check_spends!(htlc_txn[1], bob_state_y);
8479         }
8480 }
8481
8482 #[test]
8483 fn test_pre_lockin_no_chan_closed_update() {
8484         // Test that if a peer closes a channel in response to a funding_created message we don't
8485         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8486         // message).
8487         //
8488         // Doing so would imply a channel monitor update before the initial channel monitor
8489         // registration, violating our API guarantees.
8490         //
8491         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8492         // then opening a second channel with the same funding output as the first (which is not
8493         // rejected because the first channel does not exist in the ChannelManager) and closing it
8494         // before receiving funding_signed.
8495         let chanmon_cfgs = create_chanmon_cfgs(2);
8496         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8497         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8498         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8499
8500         // Create an initial channel
8501         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8502         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8503         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8504         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8505         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8506
8507         // Move the first channel through the funding flow...
8508         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8509
8510         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8511         check_added_monitors!(nodes[0], 0);
8512
8513         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8514         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8515         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8516         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8517         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8518 }
8519
8520 #[test]
8521 fn test_htlc_no_detection() {
8522         // This test is a mutation to underscore the detection logic bug we had
8523         // before #653. HTLC value routed is above the remaining balance, thus
8524         // inverting HTLC and `to_remote` output. HTLC will come second and
8525         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8526         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8527         // outputs order detection for correct spending children filtring.
8528
8529         let chanmon_cfgs = create_chanmon_cfgs(2);
8530         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8531         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8532         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8533
8534         // Create some initial channels
8535         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8536
8537         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8538         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8539         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8540         assert_eq!(local_txn[0].input.len(), 1);
8541         assert_eq!(local_txn[0].output.len(), 3);
8542         check_spends!(local_txn[0], chan_1.3);
8543
8544         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8545         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8546         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8547         // We deliberately connect the local tx twice as this should provoke a failure calling
8548         // this test before #653 fix.
8549         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);
8550         check_closed_broadcast!(nodes[0], true);
8551         check_added_monitors!(nodes[0], 1);
8552         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8553         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8554
8555         let htlc_timeout = {
8556                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8557                 assert_eq!(node_txn[1].input.len(), 1);
8558                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8559                 check_spends!(node_txn[1], local_txn[0]);
8560                 node_txn[1].clone()
8561         };
8562
8563         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8564         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8565         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8566         expect_payment_failed!(nodes[0], our_payment_hash, true);
8567 }
8568
8569 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8570         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8571         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8572         // Carol, Alice would be the upstream node, and Carol the downstream.)
8573         //
8574         // Steps of the test:
8575         // 1) Alice sends a HTLC to Carol through Bob.
8576         // 2) Carol doesn't settle the HTLC.
8577         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8578         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8579         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8580         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8581         // 5) Carol release the preimage to Bob off-chain.
8582         // 6) Bob claims the offered output on the broadcasted commitment.
8583         let chanmon_cfgs = create_chanmon_cfgs(3);
8584         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8585         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8586         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8587
8588         // Create some initial channels
8589         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8590         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8591
8592         // Steps (1) and (2):
8593         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8594         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8595
8596         // Check that Alice's commitment transaction now contains an output for this HTLC.
8597         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8598         check_spends!(alice_txn[0], chan_ab.3);
8599         assert_eq!(alice_txn[0].output.len(), 2);
8600         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8601         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8602         assert_eq!(alice_txn.len(), 2);
8603
8604         // Steps (3) and (4):
8605         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8606         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8607         let mut force_closing_node = 0; // Alice force-closes
8608         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8609         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8610         check_closed_broadcast!(nodes[force_closing_node], true);
8611         check_added_monitors!(nodes[force_closing_node], 1);
8612         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8613         if go_onchain_before_fulfill {
8614                 let txn_to_broadcast = match broadcast_alice {
8615                         true => alice_txn.clone(),
8616                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8617                 };
8618                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8619                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8620                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8621                 if broadcast_alice {
8622                         check_closed_broadcast!(nodes[1], true);
8623                         check_added_monitors!(nodes[1], 1);
8624                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8625                 }
8626                 assert_eq!(bob_txn.len(), 1);
8627                 check_spends!(bob_txn[0], chan_ab.3);
8628         }
8629
8630         // Step (5):
8631         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8632         // process of removing the HTLC from their commitment transactions.
8633         assert!(nodes[2].node.claim_funds(payment_preimage));
8634         check_added_monitors!(nodes[2], 1);
8635         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8636         assert!(carol_updates.update_add_htlcs.is_empty());
8637         assert!(carol_updates.update_fail_htlcs.is_empty());
8638         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8639         assert!(carol_updates.update_fee.is_none());
8640         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8641
8642         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8643         expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8644         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8645         if !go_onchain_before_fulfill && broadcast_alice {
8646                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8647                 assert_eq!(events.len(), 1);
8648                 match events[0] {
8649                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8650                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8651                         },
8652                         _ => panic!("Unexpected event"),
8653                 };
8654         }
8655         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8656         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8657         // Carol<->Bob's updated commitment transaction info.
8658         check_added_monitors!(nodes[1], 2);
8659
8660         let events = nodes[1].node.get_and_clear_pending_msg_events();
8661         assert_eq!(events.len(), 2);
8662         let bob_revocation = match events[0] {
8663                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8664                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8665                         (*msg).clone()
8666                 },
8667                 _ => panic!("Unexpected event"),
8668         };
8669         let bob_updates = match events[1] {
8670                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8671                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8672                         (*updates).clone()
8673                 },
8674                 _ => panic!("Unexpected event"),
8675         };
8676
8677         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8678         check_added_monitors!(nodes[2], 1);
8679         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8680         check_added_monitors!(nodes[2], 1);
8681
8682         let events = nodes[2].node.get_and_clear_pending_msg_events();
8683         assert_eq!(events.len(), 1);
8684         let carol_revocation = match events[0] {
8685                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8686                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8687                         (*msg).clone()
8688                 },
8689                 _ => panic!("Unexpected event"),
8690         };
8691         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8692         check_added_monitors!(nodes[1], 1);
8693
8694         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8695         // here's where we put said channel's commitment tx on-chain.
8696         let mut txn_to_broadcast = alice_txn.clone();
8697         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8698         if !go_onchain_before_fulfill {
8699                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8700                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8701                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8702                 if broadcast_alice {
8703                         check_closed_broadcast!(nodes[1], true);
8704                         check_added_monitors!(nodes[1], 1);
8705                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8706                 }
8707                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8708                 if broadcast_alice {
8709                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8710                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8711                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8712                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8713                         // broadcasted.
8714                         assert_eq!(bob_txn.len(), 3);
8715                         check_spends!(bob_txn[1], chan_ab.3);
8716                 } else {
8717                         assert_eq!(bob_txn.len(), 2);
8718                         check_spends!(bob_txn[0], chan_ab.3);
8719                 }
8720         }
8721
8722         // Step (6):
8723         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8724         // broadcasted commitment transaction.
8725         {
8726                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8727                 if go_onchain_before_fulfill {
8728                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8729                         assert_eq!(bob_txn.len(), 2);
8730                 }
8731                 let script_weight = match broadcast_alice {
8732                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8733                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8734                 };
8735                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8736                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8737                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8738                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8739                 if broadcast_alice && !go_onchain_before_fulfill {
8740                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8741                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8742                 } else {
8743                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8744                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8745                 }
8746         }
8747 }
8748
8749 #[test]
8750 fn test_onchain_htlc_settlement_after_close() {
8751         do_test_onchain_htlc_settlement_after_close(true, true);
8752         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8753         do_test_onchain_htlc_settlement_after_close(true, false);
8754         do_test_onchain_htlc_settlement_after_close(false, false);
8755 }
8756
8757 #[test]
8758 fn test_duplicate_chan_id() {
8759         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8760         // already open we reject it and keep the old channel.
8761         //
8762         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8763         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8764         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8765         // updating logic for the existing channel.
8766         let chanmon_cfgs = create_chanmon_cfgs(2);
8767         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8768         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8769         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8770
8771         // Create an initial channel
8772         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8773         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8774         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8775         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()));
8776
8777         // Try to create a second channel with the same temporary_channel_id as the first and check
8778         // that it is rejected.
8779         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8780         {
8781                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8782                 assert_eq!(events.len(), 1);
8783                 match events[0] {
8784                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8785                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8786                                 // first (valid) and second (invalid) channels are closed, given they both have
8787                                 // the same non-temporary channel_id. However, currently we do not, so we just
8788                                 // move forward with it.
8789                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8790                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8791                         },
8792                         _ => panic!("Unexpected event"),
8793                 }
8794         }
8795
8796         // Move the first channel through the funding flow...
8797         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8798
8799         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8800         check_added_monitors!(nodes[0], 0);
8801
8802         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8803         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8804         {
8805                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8806                 assert_eq!(added_monitors.len(), 1);
8807                 assert_eq!(added_monitors[0].0, funding_output);
8808                 added_monitors.clear();
8809         }
8810         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8811
8812         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8813         let channel_id = funding_outpoint.to_channel_id();
8814
8815         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8816         // temporary one).
8817
8818         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8819         // Technically this is allowed by the spec, but we don't support it and there's little reason
8820         // to. Still, it shouldn't cause any other issues.
8821         open_chan_msg.temporary_channel_id = channel_id;
8822         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8823         {
8824                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8825                 assert_eq!(events.len(), 1);
8826                 match events[0] {
8827                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8828                                 // Technically, at this point, nodes[1] would be justified in thinking both
8829                                 // channels are closed, but currently we do not, so we just move forward with it.
8830                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8831                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8832                         },
8833                         _ => panic!("Unexpected event"),
8834                 }
8835         }
8836
8837         // Now try to create a second channel which has a duplicate funding output.
8838         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8839         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8840         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8841         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()));
8842         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8843
8844         let funding_created = {
8845                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8846                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8847                 let logger = test_utils::TestLogger::new();
8848                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8849         };
8850         check_added_monitors!(nodes[0], 0);
8851         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8852         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8853         // still needs to be cleared here.
8854         check_added_monitors!(nodes[1], 1);
8855
8856         // ...still, nodes[1] will reject the duplicate channel.
8857         {
8858                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8859                 assert_eq!(events.len(), 1);
8860                 match events[0] {
8861                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8862                                 // Technically, at this point, nodes[1] would be justified in thinking both
8863                                 // channels are closed, but currently we do not, so we just move forward with it.
8864                                 assert_eq!(msg.channel_id, channel_id);
8865                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8866                         },
8867                         _ => panic!("Unexpected event"),
8868                 }
8869         }
8870
8871         // finally, finish creating the original channel and send a payment over it to make sure
8872         // everything is functional.
8873         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8874         {
8875                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8876                 assert_eq!(added_monitors.len(), 1);
8877                 assert_eq!(added_monitors[0].0, funding_output);
8878                 added_monitors.clear();
8879         }
8880
8881         let events_4 = nodes[0].node.get_and_clear_pending_events();
8882         assert_eq!(events_4.len(), 0);
8883         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8884         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
8885
8886         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8887         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8888         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8889         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8890 }
8891
8892 #[test]
8893 fn test_error_chans_closed() {
8894         // Test that we properly handle error messages, closing appropriate channels.
8895         //
8896         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8897         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8898         // we can test various edge cases around it to ensure we don't regress.
8899         let chanmon_cfgs = create_chanmon_cfgs(3);
8900         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8901         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8902         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8903
8904         // Create some initial channels
8905         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8906         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8907         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8908
8909         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8910         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8911         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8912
8913         // Closing a channel from a different peer has no effect
8914         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8915         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8916
8917         // Closing one channel doesn't impact others
8918         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8919         check_added_monitors!(nodes[0], 1);
8920         check_closed_broadcast!(nodes[0], false);
8921         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8922         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8923         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8924         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);
8925         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);
8926
8927         // A null channel ID should close all channels
8928         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8929         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8930         check_added_monitors!(nodes[0], 2);
8931         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8932         let events = nodes[0].node.get_and_clear_pending_msg_events();
8933         assert_eq!(events.len(), 2);
8934         match events[0] {
8935                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8936                         assert_eq!(msg.contents.flags & 2, 2);
8937                 },
8938                 _ => panic!("Unexpected event"),
8939         }
8940         match events[1] {
8941                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8942                         assert_eq!(msg.contents.flags & 2, 2);
8943                 },
8944                 _ => panic!("Unexpected event"),
8945         }
8946         // Note that at this point users of a standard PeerHandler will end up calling
8947         // peer_disconnected with no_connection_possible set to false, duplicating the
8948         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8949         // users with their own peer handling logic. We duplicate the call here, however.
8950         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8951         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8952
8953         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8954         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8955         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8956 }
8957
8958 #[test]
8959 fn test_invalid_funding_tx() {
8960         // Test that we properly handle invalid funding transactions sent to us from a peer.
8961         //
8962         // Previously, all other major lightning implementations had failed to properly sanitize
8963         // funding transactions from their counterparties, leading to a multi-implementation critical
8964         // security vulnerability (though we always sanitized properly, we've previously had
8965         // un-released crashes in the sanitization process).
8966         let chanmon_cfgs = create_chanmon_cfgs(2);
8967         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8968         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8969         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8970
8971         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8972         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()));
8973         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()));
8974
8975         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
8976         for output in tx.output.iter_mut() {
8977                 // Make the confirmed funding transaction have a bogus script_pubkey
8978                 output.script_pubkey = bitcoin::Script::new();
8979         }
8980
8981         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
8982         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()));
8983         check_added_monitors!(nodes[1], 1);
8984
8985         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()));
8986         check_added_monitors!(nodes[0], 1);
8987
8988         let events_1 = nodes[0].node.get_and_clear_pending_events();
8989         assert_eq!(events_1.len(), 0);
8990
8991         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8992         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8993         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8994
8995         confirm_transaction_at(&nodes[1], &tx, 1);
8996         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8997         check_added_monitors!(nodes[1], 1);
8998         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8999         assert_eq!(events_2.len(), 1);
9000         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9001                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9002                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9003                         assert_eq!(msg.data, "funding tx had wrong script/value or output index");
9004                 } else { panic!(); }
9005         } else { panic!(); }
9006         assert_eq!(nodes[1].node.list_channels().len(), 0);
9007 }
9008
9009 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9010         // In the first version of the chain::Confirm interface, after a refactor was made to not
9011         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9012         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9013         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9014         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9015         // spending transaction until height N+1 (or greater). This was due to the way
9016         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9017         // spending transaction at the height the input transaction was confirmed at, not whether we
9018         // should broadcast a spending transaction at the current height.
9019         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9020         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9021         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9022         // until we learned about an additional block.
9023         //
9024         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9025         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9026         let chanmon_cfgs = create_chanmon_cfgs(3);
9027         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9028         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9029         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9030         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9031
9032         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9033         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9034         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9035         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9036         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9037
9038         nodes[1].node.force_close_channel(&channel_id).unwrap();
9039         check_closed_broadcast!(nodes[1], true);
9040         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9041         check_added_monitors!(nodes[1], 1);
9042         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9043         assert_eq!(node_txn.len(), 1);
9044
9045         let conf_height = nodes[1].best_block_info().1;
9046         if !test_height_before_timelock {
9047                 connect_blocks(&nodes[1], 24 * 6);
9048         }
9049         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9050                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9051         if test_height_before_timelock {
9052                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9053                 // generate any events or broadcast any transactions
9054                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9055                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9056         } else {
9057                 // We should broadcast an HTLC transaction spending our funding transaction first
9058                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9059                 assert_eq!(spending_txn.len(), 2);
9060                 assert_eq!(spending_txn[0], node_txn[0]);
9061                 check_spends!(spending_txn[1], node_txn[0]);
9062                 // We should also generate a SpendableOutputs event with the to_self output (as its
9063                 // timelock is up).
9064                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9065                 assert_eq!(descriptor_spend_txn.len(), 1);
9066
9067                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9068                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9069                 // additional block built on top of the current chain.
9070                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9071                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9072                 expect_pending_htlcs_forwardable!(nodes[1]);
9073                 check_added_monitors!(nodes[1], 1);
9074
9075                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9076                 assert!(updates.update_add_htlcs.is_empty());
9077                 assert!(updates.update_fulfill_htlcs.is_empty());
9078                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9079                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9080                 assert!(updates.update_fee.is_none());
9081                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9082                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9083                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9084         }
9085 }
9086
9087 #[test]
9088 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9089         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9090         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9091 }
9092
9093 #[test]
9094 fn test_forwardable_regen() {
9095         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9096         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9097         // HTLCs.
9098         // We test it for both payment receipt and payment forwarding.
9099
9100         let chanmon_cfgs = create_chanmon_cfgs(3);
9101         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9102         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9103         let persister: test_utils::TestPersister;
9104         let new_chain_monitor: test_utils::TestChainMonitor;
9105         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9106         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9107         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9108         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9109
9110         // First send a payment to nodes[1]
9111         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9112         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9113         check_added_monitors!(nodes[0], 1);
9114
9115         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9116         assert_eq!(events.len(), 1);
9117         let payment_event = SendEvent::from_event(events.pop().unwrap());
9118         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9119         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9120
9121         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9122
9123         // Next send a payment which is forwarded by nodes[1]
9124         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9125         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9126         check_added_monitors!(nodes[0], 1);
9127
9128         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9129         assert_eq!(events.len(), 1);
9130         let payment_event = SendEvent::from_event(events.pop().unwrap());
9131         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9132         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9133
9134         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9135         // generated
9136         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9137
9138         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9139         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9140         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9141
9142         let nodes_1_serialized = nodes[1].node.encode();
9143         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9144         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9145         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9146         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9147
9148         persister = test_utils::TestPersister::new();
9149         let keys_manager = &chanmon_cfgs[1].keys_manager;
9150         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);
9151         nodes[1].chain_monitor = &new_chain_monitor;
9152
9153         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9154         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9155                 &mut chan_0_monitor_read, keys_manager).unwrap();
9156         assert!(chan_0_monitor_read.is_empty());
9157         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9158         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9159                 &mut chan_1_monitor_read, keys_manager).unwrap();
9160         assert!(chan_1_monitor_read.is_empty());
9161
9162         let mut nodes_1_read = &nodes_1_serialized[..];
9163         let (_, nodes_1_deserialized_tmp) = {
9164                 let mut channel_monitors = HashMap::new();
9165                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9166                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9167                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9168                         default_config: UserConfig::default(),
9169                         keys_manager,
9170                         fee_estimator: node_cfgs[1].fee_estimator,
9171                         chain_monitor: nodes[1].chain_monitor,
9172                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9173                         logger: nodes[1].logger,
9174                         channel_monitors,
9175                 }).unwrap()
9176         };
9177         nodes_1_deserialized = nodes_1_deserialized_tmp;
9178         assert!(nodes_1_read.is_empty());
9179
9180         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9181         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9182         nodes[1].node = &nodes_1_deserialized;
9183         check_added_monitors!(nodes[1], 2);
9184
9185         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9186         // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9187         // the commitment state.
9188         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9189
9190         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9191
9192         expect_pending_htlcs_forwardable!(nodes[1]);
9193         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9194         check_added_monitors!(nodes[1], 1);
9195
9196         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9197         assert_eq!(events.len(), 1);
9198         let payment_event = SendEvent::from_event(events.pop().unwrap());
9199         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9200         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9201         expect_pending_htlcs_forwardable!(nodes[2]);
9202         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9203
9204         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9205         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9206 }
9207
9208 #[test]
9209 fn test_keysend_payments_to_public_node() {
9210         let chanmon_cfgs = create_chanmon_cfgs(2);
9211         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9212         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9213         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9214
9215         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9216         let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
9217         let payer_pubkey = nodes[0].node.get_our_node_id();
9218         let payee_pubkey = nodes[1].node.get_our_node_id();
9219         let scorer = Scorer::new(0);
9220         let route = get_keysend_route(
9221                 &payer_pubkey, &network_graph, &payee_pubkey, None, &vec![], 10000, 40, nodes[0].logger, &scorer
9222         ).unwrap();
9223
9224         let test_preimage = PaymentPreimage([42; 32]);
9225         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9226         check_added_monitors!(nodes[0], 1);
9227         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9228         assert_eq!(events.len(), 1);
9229         let event = events.pop().unwrap();
9230         let path = vec![&nodes[1]];
9231         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9232         claim_payment(&nodes[0], &path, test_preimage);
9233 }
9234
9235 #[test]
9236 fn test_keysend_payments_to_private_node() {
9237         let chanmon_cfgs = create_chanmon_cfgs(2);
9238         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9239         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9240         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9241
9242         let payer_pubkey = nodes[0].node.get_our_node_id();
9243         let payee_pubkey = nodes[1].node.get_our_node_id();
9244         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known() });
9245         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known() });
9246
9247         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9248         let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
9249         let first_hops = nodes[0].node.list_usable_channels();
9250         let scorer = Scorer::new(0);
9251         let route = get_keysend_route(
9252                 &payer_pubkey, &network_graph, &payee_pubkey, Some(&first_hops.iter().collect::<Vec<_>>()),
9253                 &vec![], 10000, 40, nodes[0].logger, &scorer
9254         ).unwrap();
9255
9256         let test_preimage = PaymentPreimage([42; 32]);
9257         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9258         check_added_monitors!(nodes[0], 1);
9259         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9260         assert_eq!(events.len(), 1);
9261         let event = events.pop().unwrap();
9262         let path = vec![&nodes[1]];
9263         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9264         claim_payment(&nodes[0], &path, test_preimage);
9265 }