Cancel the outbound feerate update if above what we can afford
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use chain;
15 use chain::{Confirm, Listen, Watch};
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::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, HTLCOutputInCommitment};
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 = 1977;
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         let secp_ctx = Secp256k1::new();
592
593         let feerate = 260;
594         {
595                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
596                 *feerate_lock = feerate;
597         }
598         nodes[0].node.timer_tick_occurred();
599         check_added_monitors!(nodes[0], 1);
600         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
601
602         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
603
604         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
605
606         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
607         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
608         {
609                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
610
611                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
612                 let num_htlcs = commitment_tx.output.len() - 2;
613                 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
614                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
615                 actual_fee = channel_value - actual_fee;
616                 assert_eq!(total_fee, actual_fee);
617         }
618
619         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
620         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
621         {
622                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
623                 *feerate_lock = feerate + 2;
624         }
625         nodes[0].node.timer_tick_occurred();
626         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 2), 1);
627         check_added_monitors!(nodes[0], 0);
628
629         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
630
631         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
632         // needed to sign the new commitment tx and (2) sign the new commitment tx.
633         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
634                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
635                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
636                 let chan_signer = local_chan.get_signer();
637                 let pubkeys = chan_signer.pubkeys();
638                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
639                  pubkeys.funding_pubkey)
640         };
641         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
642                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
643                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
644                 let chan_signer = remote_chan.get_signer();
645                 let pubkeys = chan_signer.pubkeys();
646                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
647                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
648                  pubkeys.funding_pubkey)
649         };
650
651         // Assemble the set of keys we can use for signatures for our commitment_signed message.
652         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
653                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
654
655         let res = {
656                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
657                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
658                 let local_chan_signer = local_chan.get_signer();
659                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
660                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
661                         INITIAL_COMMITMENT_NUMBER - 1,
662                         700,
663                         999,
664                         false, local_funding, remote_funding,
665                         commit_tx_keys.clone(),
666                         feerate + 124,
667                         &mut htlcs,
668                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
669                 );
670                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
671         };
672
673         let commit_signed_msg = msgs::CommitmentSigned {
674                 channel_id: chan.2,
675                 signature: res.0,
676                 htlc_signatures: res.1
677         };
678
679         let update_fee = msgs::UpdateFee {
680                 channel_id: chan.2,
681                 feerate_per_kw: feerate + 124,
682         };
683
684         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
685
686         //While producing the commitment_signed response after handling a received update_fee request the
687         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
688         //Should produce and error.
689         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
690         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
691         check_added_monitors!(nodes[1], 1);
692         check_closed_broadcast!(nodes[1], true);
693         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
694 }
695
696 #[test]
697 fn test_update_fee_with_fundee_update_add_htlc() {
698         let chanmon_cfgs = create_chanmon_cfgs(2);
699         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
700         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
701         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
702         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
703
704         // balancing
705         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
706
707         {
708                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
709                 *feerate_lock += 20;
710         }
711         nodes[0].node.timer_tick_occurred();
712         check_added_monitors!(nodes[0], 1);
713
714         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
715         assert_eq!(events_0.len(), 1);
716         let (update_msg, commitment_signed) = match events_0[0] {
717                         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 } } => {
718                         (update_fee.as_ref(), commitment_signed)
719                 },
720                 _ => panic!("Unexpected event"),
721         };
722         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
723         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
724         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
725         check_added_monitors!(nodes[1], 1);
726
727         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
728
729         // nothing happens since node[1] is in AwaitingRemoteRevoke
730         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
731         {
732                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
733                 assert_eq!(added_monitors.len(), 0);
734                 added_monitors.clear();
735         }
736         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
737         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
738         // node[1] has nothing to do
739
740         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
741         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
742         check_added_monitors!(nodes[0], 1);
743
744         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
745         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
746         // No commitment_signed so get_event_msg's assert(len == 1) passes
747         check_added_monitors!(nodes[0], 1);
748         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
749         check_added_monitors!(nodes[1], 1);
750         // AwaitingRemoteRevoke ends here
751
752         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
753         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
754         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
755         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
756         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
757         assert_eq!(commitment_update.update_fee.is_none(), true);
758
759         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
760         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
761         check_added_monitors!(nodes[0], 1);
762         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
763
764         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
765         check_added_monitors!(nodes[1], 1);
766         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
767
768         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
769         check_added_monitors!(nodes[1], 1);
770         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
771         // No commitment_signed so get_event_msg's assert(len == 1) passes
772
773         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
774         check_added_monitors!(nodes[0], 1);
775         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
776
777         expect_pending_htlcs_forwardable!(nodes[0]);
778
779         let events = nodes[0].node.get_and_clear_pending_events();
780         assert_eq!(events.len(), 1);
781         match events[0] {
782                 Event::PaymentReceived { .. } => { },
783                 _ => panic!("Unexpected event"),
784         };
785
786         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
787
788         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
789         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
790         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
791         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
792         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
793 }
794
795 #[test]
796 fn test_update_fee() {
797         let chanmon_cfgs = create_chanmon_cfgs(2);
798         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
799         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
800         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
801         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
802         let channel_id = chan.2;
803
804         // A                                        B
805         // (1) update_fee/commitment_signed      ->
806         //                                       <- (2) revoke_and_ack
807         //                                       .- send (3) commitment_signed
808         // (4) update_fee/commitment_signed      ->
809         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
810         //                                       <- (3) commitment_signed delivered
811         // send (6) revoke_and_ack               -.
812         //                                       <- (5) deliver revoke_and_ack
813         // (6) deliver revoke_and_ack            ->
814         //                                       .- send (7) commitment_signed in response to (4)
815         //                                       <- (7) deliver commitment_signed
816         // revoke_and_ack                        ->
817
818         // Create and deliver (1)...
819         let feerate;
820         {
821                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
822                 feerate = *feerate_lock;
823                 *feerate_lock = feerate + 20;
824         }
825         nodes[0].node.timer_tick_occurred();
826         check_added_monitors!(nodes[0], 1);
827
828         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
829         assert_eq!(events_0.len(), 1);
830         let (update_msg, commitment_signed) = match events_0[0] {
831                         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 } } => {
832                         (update_fee.as_ref(), commitment_signed)
833                 },
834                 _ => panic!("Unexpected event"),
835         };
836         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
837
838         // Generate (2) and (3):
839         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
840         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
841         check_added_monitors!(nodes[1], 1);
842
843         // Deliver (2):
844         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
845         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
846         check_added_monitors!(nodes[0], 1);
847
848         // Create and deliver (4)...
849         {
850                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
851                 *feerate_lock = feerate + 30;
852         }
853         nodes[0].node.timer_tick_occurred();
854         check_added_monitors!(nodes[0], 1);
855         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
856         assert_eq!(events_0.len(), 1);
857         let (update_msg, commitment_signed) = match events_0[0] {
858                         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 } } => {
859                         (update_fee.as_ref(), commitment_signed)
860                 },
861                 _ => panic!("Unexpected event"),
862         };
863
864         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
865         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
866         check_added_monitors!(nodes[1], 1);
867         // ... creating (5)
868         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
869         // No commitment_signed so get_event_msg's assert(len == 1) passes
870
871         // Handle (3), creating (6):
872         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
873         check_added_monitors!(nodes[0], 1);
874         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
875         // No commitment_signed so get_event_msg's assert(len == 1) passes
876
877         // Deliver (5):
878         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
879         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
880         check_added_monitors!(nodes[0], 1);
881
882         // Deliver (6), creating (7):
883         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
884         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
885         assert!(commitment_update.update_add_htlcs.is_empty());
886         assert!(commitment_update.update_fulfill_htlcs.is_empty());
887         assert!(commitment_update.update_fail_htlcs.is_empty());
888         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
889         assert!(commitment_update.update_fee.is_none());
890         check_added_monitors!(nodes[1], 1);
891
892         // Deliver (7)
893         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
894         check_added_monitors!(nodes[0], 1);
895         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
896         // No commitment_signed so get_event_msg's assert(len == 1) passes
897
898         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
899         check_added_monitors!(nodes[1], 1);
900         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
901
902         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
903         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
904         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
905         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
906         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
907 }
908
909 #[test]
910 fn fake_network_test() {
911         // Simple test which builds a network of ChannelManagers, connects them to each other, and
912         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
913         let chanmon_cfgs = create_chanmon_cfgs(4);
914         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
915         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
916         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
917
918         // Create some initial channels
919         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
920         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
921         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
922
923         // Rebalance the network a bit by relaying one payment through all the channels...
924         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
925         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
926         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
927         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
928
929         // Send some more payments
930         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
931         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
932         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
933
934         // Test failure packets
935         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
936         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
937
938         // Add a new channel that skips 3
939         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
940
941         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
942         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
943         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
944         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
945         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
946         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
947         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
948
949         // Do some rebalance loop payments, simultaneously
950         let mut hops = Vec::with_capacity(3);
951         hops.push(RouteHop {
952                 pubkey: nodes[2].node.get_our_node_id(),
953                 node_features: NodeFeatures::empty(),
954                 short_channel_id: chan_2.0.contents.short_channel_id,
955                 channel_features: ChannelFeatures::empty(),
956                 fee_msat: 0,
957                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
958         });
959         hops.push(RouteHop {
960                 pubkey: nodes[3].node.get_our_node_id(),
961                 node_features: NodeFeatures::empty(),
962                 short_channel_id: chan_3.0.contents.short_channel_id,
963                 channel_features: ChannelFeatures::empty(),
964                 fee_msat: 0,
965                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
966         });
967         hops.push(RouteHop {
968                 pubkey: nodes[1].node.get_our_node_id(),
969                 node_features: NodeFeatures::known(),
970                 short_channel_id: chan_4.0.contents.short_channel_id,
971                 channel_features: ChannelFeatures::known(),
972                 fee_msat: 1000000,
973                 cltv_expiry_delta: TEST_FINAL_CLTV,
974         });
975         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;
976         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;
977         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
978
979         let mut hops = Vec::with_capacity(3);
980         hops.push(RouteHop {
981                 pubkey: nodes[3].node.get_our_node_id(),
982                 node_features: NodeFeatures::empty(),
983                 short_channel_id: chan_4.0.contents.short_channel_id,
984                 channel_features: ChannelFeatures::empty(),
985                 fee_msat: 0,
986                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
987         });
988         hops.push(RouteHop {
989                 pubkey: nodes[2].node.get_our_node_id(),
990                 node_features: NodeFeatures::empty(),
991                 short_channel_id: chan_3.0.contents.short_channel_id,
992                 channel_features: ChannelFeatures::empty(),
993                 fee_msat: 0,
994                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
995         });
996         hops.push(RouteHop {
997                 pubkey: nodes[1].node.get_our_node_id(),
998                 node_features: NodeFeatures::known(),
999                 short_channel_id: chan_2.0.contents.short_channel_id,
1000                 channel_features: ChannelFeatures::known(),
1001                 fee_msat: 1000000,
1002                 cltv_expiry_delta: TEST_FINAL_CLTV,
1003         });
1004         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;
1005         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;
1006         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1007
1008         // Claim the rebalances...
1009         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1010         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1011
1012         // Add a duplicate new channel from 2 to 4
1013         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1014
1015         // Send some payments across both channels
1016         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1017         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1018         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1019
1020
1021         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1022         let events = nodes[0].node.get_and_clear_pending_msg_events();
1023         assert_eq!(events.len(), 0);
1024         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);
1025
1026         //TODO: Test that routes work again here as we've been notified that the channel is full
1027
1028         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1029         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1030         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1031
1032         // Close down the channels...
1033         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1034         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1035         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1036         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1037         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1038         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1039         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1040         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1041         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1042         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1043         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1044         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1045         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1046         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1047         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1048 }
1049
1050 #[test]
1051 fn holding_cell_htlc_counting() {
1052         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1053         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1054         // commitment dance rounds.
1055         let chanmon_cfgs = create_chanmon_cfgs(3);
1056         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1057         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1058         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1059         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1060         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1061
1062         let mut payments = Vec::new();
1063         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1064                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1065                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1066                 payments.push((payment_preimage, payment_hash));
1067         }
1068         check_added_monitors!(nodes[1], 1);
1069
1070         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1071         assert_eq!(events.len(), 1);
1072         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1073         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1074
1075         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1076         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1077         // another HTLC.
1078         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1079         {
1080                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1081                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1082                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1083                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1084         }
1085
1086         // This should also be true if we try to forward a payment.
1087         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1088         {
1089                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1090                 check_added_monitors!(nodes[0], 1);
1091         }
1092
1093         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1094         assert_eq!(events.len(), 1);
1095         let payment_event = SendEvent::from_event(events.pop().unwrap());
1096         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1097
1098         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1099         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1100         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1101         // fails), the second will process the resulting failure and fail the HTLC backward.
1102         expect_pending_htlcs_forwardable!(nodes[1]);
1103         expect_pending_htlcs_forwardable!(nodes[1]);
1104         check_added_monitors!(nodes[1], 1);
1105
1106         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1107         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1108         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1109
1110         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1111
1112         // Now forward all the pending HTLCs and claim them back
1113         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1114         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1115         check_added_monitors!(nodes[2], 1);
1116
1117         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1118         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1119         check_added_monitors!(nodes[1], 1);
1120         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1121
1122         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1123         check_added_monitors!(nodes[1], 1);
1124         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1125
1126         for ref update in as_updates.update_add_htlcs.iter() {
1127                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1128         }
1129         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1130         check_added_monitors!(nodes[2], 1);
1131         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1132         check_added_monitors!(nodes[2], 1);
1133         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1134
1135         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1136         check_added_monitors!(nodes[1], 1);
1137         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1138         check_added_monitors!(nodes[1], 1);
1139         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1140
1141         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1142         check_added_monitors!(nodes[2], 1);
1143
1144         expect_pending_htlcs_forwardable!(nodes[2]);
1145
1146         let events = nodes[2].node.get_and_clear_pending_events();
1147         assert_eq!(events.len(), payments.len());
1148         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1149                 match event {
1150                         &Event::PaymentReceived { ref payment_hash, .. } => {
1151                                 assert_eq!(*payment_hash, *hash);
1152                         },
1153                         _ => panic!("Unexpected event"),
1154                 };
1155         }
1156
1157         for (preimage, _) in payments.drain(..) {
1158                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1159         }
1160
1161         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1162 }
1163
1164 #[test]
1165 fn duplicate_htlc_test() {
1166         // Test that we accept duplicate payment_hash HTLCs across the network and that
1167         // claiming/failing them are all separate and don't affect each other
1168         let chanmon_cfgs = create_chanmon_cfgs(6);
1169         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1170         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1171         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1172
1173         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1174         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1175         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1176         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1177         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1178         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1179
1180         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1181
1182         *nodes[0].network_payment_count.borrow_mut() -= 1;
1183         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1184
1185         *nodes[0].network_payment_count.borrow_mut() -= 1;
1186         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1187
1188         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1189         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1190         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1191 }
1192
1193 #[test]
1194 fn test_duplicate_htlc_different_direction_onchain() {
1195         // Test that ChannelMonitor doesn't generate 2 preimage txn
1196         // when we have 2 HTLCs with same preimage that go across a node
1197         // in opposite directions, even with the same payment secret.
1198         let chanmon_cfgs = create_chanmon_cfgs(2);
1199         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1200         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1201         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1202
1203         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1204
1205         // balancing
1206         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1207
1208         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1209
1210         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1211         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, 0).unwrap();
1212         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1213
1214         // Provide preimage to node 0 by claiming payment
1215         nodes[0].node.claim_funds(payment_preimage);
1216         check_added_monitors!(nodes[0], 1);
1217
1218         // Broadcast node 1 commitment txn
1219         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1220
1221         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1222         let mut has_both_htlcs = 0; // check htlcs match ones committed
1223         for outp in remote_txn[0].output.iter() {
1224                 if outp.value == 800_000 / 1000 {
1225                         has_both_htlcs += 1;
1226                 } else if outp.value == 900_000 / 1000 {
1227                         has_both_htlcs += 1;
1228                 }
1229         }
1230         assert_eq!(has_both_htlcs, 2);
1231
1232         mine_transaction(&nodes[0], &remote_txn[0]);
1233         check_added_monitors!(nodes[0], 1);
1234         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1235         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1236
1237         // Check we only broadcast 1 timeout tx
1238         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1239         assert_eq!(claim_txn.len(), 8);
1240         assert_eq!(claim_txn[1], claim_txn[4]);
1241         assert_eq!(claim_txn[2], claim_txn[5]);
1242         check_spends!(claim_txn[1], chan_1.3);
1243         check_spends!(claim_txn[2], claim_txn[1]);
1244         check_spends!(claim_txn[7], claim_txn[1]);
1245
1246         assert_eq!(claim_txn[0].input.len(), 1);
1247         assert_eq!(claim_txn[3].input.len(), 1);
1248         assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1249
1250         assert_eq!(claim_txn[0].input.len(), 1);
1251         assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1252         check_spends!(claim_txn[0], remote_txn[0]);
1253         assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1254         assert_eq!(claim_txn[6].input.len(), 1);
1255         assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1256         check_spends!(claim_txn[6], remote_txn[0]);
1257         assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1258
1259         let events = nodes[0].node.get_and_clear_pending_msg_events();
1260         assert_eq!(events.len(), 3);
1261         for e in events {
1262                 match e {
1263                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1264                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1265                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1266                                 assert_eq!(msg.data, "Commitment or closing transaction was confirmed on chain.");
1267                         },
1268                         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, .. } } => {
1269                                 assert!(update_add_htlcs.is_empty());
1270                                 assert!(update_fail_htlcs.is_empty());
1271                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1272                                 assert!(update_fail_malformed_htlcs.is_empty());
1273                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1274                         },
1275                         _ => panic!("Unexpected event"),
1276                 }
1277         }
1278 }
1279
1280 #[test]
1281 fn test_basic_channel_reserve() {
1282         let chanmon_cfgs = create_chanmon_cfgs(2);
1283         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1284         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1285         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1286         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1287
1288         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1289         let channel_reserve = chan_stat.channel_reserve_msat;
1290
1291         // The 2* and +1 are for the fee spike reserve.
1292         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1293         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1294         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1295         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1296         match err {
1297                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1298                         match &fails[0] {
1299                                 &APIError::ChannelUnavailable{ref err} =>
1300                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1301                                 _ => panic!("Unexpected error variant"),
1302                         }
1303                 },
1304                 _ => panic!("Unexpected error variant"),
1305         }
1306         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1307         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);
1308
1309         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1310 }
1311
1312 #[test]
1313 fn test_fee_spike_violation_fails_htlc() {
1314         let chanmon_cfgs = create_chanmon_cfgs(2);
1315         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1316         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1317         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1318         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1319
1320         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1321         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1322         let secp_ctx = Secp256k1::new();
1323         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1324
1325         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1326
1327         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1328         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1329         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1330         let msg = msgs::UpdateAddHTLC {
1331                 channel_id: chan.2,
1332                 htlc_id: 0,
1333                 amount_msat: htlc_msat,
1334                 payment_hash: payment_hash,
1335                 cltv_expiry: htlc_cltv,
1336                 onion_routing_packet: onion_packet,
1337         };
1338
1339         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1340
1341         // Now manually create the commitment_signed message corresponding to the update_add
1342         // nodes[0] just sent. In the code for construction of this message, "local" refers
1343         // to the sender of the message, and "remote" refers to the receiver.
1344
1345         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1346
1347         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1348
1349         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1350         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1351         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1352                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1353                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1354                 let chan_signer = local_chan.get_signer();
1355                 // Make the signer believe we validated another commitment, so we can release the secret
1356                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1357
1358                 let pubkeys = chan_signer.pubkeys();
1359                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1360                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1361                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1362                  chan_signer.pubkeys().funding_pubkey)
1363         };
1364         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1365                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1366                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1367                 let chan_signer = remote_chan.get_signer();
1368                 let pubkeys = chan_signer.pubkeys();
1369                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1370                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1371                  chan_signer.pubkeys().funding_pubkey)
1372         };
1373
1374         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1375         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1376                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1377
1378         // Build the remote commitment transaction so we can sign it, and then later use the
1379         // signature for the commitment_signed message.
1380         let local_chan_balance = 1313;
1381
1382         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1383                 offered: false,
1384                 amount_msat: 3460001,
1385                 cltv_expiry: htlc_cltv,
1386                 payment_hash,
1387                 transaction_output_index: Some(1),
1388         };
1389
1390         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1391
1392         let res = {
1393                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1394                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1395                 let local_chan_signer = local_chan.get_signer();
1396                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1397                         commitment_number,
1398                         95000,
1399                         local_chan_balance,
1400                         false, local_funding, remote_funding,
1401                         commit_tx_keys.clone(),
1402                         feerate_per_kw,
1403                         &mut vec![(accepted_htlc_info, ())],
1404                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1405                 );
1406                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1407         };
1408
1409         let commit_signed_msg = msgs::CommitmentSigned {
1410                 channel_id: chan.2,
1411                 signature: res.0,
1412                 htlc_signatures: res.1
1413         };
1414
1415         // Send the commitment_signed message to the nodes[1].
1416         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1417         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1418
1419         // Send the RAA to nodes[1].
1420         let raa_msg = msgs::RevokeAndACK {
1421                 channel_id: chan.2,
1422                 per_commitment_secret: local_secret,
1423                 next_per_commitment_point: next_local_point
1424         };
1425         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1426
1427         let events = nodes[1].node.get_and_clear_pending_msg_events();
1428         assert_eq!(events.len(), 1);
1429         // Make sure the HTLC failed in the way we expect.
1430         match events[0] {
1431                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1432                         assert_eq!(update_fail_htlcs.len(), 1);
1433                         update_fail_htlcs[0].clone()
1434                 },
1435                 _ => panic!("Unexpected event"),
1436         };
1437         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1438                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1439
1440         check_added_monitors!(nodes[1], 2);
1441 }
1442
1443 #[test]
1444 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1445         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1446         // Set the fee rate for the channel very high, to the point where the fundee
1447         // sending any above-dust amount would result in a channel reserve violation.
1448         // In this test we check that we would be prevented from sending an HTLC in
1449         // this situation.
1450         let feerate_per_kw = 253;
1451         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1452         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1453         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1454         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1455         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1456
1457         let mut push_amt = 100_000_000;
1458         push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT + COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
1459         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1460
1461         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1462
1463         // Sending exactly enough to hit the reserve amount should be accepted
1464         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1465
1466         // However one more HTLC should be significantly over the reserve amount and fail.
1467         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1468         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1469                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1470         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1471         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);
1472 }
1473
1474 #[test]
1475 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1476         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1477         // Set the fee rate for the channel very high, to the point where the funder
1478         // receiving 1 update_add_htlc would result in them closing the channel due
1479         // to channel reserve violation. This close could also happen if the fee went
1480         // up a more realistic amount, but many HTLCs were outstanding at the time of
1481         // the update_add_htlc.
1482         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1483         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1484         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1485         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1486         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1487         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1488
1489         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1490         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1491         let secp_ctx = Secp256k1::new();
1492         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1493         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1494         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1495         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &Some(payment_secret), cur_height, &None).unwrap();
1496         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1497         let msg = msgs::UpdateAddHTLC {
1498                 channel_id: chan.2,
1499                 htlc_id: 1,
1500                 amount_msat: htlc_msat + 1,
1501                 payment_hash: payment_hash,
1502                 cltv_expiry: htlc_cltv,
1503                 onion_routing_packet: onion_packet,
1504         };
1505
1506         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1507         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1508         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);
1509         assert_eq!(nodes[0].node.list_channels().len(), 0);
1510         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1511         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1512         check_added_monitors!(nodes[0], 1);
1513         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() });
1514 }
1515
1516 #[test]
1517 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1518         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1519         // calculating our commitment transaction fee (this was previously broken).
1520         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1521         let feerate_per_kw = 253;
1522         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1523         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1524
1525         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1526         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1527         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1528
1529         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1530         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1531         // transaction fee with 0 HTLCs (183 sats)).
1532         let mut push_amt = 100_000_000;
1533         push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT) / 1000 * 1000;
1534         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1535         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1536
1537         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1538                 + feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000 * 1000 - 1;
1539         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1540         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1541         // commitment transaction fee.
1542         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1543
1544         // One more than the dust amt should fail, however.
1545         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1546         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1547                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1548 }
1549
1550 #[test]
1551 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1552         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1553         // calculating our counterparty's commitment transaction fee (this was previously broken).
1554         let chanmon_cfgs = create_chanmon_cfgs(2);
1555         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1556         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1557         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1558         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1559
1560         let payment_amt = 46000; // Dust amount
1561         // In the previous code, these first four payments would succeed.
1562         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1563         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1564         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1565         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1566
1567         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1568         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1569         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1570         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1571         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1572         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1573
1574         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1575         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1576         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1577         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1578 }
1579
1580 #[test]
1581 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1582         let chanmon_cfgs = create_chanmon_cfgs(3);
1583         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1584         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1585         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1586         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1587         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1588
1589         let feemsat = 239;
1590         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1591         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1592         let feerate = get_feerate!(nodes[0], chan.2);
1593
1594         // Add a 2* and +1 for the fee spike reserve.
1595         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1596         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;
1597         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1598
1599         // Add a pending HTLC.
1600         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1601         let payment_event_1 = {
1602                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1603                 check_added_monitors!(nodes[0], 1);
1604
1605                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1606                 assert_eq!(events.len(), 1);
1607                 SendEvent::from_event(events.remove(0))
1608         };
1609         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1610
1611         // Attempt to trigger a channel reserve violation --> payment failure.
1612         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1613         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;
1614         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1615         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1616
1617         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1618         let secp_ctx = Secp256k1::new();
1619         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1620         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1621         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1622         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1623         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1624         let msg = msgs::UpdateAddHTLC {
1625                 channel_id: chan.2,
1626                 htlc_id: 1,
1627                 amount_msat: htlc_msat + 1,
1628                 payment_hash: our_payment_hash_1,
1629                 cltv_expiry: htlc_cltv,
1630                 onion_routing_packet: onion_packet,
1631         };
1632
1633         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1634         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1635         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1636         assert_eq!(nodes[1].node.list_channels().len(), 1);
1637         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1638         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1639         check_added_monitors!(nodes[1], 1);
1640         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1641 }
1642
1643 #[test]
1644 fn test_inbound_outbound_capacity_is_not_zero() {
1645         let chanmon_cfgs = create_chanmon_cfgs(2);
1646         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1647         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1648         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1649         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1650         let channels0 = node_chanmgrs[0].list_channels();
1651         let channels1 = node_chanmgrs[1].list_channels();
1652         assert_eq!(channels0.len(), 1);
1653         assert_eq!(channels1.len(), 1);
1654
1655         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1656         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1657         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1658
1659         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1660         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1661 }
1662
1663 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1664         (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1665 }
1666
1667 #[test]
1668 fn test_channel_reserve_holding_cell_htlcs() {
1669         let chanmon_cfgs = create_chanmon_cfgs(3);
1670         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1671         // When this test was written, the default base fee floated based on the HTLC count.
1672         // It is now fixed, so we simply set the fee to the expected value here.
1673         let mut config = test_default_channel_config();
1674         config.channel_options.forwarding_fee_base_msat = 239;
1675         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1676         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1677         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1678         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1679
1680         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1681         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1682
1683         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1684         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1685
1686         macro_rules! expect_forward {
1687                 ($node: expr) => {{
1688                         let mut events = $node.node.get_and_clear_pending_msg_events();
1689                         assert_eq!(events.len(), 1);
1690                         check_added_monitors!($node, 1);
1691                         let payment_event = SendEvent::from_event(events.remove(0));
1692                         payment_event
1693                 }}
1694         }
1695
1696         let feemsat = 239; // set above
1697         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1698         let feerate = get_feerate!(nodes[0], chan_1.2);
1699
1700         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1701
1702         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1703         {
1704                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1705                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1706                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1707                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1708                         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)));
1709                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1710                 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);
1711         }
1712
1713         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1714         // nodes[0]'s wealth
1715         loop {
1716                 let amt_msat = recv_value_0 + total_fee_msat;
1717                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1718                 // Also, ensure that each payment has enough to be over the dust limit to
1719                 // ensure it'll be included in each commit tx fee calculation.
1720                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1721                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1722                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1723                         break;
1724                 }
1725                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1726
1727                 let (stat01_, stat11_, stat12_, stat22_) = (
1728                         get_channel_value_stat!(nodes[0], chan_1.2),
1729                         get_channel_value_stat!(nodes[1], chan_1.2),
1730                         get_channel_value_stat!(nodes[1], chan_2.2),
1731                         get_channel_value_stat!(nodes[2], chan_2.2),
1732                 );
1733
1734                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1735                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1736                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1737                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1738                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1739         }
1740
1741         // adding pending output.
1742         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1743         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1744         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1745         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1746         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1747         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1748         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1749         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1750         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1751         // policy.
1752         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
1753         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1754         let amt_msat_1 = recv_value_1 + total_fee_msat;
1755
1756         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);
1757         let payment_event_1 = {
1758                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1759                 check_added_monitors!(nodes[0], 1);
1760
1761                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1762                 assert_eq!(events.len(), 1);
1763                 SendEvent::from_event(events.remove(0))
1764         };
1765         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1766
1767         // channel reserve test with htlc pending output > 0
1768         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1769         {
1770                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1771                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1772                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1773                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1774         }
1775
1776         // split the rest to test holding cell
1777         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1778         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1779         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1780         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1781         {
1782                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1783                 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);
1784         }
1785
1786         // now see if they go through on both sides
1787         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);
1788         // but this will stuck in the holding cell
1789         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1790         check_added_monitors!(nodes[0], 0);
1791         let events = nodes[0].node.get_and_clear_pending_events();
1792         assert_eq!(events.len(), 0);
1793
1794         // test with outbound holding cell amount > 0
1795         {
1796                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1797                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1798                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1799                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1800                 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);
1801         }
1802
1803         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);
1804         // this will also stuck in the holding cell
1805         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1806         check_added_monitors!(nodes[0], 0);
1807         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1808         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1809
1810         // flush the pending htlc
1811         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1812         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1813         check_added_monitors!(nodes[1], 1);
1814
1815         // the pending htlc should be promoted to committed
1816         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1817         check_added_monitors!(nodes[0], 1);
1818         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1819
1820         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1821         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1822         // No commitment_signed so get_event_msg's assert(len == 1) passes
1823         check_added_monitors!(nodes[0], 1);
1824
1825         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1826         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1827         check_added_monitors!(nodes[1], 1);
1828
1829         expect_pending_htlcs_forwardable!(nodes[1]);
1830
1831         let ref payment_event_11 = expect_forward!(nodes[1]);
1832         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1833         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1834
1835         expect_pending_htlcs_forwardable!(nodes[2]);
1836         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1837
1838         // flush the htlcs in the holding cell
1839         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1840         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1841         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1842         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1843         expect_pending_htlcs_forwardable!(nodes[1]);
1844
1845         let ref payment_event_3 = expect_forward!(nodes[1]);
1846         assert_eq!(payment_event_3.msgs.len(), 2);
1847         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1848         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1849
1850         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1851         expect_pending_htlcs_forwardable!(nodes[2]);
1852
1853         let events = nodes[2].node.get_and_clear_pending_events();
1854         assert_eq!(events.len(), 2);
1855         match events[0] {
1856                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1857                         assert_eq!(our_payment_hash_21, *payment_hash);
1858                         assert_eq!(recv_value_21, amt);
1859                         match &purpose {
1860                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1861                                         assert!(payment_preimage.is_none());
1862                                         assert_eq!(our_payment_secret_21, *payment_secret);
1863                                 },
1864                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1865                         }
1866                 },
1867                 _ => panic!("Unexpected event"),
1868         }
1869         match events[1] {
1870                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1871                         assert_eq!(our_payment_hash_22, *payment_hash);
1872                         assert_eq!(recv_value_22, amt);
1873                         match &purpose {
1874                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1875                                         assert!(payment_preimage.is_none());
1876                                         assert_eq!(our_payment_secret_22, *payment_secret);
1877                                 },
1878                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1879                         }
1880                 },
1881                 _ => panic!("Unexpected event"),
1882         }
1883
1884         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1885         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1886         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1887
1888         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
1889         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1890         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1891
1892         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
1893         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);
1894         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1895         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1896         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1897
1898         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1899         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
1900 }
1901
1902 #[test]
1903 fn channel_reserve_in_flight_removes() {
1904         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1905         // can send to its counterparty, but due to update ordering, the other side may not yet have
1906         // considered those HTLCs fully removed.
1907         // This tests that we don't count HTLCs which will not be included in the next remote
1908         // commitment transaction towards the reserve value (as it implies no commitment transaction
1909         // will be generated which violates the remote reserve value).
1910         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1911         // To test this we:
1912         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1913         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1914         //    you only consider the value of the first HTLC, it may not),
1915         //  * start routing a third HTLC from A to B,
1916         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1917         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1918         //  * deliver the first fulfill from B
1919         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1920         //    claim,
1921         //  * deliver A's response CS and RAA.
1922         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1923         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
1924         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1925         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1926         let chanmon_cfgs = create_chanmon_cfgs(2);
1927         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1928         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1929         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1930         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1931
1932         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1933         // Route the first two HTLCs.
1934         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1935         let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1936
1937         // Start routing the third HTLC (this is just used to get everyone in the right state).
1938         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
1939         let send_1 = {
1940                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
1941                 check_added_monitors!(nodes[0], 1);
1942                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1943                 assert_eq!(events.len(), 1);
1944                 SendEvent::from_event(events.remove(0))
1945         };
1946
1947         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1948         // initial fulfill/CS.
1949         assert!(nodes[1].node.claim_funds(payment_preimage_1));
1950         check_added_monitors!(nodes[1], 1);
1951         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1952
1953         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1954         // remove the second HTLC when we send the HTLC back from B to A.
1955         assert!(nodes[1].node.claim_funds(payment_preimage_2));
1956         check_added_monitors!(nodes[1], 1);
1957         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1958
1959         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1960         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1961         check_added_monitors!(nodes[0], 1);
1962         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1963         expect_payment_sent!(nodes[0], payment_preimage_1);
1964
1965         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1966         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1967         check_added_monitors!(nodes[1], 1);
1968         // B is already AwaitingRAA, so cant generate a CS here
1969         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1970
1971         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1972         check_added_monitors!(nodes[1], 1);
1973         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1974
1975         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1976         check_added_monitors!(nodes[0], 1);
1977         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1978
1979         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1980         check_added_monitors!(nodes[1], 1);
1981         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1982
1983         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1984         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1985         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1986         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1987         // on-chain as necessary).
1988         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1989         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1990         check_added_monitors!(nodes[0], 1);
1991         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1992         expect_payment_sent!(nodes[0], payment_preimage_2);
1993
1994         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1995         check_added_monitors!(nodes[1], 1);
1996         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1997
1998         expect_pending_htlcs_forwardable!(nodes[1]);
1999         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2000
2001         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2002         // resolve the second HTLC from A's point of view.
2003         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2004         check_added_monitors!(nodes[0], 1);
2005         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2006
2007         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2008         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2009         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2010         let send_2 = {
2011                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2012                 check_added_monitors!(nodes[1], 1);
2013                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2014                 assert_eq!(events.len(), 1);
2015                 SendEvent::from_event(events.remove(0))
2016         };
2017
2018         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2019         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2020         check_added_monitors!(nodes[0], 1);
2021         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2022
2023         // Now just resolve all the outstanding messages/HTLCs for completeness...
2024
2025         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2026         check_added_monitors!(nodes[1], 1);
2027         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2028
2029         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2030         check_added_monitors!(nodes[1], 1);
2031
2032         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2033         check_added_monitors!(nodes[0], 1);
2034         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2035
2036         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2037         check_added_monitors!(nodes[1], 1);
2038         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2039
2040         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2041         check_added_monitors!(nodes[0], 1);
2042
2043         expect_pending_htlcs_forwardable!(nodes[0]);
2044         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2045
2046         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2047         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2048 }
2049
2050 #[test]
2051 fn channel_monitor_network_test() {
2052         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2053         // tests that ChannelMonitor is able to recover from various states.
2054         let chanmon_cfgs = create_chanmon_cfgs(5);
2055         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2056         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2057         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2058
2059         // Create some initial channels
2060         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2061         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2062         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2063         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2064
2065         // Make sure all nodes are at the same starting height
2066         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2067         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2068         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2069         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2070         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2071
2072         // Rebalance the network a bit by relaying one payment through all the channels...
2073         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2074         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2075         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2076         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2077
2078         // Simple case with no pending HTLCs:
2079         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2080         check_added_monitors!(nodes[1], 1);
2081         check_closed_broadcast!(nodes[1], false);
2082         {
2083                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2084                 assert_eq!(node_txn.len(), 1);
2085                 mine_transaction(&nodes[0], &node_txn[0]);
2086                 check_added_monitors!(nodes[0], 1);
2087                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2088         }
2089         check_closed_broadcast!(nodes[0], true);
2090         assert_eq!(nodes[0].node.list_channels().len(), 0);
2091         assert_eq!(nodes[1].node.list_channels().len(), 1);
2092         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2093         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2094
2095         // One pending HTLC is discarded by the force-close:
2096         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2097
2098         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2099         // broadcasted until we reach the timelock time).
2100         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2101         check_closed_broadcast!(nodes[1], false);
2102         check_added_monitors!(nodes[1], 1);
2103         {
2104                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2105                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2106                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2107                 mine_transaction(&nodes[2], &node_txn[0]);
2108                 check_added_monitors!(nodes[2], 1);
2109                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2110         }
2111         check_closed_broadcast!(nodes[2], true);
2112         assert_eq!(nodes[1].node.list_channels().len(), 0);
2113         assert_eq!(nodes[2].node.list_channels().len(), 1);
2114         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2115         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2116
2117         macro_rules! claim_funds {
2118                 ($node: expr, $prev_node: expr, $preimage: expr) => {
2119                         {
2120                                 assert!($node.node.claim_funds($preimage));
2121                                 check_added_monitors!($node, 1);
2122
2123                                 let events = $node.node.get_and_clear_pending_msg_events();
2124                                 assert_eq!(events.len(), 1);
2125                                 match events[0] {
2126                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2127                                                 assert!(update_add_htlcs.is_empty());
2128                                                 assert!(update_fail_htlcs.is_empty());
2129                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2130                                         },
2131                                         _ => panic!("Unexpected event"),
2132                                 };
2133                         }
2134                 }
2135         }
2136
2137         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2138         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2139         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2140         check_added_monitors!(nodes[2], 1);
2141         check_closed_broadcast!(nodes[2], false);
2142         let node2_commitment_txid;
2143         {
2144                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2145                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2146                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2147                 node2_commitment_txid = node_txn[0].txid();
2148
2149                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2150                 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2151                 mine_transaction(&nodes[3], &node_txn[0]);
2152                 check_added_monitors!(nodes[3], 1);
2153                 check_preimage_claim(&nodes[3], &node_txn);
2154         }
2155         check_closed_broadcast!(nodes[3], true);
2156         assert_eq!(nodes[2].node.list_channels().len(), 0);
2157         assert_eq!(nodes[3].node.list_channels().len(), 1);
2158         check_closed_event!(nodes[2], 1, ClosureReason::DisconnectedPeer);
2159         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2160
2161         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2162         // confusing us in the following tests.
2163         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2164
2165         // One pending HTLC to time out:
2166         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2167         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2168         // buffer space).
2169
2170         let (close_chan_update_1, close_chan_update_2) = {
2171                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2172                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2173                 assert_eq!(events.len(), 2);
2174                 let close_chan_update_1 = match events[0] {
2175                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2176                                 msg.clone()
2177                         },
2178                         _ => panic!("Unexpected event"),
2179                 };
2180                 match events[1] {
2181                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2182                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2183                         },
2184                         _ => panic!("Unexpected event"),
2185                 }
2186                 check_added_monitors!(nodes[3], 1);
2187
2188                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2189                 {
2190                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2191                         node_txn.retain(|tx| {
2192                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2193                                         false
2194                                 } else { true }
2195                         });
2196                 }
2197
2198                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2199
2200                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2201                 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2202
2203                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2204                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2205                 assert_eq!(events.len(), 2);
2206                 let close_chan_update_2 = match events[0] {
2207                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2208                                 msg.clone()
2209                         },
2210                         _ => panic!("Unexpected event"),
2211                 };
2212                 match events[1] {
2213                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2214                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2215                         },
2216                         _ => panic!("Unexpected event"),
2217                 }
2218                 check_added_monitors!(nodes[4], 1);
2219                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2220
2221                 mine_transaction(&nodes[4], &node_txn[0]);
2222                 check_preimage_claim(&nodes[4], &node_txn);
2223                 (close_chan_update_1, close_chan_update_2)
2224         };
2225         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2226         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2227         assert_eq!(nodes[3].node.list_channels().len(), 0);
2228         assert_eq!(nodes[4].node.list_channels().len(), 0);
2229
2230         nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2231         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2232         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2233 }
2234
2235 #[test]
2236 fn test_justice_tx() {
2237         // Test justice txn built on revoked HTLC-Success tx, against both sides
2238         let mut alice_config = UserConfig::default();
2239         alice_config.channel_options.announced_channel = true;
2240         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2241         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2242         let mut bob_config = UserConfig::default();
2243         bob_config.channel_options.announced_channel = true;
2244         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2245         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2246         let user_cfgs = [Some(alice_config), Some(bob_config)];
2247         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2248         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2249         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2250         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2251         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2252         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2253         // Create some new channels:
2254         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2255
2256         // A pending HTLC which will be revoked:
2257         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2258         // Get the will-be-revoked local txn from nodes[0]
2259         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2260         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2261         assert_eq!(revoked_local_txn[0].input.len(), 1);
2262         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2263         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2264         assert_eq!(revoked_local_txn[1].input.len(), 1);
2265         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2266         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2267         // Revoke the old state
2268         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2269
2270         {
2271                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2272                 {
2273                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2274                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2275                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2276
2277                         check_spends!(node_txn[0], revoked_local_txn[0]);
2278                         node_txn.swap_remove(0);
2279                         node_txn.truncate(1);
2280                 }
2281                 check_added_monitors!(nodes[1], 1);
2282                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2283                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2284
2285                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2286                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2287                 // Verify broadcast of revoked HTLC-timeout
2288                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2289                 check_added_monitors!(nodes[0], 1);
2290                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2291                 // Broadcast revoked HTLC-timeout on node 1
2292                 mine_transaction(&nodes[1], &node_txn[1]);
2293                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2294         }
2295         get_announce_close_broadcast_events(&nodes, 0, 1);
2296
2297         assert_eq!(nodes[0].node.list_channels().len(), 0);
2298         assert_eq!(nodes[1].node.list_channels().len(), 0);
2299
2300         // We test justice_tx build by A on B's revoked HTLC-Success tx
2301         // Create some new channels:
2302         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2303         {
2304                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2305                 node_txn.clear();
2306         }
2307
2308         // A pending HTLC which will be revoked:
2309         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2310         // Get the will-be-revoked local txn from B
2311         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2312         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2313         assert_eq!(revoked_local_txn[0].input.len(), 1);
2314         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2315         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2316         // Revoke the old state
2317         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2318         {
2319                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2320                 {
2321                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2322                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2323                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2324
2325                         check_spends!(node_txn[0], revoked_local_txn[0]);
2326                         node_txn.swap_remove(0);
2327                 }
2328                 check_added_monitors!(nodes[0], 1);
2329                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2330
2331                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2332                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2333                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2334                 check_added_monitors!(nodes[1], 1);
2335                 mine_transaction(&nodes[0], &node_txn[1]);
2336                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2337                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2338         }
2339         get_announce_close_broadcast_events(&nodes, 0, 1);
2340         assert_eq!(nodes[0].node.list_channels().len(), 0);
2341         assert_eq!(nodes[1].node.list_channels().len(), 0);
2342 }
2343
2344 #[test]
2345 fn revoked_output_claim() {
2346         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2347         // transaction is broadcast by its counterparty
2348         let chanmon_cfgs = create_chanmon_cfgs(2);
2349         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2350         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2351         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2352         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2353         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2354         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2355         assert_eq!(revoked_local_txn.len(), 1);
2356         // Only output is the full channel value back to nodes[0]:
2357         assert_eq!(revoked_local_txn[0].output.len(), 1);
2358         // Send a payment through, updating everyone's latest commitment txn
2359         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2360
2361         // Inform nodes[1] that nodes[0] broadcast a stale tx
2362         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2363         check_added_monitors!(nodes[1], 1);
2364         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2365         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2366         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2367
2368         check_spends!(node_txn[0], revoked_local_txn[0]);
2369         check_spends!(node_txn[1], chan_1.3);
2370
2371         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2372         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2373         get_announce_close_broadcast_events(&nodes, 0, 1);
2374         check_added_monitors!(nodes[0], 1);
2375         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2376 }
2377
2378 #[test]
2379 fn claim_htlc_outputs_shared_tx() {
2380         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2381         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2382         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2383         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2384         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2385         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2386
2387         // Create some new channel:
2388         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2389
2390         // Rebalance the network to generate htlc in the two directions
2391         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2392         // 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
2393         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2394         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2395
2396         // Get the will-be-revoked local txn from node[0]
2397         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2398         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2399         assert_eq!(revoked_local_txn[0].input.len(), 1);
2400         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2401         assert_eq!(revoked_local_txn[1].input.len(), 1);
2402         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2403         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2404         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2405
2406         //Revoke the old state
2407         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2408
2409         {
2410                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2411                 check_added_monitors!(nodes[0], 1);
2412                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2413                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2414                 check_added_monitors!(nodes[1], 1);
2415                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2416                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2417                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2418
2419                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2420                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2421
2422                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2423                 check_spends!(node_txn[0], revoked_local_txn[0]);
2424
2425                 let mut witness_lens = BTreeSet::new();
2426                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2427                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2428                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2429                 assert_eq!(witness_lens.len(), 3);
2430                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2431                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2432                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2433
2434                 // Next nodes[1] broadcasts its current local tx state:
2435                 assert_eq!(node_txn[1].input.len(), 1);
2436                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2437         }
2438         get_announce_close_broadcast_events(&nodes, 0, 1);
2439         assert_eq!(nodes[0].node.list_channels().len(), 0);
2440         assert_eq!(nodes[1].node.list_channels().len(), 0);
2441 }
2442
2443 #[test]
2444 fn claim_htlc_outputs_single_tx() {
2445         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2446         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2447         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2448         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2449         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2450         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2451
2452         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2453
2454         // Rebalance the network to generate htlc in the two directions
2455         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2456         // 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
2457         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2458         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2459         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2460
2461         // Get the will-be-revoked local txn from node[0]
2462         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2463
2464         //Revoke the old state
2465         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2466
2467         {
2468                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2469                 check_added_monitors!(nodes[0], 1);
2470                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2471                 check_added_monitors!(nodes[1], 1);
2472                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2473                 let mut events = nodes[0].node.get_and_clear_pending_events();
2474                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2475                 match events[1] {
2476                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2477                         _ => panic!("Unexpected event"),
2478                 }
2479
2480                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2481                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2482
2483                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2484                 assert_eq!(node_txn.len(), 9);
2485                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2486                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2487                 // 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)
2488                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2489
2490                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2491                 assert_eq!(node_txn[0].input.len(), 1);
2492                 check_spends!(node_txn[0], chan_1.3);
2493                 assert_eq!(node_txn[1].input.len(), 1);
2494                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2495                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2496                 check_spends!(node_txn[1], node_txn[0]);
2497
2498                 // Justice transactions are indices 1-2-4
2499                 assert_eq!(node_txn[2].input.len(), 1);
2500                 assert_eq!(node_txn[3].input.len(), 1);
2501                 assert_eq!(node_txn[4].input.len(), 1);
2502
2503                 check_spends!(node_txn[2], revoked_local_txn[0]);
2504                 check_spends!(node_txn[3], revoked_local_txn[0]);
2505                 check_spends!(node_txn[4], revoked_local_txn[0]);
2506
2507                 let mut witness_lens = BTreeSet::new();
2508                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2509                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2510                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2511                 assert_eq!(witness_lens.len(), 3);
2512                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2513                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2514                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2515         }
2516         get_announce_close_broadcast_events(&nodes, 0, 1);
2517         assert_eq!(nodes[0].node.list_channels().len(), 0);
2518         assert_eq!(nodes[1].node.list_channels().len(), 0);
2519 }
2520
2521 #[test]
2522 fn test_htlc_on_chain_success() {
2523         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2524         // the preimage backward accordingly. So here we test that ChannelManager is
2525         // broadcasting the right event to other nodes in payment path.
2526         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2527         // A --------------------> B ----------------------> C (preimage)
2528         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2529         // commitment transaction was broadcast.
2530         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2531         // towards B.
2532         // B should be able to claim via preimage if A then broadcasts its local tx.
2533         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2534         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2535         // PaymentSent event).
2536
2537         let chanmon_cfgs = create_chanmon_cfgs(3);
2538         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2539         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2540         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2541
2542         // Create some initial channels
2543         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2544         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2545
2546         // Ensure all nodes are at the same height
2547         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2548         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2549         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2550         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2551
2552         // Rebalance the network a bit by relaying one payment through all the channels...
2553         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2554         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2555
2556         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2557         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2558
2559         // Broadcast legit commitment tx from C on B's chain
2560         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2561         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2562         assert_eq!(commitment_tx.len(), 1);
2563         check_spends!(commitment_tx[0], chan_2.3);
2564         nodes[2].node.claim_funds(our_payment_preimage);
2565         nodes[2].node.claim_funds(our_payment_preimage_2);
2566         check_added_monitors!(nodes[2], 2);
2567         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2568         assert!(updates.update_add_htlcs.is_empty());
2569         assert!(updates.update_fail_htlcs.is_empty());
2570         assert!(updates.update_fail_malformed_htlcs.is_empty());
2571         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2572
2573         mine_transaction(&nodes[2], &commitment_tx[0]);
2574         check_closed_broadcast!(nodes[2], true);
2575         check_added_monitors!(nodes[2], 1);
2576         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2577         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)
2578         assert_eq!(node_txn.len(), 5);
2579         assert_eq!(node_txn[0], node_txn[3]);
2580         assert_eq!(node_txn[1], node_txn[4]);
2581         assert_eq!(node_txn[2], commitment_tx[0]);
2582         check_spends!(node_txn[0], commitment_tx[0]);
2583         check_spends!(node_txn[1], commitment_tx[0]);
2584         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2585         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2586         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2587         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2588         assert_eq!(node_txn[0].lock_time, 0);
2589         assert_eq!(node_txn[1].lock_time, 0);
2590
2591         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2592         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2593         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2594         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2595         {
2596                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2597                 assert_eq!(added_monitors.len(), 1);
2598                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2599                 added_monitors.clear();
2600         }
2601         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2602         assert_eq!(forwarded_events.len(), 3);
2603         match forwarded_events[0] {
2604                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2605                 _ => panic!("Unexpected event"),
2606         }
2607         if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[1] {
2608                 } else { panic!(); }
2609         if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[2] {
2610                 } else { panic!(); }
2611         let events = nodes[1].node.get_and_clear_pending_msg_events();
2612         {
2613                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2614                 assert_eq!(added_monitors.len(), 2);
2615                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2616                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2617                 added_monitors.clear();
2618         }
2619         assert_eq!(events.len(), 3);
2620         match events[0] {
2621                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2622                 _ => panic!("Unexpected event"),
2623         }
2624         match events[1] {
2625                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2626                 _ => panic!("Unexpected event"),
2627         }
2628
2629         match events[2] {
2630                 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, .. } } => {
2631                         assert!(update_add_htlcs.is_empty());
2632                         assert!(update_fail_htlcs.is_empty());
2633                         assert_eq!(update_fulfill_htlcs.len(), 1);
2634                         assert!(update_fail_malformed_htlcs.is_empty());
2635                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2636                 },
2637                 _ => panic!("Unexpected event"),
2638         };
2639         macro_rules! check_tx_local_broadcast {
2640                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2641                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2642                         assert_eq!(node_txn.len(), 3);
2643                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2644                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2645                         check_spends!(node_txn[1], $commitment_tx);
2646                         check_spends!(node_txn[2], $commitment_tx);
2647                         assert_ne!(node_txn[1].lock_time, 0);
2648                         assert_ne!(node_txn[2].lock_time, 0);
2649                         if $htlc_offered {
2650                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2651                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2652                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2653                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2654                         } else {
2655                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2656                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2657                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2658                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2659                         }
2660                         check_spends!(node_txn[0], $chan_tx);
2661                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2662                         node_txn.clear();
2663                 } }
2664         }
2665         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2666         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2667         // timeout-claim of the output that nodes[2] just claimed via success.
2668         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2669
2670         // Broadcast legit commitment tx from A on B's chain
2671         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2672         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2673         check_spends!(node_a_commitment_tx[0], chan_1.3);
2674         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2675         check_closed_broadcast!(nodes[1], true);
2676         check_added_monitors!(nodes[1], 1);
2677         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2678         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2679         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2680         let commitment_spend =
2681                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2682                         check_spends!(node_txn[1], commitment_tx[0]);
2683                         check_spends!(node_txn[2], commitment_tx[0]);
2684                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2685                         &node_txn[0]
2686                 } else {
2687                         check_spends!(node_txn[0], commitment_tx[0]);
2688                         check_spends!(node_txn[1], commitment_tx[0]);
2689                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2690                         &node_txn[2]
2691                 };
2692
2693         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2694         assert_eq!(commitment_spend.input.len(), 2);
2695         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2696         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2697         assert_eq!(commitment_spend.lock_time, 0);
2698         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2699         check_spends!(node_txn[3], chan_1.3);
2700         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2701         check_spends!(node_txn[4], node_txn[3]);
2702         check_spends!(node_txn[5], node_txn[3]);
2703         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2704         // we already checked the same situation with A.
2705
2706         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2707         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2708         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2709         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2710         check_closed_broadcast!(nodes[0], true);
2711         check_added_monitors!(nodes[0], 1);
2712         let events = nodes[0].node.get_and_clear_pending_events();
2713         assert_eq!(events.len(), 3);
2714         let mut first_claimed = false;
2715         for event in events {
2716                 match event {
2717                         Event::PaymentSent { payment_preimage, payment_hash } => {
2718                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2719                                         assert!(!first_claimed);
2720                                         first_claimed = true;
2721                                 } else {
2722                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2723                                         assert_eq!(payment_hash, payment_hash_2);
2724                                 }
2725                         },
2726                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2727                         _ => panic!("Unexpected event"),
2728                 }
2729         }
2730         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2731 }
2732
2733 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2734         // Test that in case of a unilateral close onchain, we detect the state of output and
2735         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2736         // broadcasting the right event to other nodes in payment path.
2737         // A ------------------> B ----------------------> C (timeout)
2738         //    B's commitment tx                 C's commitment tx
2739         //            \                                  \
2740         //         B's HTLC timeout tx               B's timeout tx
2741
2742         let chanmon_cfgs = create_chanmon_cfgs(3);
2743         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2744         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2745         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2746         *nodes[0].connect_style.borrow_mut() = connect_style;
2747         *nodes[1].connect_style.borrow_mut() = connect_style;
2748         *nodes[2].connect_style.borrow_mut() = connect_style;
2749
2750         // Create some intial channels
2751         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2752         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2753
2754         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2755         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2756         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2757
2758         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2759
2760         // Broadcast legit commitment tx from C on B's chain
2761         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2762         check_spends!(commitment_tx[0], chan_2.3);
2763         nodes[2].node.fail_htlc_backwards(&payment_hash);
2764         check_added_monitors!(nodes[2], 0);
2765         expect_pending_htlcs_forwardable!(nodes[2]);
2766         check_added_monitors!(nodes[2], 1);
2767
2768         let events = nodes[2].node.get_and_clear_pending_msg_events();
2769         assert_eq!(events.len(), 1);
2770         match events[0] {
2771                 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, .. } } => {
2772                         assert!(update_add_htlcs.is_empty());
2773                         assert!(!update_fail_htlcs.is_empty());
2774                         assert!(update_fulfill_htlcs.is_empty());
2775                         assert!(update_fail_malformed_htlcs.is_empty());
2776                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2777                 },
2778                 _ => panic!("Unexpected event"),
2779         };
2780         mine_transaction(&nodes[2], &commitment_tx[0]);
2781         check_closed_broadcast!(nodes[2], true);
2782         check_added_monitors!(nodes[2], 1);
2783         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2784         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2785         assert_eq!(node_txn.len(), 1);
2786         check_spends!(node_txn[0], chan_2.3);
2787         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2788
2789         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2790         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2791         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2792         mine_transaction(&nodes[1], &commitment_tx[0]);
2793         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2794         let timeout_tx;
2795         {
2796                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2797                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2798                 assert_eq!(node_txn[0], node_txn[3]);
2799                 assert_eq!(node_txn[1], node_txn[4]);
2800
2801                 check_spends!(node_txn[2], commitment_tx[0]);
2802                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2803
2804                 check_spends!(node_txn[0], chan_2.3);
2805                 check_spends!(node_txn[1], node_txn[0]);
2806                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2807                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2808
2809                 timeout_tx = node_txn[2].clone();
2810                 node_txn.clear();
2811         }
2812
2813         mine_transaction(&nodes[1], &timeout_tx);
2814         check_added_monitors!(nodes[1], 1);
2815         check_closed_broadcast!(nodes[1], true);
2816         {
2817                 // B will rebroadcast a fee-bumped timeout transaction here.
2818                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2819                 assert_eq!(node_txn.len(), 1);
2820                 check_spends!(node_txn[0], commitment_tx[0]);
2821         }
2822
2823         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2824         {
2825                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2826                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2827                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2828                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2829                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2830                 if node_txn.len() == 1 {
2831                         check_spends!(node_txn[0], chan_2.3);
2832                 } else {
2833                         assert_eq!(node_txn.len(), 0);
2834                 }
2835         }
2836
2837         expect_pending_htlcs_forwardable!(nodes[1]);
2838         check_added_monitors!(nodes[1], 1);
2839         let events = nodes[1].node.get_and_clear_pending_msg_events();
2840         assert_eq!(events.len(), 1);
2841         match events[0] {
2842                 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, .. } } => {
2843                         assert!(update_add_htlcs.is_empty());
2844                         assert!(!update_fail_htlcs.is_empty());
2845                         assert!(update_fulfill_htlcs.is_empty());
2846                         assert!(update_fail_malformed_htlcs.is_empty());
2847                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2848                 },
2849                 _ => panic!("Unexpected event"),
2850         };
2851
2852         // Broadcast legit commitment tx from B on A's chain
2853         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2854         check_spends!(commitment_tx[0], chan_1.3);
2855
2856         mine_transaction(&nodes[0], &commitment_tx[0]);
2857         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2858
2859         check_closed_broadcast!(nodes[0], true);
2860         check_added_monitors!(nodes[0], 1);
2861         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2862         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2863         assert_eq!(node_txn.len(), 2);
2864         check_spends!(node_txn[0], chan_1.3);
2865         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2866         check_spends!(node_txn[1], commitment_tx[0]);
2867         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2868 }
2869
2870 #[test]
2871 fn test_htlc_on_chain_timeout() {
2872         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2873         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2874         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2875 }
2876
2877 #[test]
2878 fn test_simple_commitment_revoked_fail_backward() {
2879         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2880         // and fail backward accordingly.
2881
2882         let chanmon_cfgs = create_chanmon_cfgs(3);
2883         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2884         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2885         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2886
2887         // Create some initial channels
2888         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2889         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2890
2891         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2892         // Get the will-be-revoked local txn from nodes[2]
2893         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2894         // Revoke the old state
2895         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2896
2897         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2898
2899         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2900         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2901         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2902         check_added_monitors!(nodes[1], 1);
2903         check_closed_broadcast!(nodes[1], true);
2904
2905         expect_pending_htlcs_forwardable!(nodes[1]);
2906         check_added_monitors!(nodes[1], 1);
2907         let events = nodes[1].node.get_and_clear_pending_msg_events();
2908         assert_eq!(events.len(), 1);
2909         match events[0] {
2910                 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, .. } } => {
2911                         assert!(update_add_htlcs.is_empty());
2912                         assert_eq!(update_fail_htlcs.len(), 1);
2913                         assert!(update_fulfill_htlcs.is_empty());
2914                         assert!(update_fail_malformed_htlcs.is_empty());
2915                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2916
2917                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2918                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2919                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
2920                 },
2921                 _ => panic!("Unexpected event"),
2922         }
2923 }
2924
2925 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2926         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2927         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2928         // commitment transaction anymore.
2929         // To do this, we have the peer which will broadcast a revoked commitment transaction send
2930         // a number of update_fail/commitment_signed updates without ever sending the RAA in
2931         // response to our commitment_signed. This is somewhat misbehavior-y, though not
2932         // technically disallowed and we should probably handle it reasonably.
2933         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2934         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2935         // transactions:
2936         // * Once we move it out of our holding cell/add it, we will immediately include it in a
2937         //   commitment_signed (implying it will be in the latest remote commitment transaction).
2938         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2939         //   and once they revoke the previous commitment transaction (allowing us to send a new
2940         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2941         let chanmon_cfgs = create_chanmon_cfgs(3);
2942         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2943         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2944         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2945
2946         // Create some initial channels
2947         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2948         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2949
2950         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 });
2951         // Get the will-be-revoked local txn from nodes[2]
2952         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2953         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2954         // Revoke the old state
2955         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2956
2957         let value = if use_dust {
2958                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2959                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2960                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
2961         } else { 3000000 };
2962
2963         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2964         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2965         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2966
2967         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2968         expect_pending_htlcs_forwardable!(nodes[2]);
2969         check_added_monitors!(nodes[2], 1);
2970         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2971         assert!(updates.update_add_htlcs.is_empty());
2972         assert!(updates.update_fulfill_htlcs.is_empty());
2973         assert!(updates.update_fail_malformed_htlcs.is_empty());
2974         assert_eq!(updates.update_fail_htlcs.len(), 1);
2975         assert!(updates.update_fee.is_none());
2976         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2977         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2978         // Drop the last RAA from 3 -> 2
2979
2980         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2981         expect_pending_htlcs_forwardable!(nodes[2]);
2982         check_added_monitors!(nodes[2], 1);
2983         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2984         assert!(updates.update_add_htlcs.is_empty());
2985         assert!(updates.update_fulfill_htlcs.is_empty());
2986         assert!(updates.update_fail_malformed_htlcs.is_empty());
2987         assert_eq!(updates.update_fail_htlcs.len(), 1);
2988         assert!(updates.update_fee.is_none());
2989         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2990         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2991         check_added_monitors!(nodes[1], 1);
2992         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2993         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2994         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2995         check_added_monitors!(nodes[2], 1);
2996
2997         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
2998         expect_pending_htlcs_forwardable!(nodes[2]);
2999         check_added_monitors!(nodes[2], 1);
3000         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3001         assert!(updates.update_add_htlcs.is_empty());
3002         assert!(updates.update_fulfill_htlcs.is_empty());
3003         assert!(updates.update_fail_malformed_htlcs.is_empty());
3004         assert_eq!(updates.update_fail_htlcs.len(), 1);
3005         assert!(updates.update_fee.is_none());
3006         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3007         // At this point first_payment_hash has dropped out of the latest two commitment
3008         // transactions that nodes[1] is tracking...
3009         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3010         check_added_monitors!(nodes[1], 1);
3011         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3012         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3013         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3014         check_added_monitors!(nodes[2], 1);
3015
3016         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3017         // on nodes[2]'s RAA.
3018         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3019         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3020         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3021         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3022         check_added_monitors!(nodes[1], 0);
3023
3024         if deliver_bs_raa {
3025                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3026                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3027                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3028                 check_added_monitors!(nodes[1], 1);
3029                 let events = nodes[1].node.get_and_clear_pending_events();
3030                 assert_eq!(events.len(), 1);
3031                 match events[0] {
3032                         Event::PendingHTLCsForwardable { .. } => { },
3033                         _ => panic!("Unexpected event"),
3034                 };
3035                 // Deliberately don't process the pending fail-back so they all fail back at once after
3036                 // block connection just like the !deliver_bs_raa case
3037         }
3038
3039         let mut failed_htlcs = HashSet::new();
3040         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3041
3042         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3043         check_added_monitors!(nodes[1], 1);
3044         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3045
3046         let events = nodes[1].node.get_and_clear_pending_events();
3047         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3048         match events[0] {
3049                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3050                 _ => panic!("Unexepected event"),
3051         }
3052         match events[1] {
3053                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3054                         assert_eq!(*payment_hash, fourth_payment_hash);
3055                 },
3056                 _ => panic!("Unexpected event"),
3057         }
3058         if !deliver_bs_raa {
3059                 match events[2] {
3060                         Event::PendingHTLCsForwardable { .. } => { },
3061                         _ => panic!("Unexpected event"),
3062                 };
3063         }
3064         nodes[1].node.process_pending_htlc_forwards();
3065         check_added_monitors!(nodes[1], 1);
3066
3067         let events = nodes[1].node.get_and_clear_pending_msg_events();
3068         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3069         match events[if deliver_bs_raa { 1 } else { 0 }] {
3070                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3071                 _ => panic!("Unexpected event"),
3072         }
3073         match events[if deliver_bs_raa { 2 } else { 1 }] {
3074                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3075                         assert_eq!(channel_id, chan_2.2);
3076                         assert_eq!(data.as_str(), "Commitment or closing transaction was confirmed on chain.");
3077                 },
3078                 _ => panic!("Unexpected event"),
3079         }
3080         if deliver_bs_raa {
3081                 match events[0] {
3082                         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, .. } } => {
3083                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3084                                 assert_eq!(update_add_htlcs.len(), 1);
3085                                 assert!(update_fulfill_htlcs.is_empty());
3086                                 assert!(update_fail_htlcs.is_empty());
3087                                 assert!(update_fail_malformed_htlcs.is_empty());
3088                         },
3089                         _ => panic!("Unexpected event"),
3090                 }
3091         }
3092         match events[if deliver_bs_raa { 3 } else { 2 }] {
3093                 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, .. } } => {
3094                         assert!(update_add_htlcs.is_empty());
3095                         assert_eq!(update_fail_htlcs.len(), 3);
3096                         assert!(update_fulfill_htlcs.is_empty());
3097                         assert!(update_fail_malformed_htlcs.is_empty());
3098                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3099
3100                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3101                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3102                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3103
3104                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3105
3106                         let events = nodes[0].node.get_and_clear_pending_events();
3107                         assert_eq!(events.len(), 3);
3108                         match events[0] {
3109                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3110                                         assert!(failed_htlcs.insert(payment_hash.0));
3111                                         // If we delivered B's RAA we got an unknown preimage error, not something
3112                                         // that we should update our routing table for.
3113                                         if !deliver_bs_raa {
3114                                                 assert!(network_update.is_some());
3115                                         }
3116                                 },
3117                                 _ => panic!("Unexpected event"),
3118                         }
3119                         match events[1] {
3120                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3121                                         assert!(failed_htlcs.insert(payment_hash.0));
3122                                         assert!(network_update.is_some());
3123                                 },
3124                                 _ => panic!("Unexpected event"),
3125                         }
3126                         match events[2] {
3127                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3128                                         assert!(failed_htlcs.insert(payment_hash.0));
3129                                         assert!(network_update.is_some());
3130                                 },
3131                                 _ => panic!("Unexpected event"),
3132                         }
3133                 },
3134                 _ => panic!("Unexpected event"),
3135         }
3136
3137         assert!(failed_htlcs.contains(&first_payment_hash.0));
3138         assert!(failed_htlcs.contains(&second_payment_hash.0));
3139         assert!(failed_htlcs.contains(&third_payment_hash.0));
3140 }
3141
3142 #[test]
3143 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3144         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3145         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3146         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3147         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3148 }
3149
3150 #[test]
3151 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3152         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3153         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3154         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3155         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3156 }
3157
3158 #[test]
3159 fn fail_backward_pending_htlc_upon_channel_failure() {
3160         let chanmon_cfgs = create_chanmon_cfgs(2);
3161         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3162         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3163         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3164         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3165
3166         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3167         {
3168                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3169                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3170                 check_added_monitors!(nodes[0], 1);
3171
3172                 let payment_event = {
3173                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3174                         assert_eq!(events.len(), 1);
3175                         SendEvent::from_event(events.remove(0))
3176                 };
3177                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3178                 assert_eq!(payment_event.msgs.len(), 1);
3179         }
3180
3181         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3182         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3183         {
3184                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3185                 check_added_monitors!(nodes[0], 0);
3186
3187                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3188         }
3189
3190         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3191         {
3192                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3193
3194                 let secp_ctx = Secp256k1::new();
3195                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3196                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3197                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3198                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3199                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3200
3201                 // Send a 0-msat update_add_htlc to fail the channel.
3202                 let update_add_htlc = msgs::UpdateAddHTLC {
3203                         channel_id: chan.2,
3204                         htlc_id: 0,
3205                         amount_msat: 0,
3206                         payment_hash,
3207                         cltv_expiry,
3208                         onion_routing_packet,
3209                 };
3210                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3211         }
3212         let events = nodes[0].node.get_and_clear_pending_events();
3213         assert_eq!(events.len(), 2);
3214         // Check that Alice fails backward the pending HTLC from the second payment.
3215         match events[0] {
3216                 Event::PaymentPathFailed { payment_hash, .. } => {
3217                         assert_eq!(payment_hash, failed_payment_hash);
3218                 },
3219                 _ => panic!("Unexpected event"),
3220         }
3221         match events[1] {
3222                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3223                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3224                 },
3225                 _ => panic!("Unexpected event {:?}", events[1]),
3226         }
3227         check_closed_broadcast!(nodes[0], true);
3228         check_added_monitors!(nodes[0], 1);
3229 }
3230
3231 #[test]
3232 fn test_htlc_ignore_latest_remote_commitment() {
3233         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3234         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3235         let chanmon_cfgs = create_chanmon_cfgs(2);
3236         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3237         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3238         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3239         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3240
3241         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3242         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3243         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3244         check_closed_broadcast!(nodes[0], true);
3245         check_added_monitors!(nodes[0], 1);
3246         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3247
3248         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3249         assert_eq!(node_txn.len(), 3);
3250         assert_eq!(node_txn[0], node_txn[1]);
3251
3252         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3253         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3254         check_closed_broadcast!(nodes[1], true);
3255         check_added_monitors!(nodes[1], 1);
3256         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3257
3258         // Duplicate the connect_block call since this may happen due to other listeners
3259         // registering new transactions
3260         header.prev_blockhash = header.block_hash();
3261         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3262 }
3263
3264 #[test]
3265 fn test_force_close_fail_back() {
3266         // Check which HTLCs are failed-backwards on channel force-closure
3267         let chanmon_cfgs = create_chanmon_cfgs(3);
3268         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3269         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3270         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3271         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3272         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3273
3274         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3275
3276         let mut payment_event = {
3277                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3278                 check_added_monitors!(nodes[0], 1);
3279
3280                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3281                 assert_eq!(events.len(), 1);
3282                 SendEvent::from_event(events.remove(0))
3283         };
3284
3285         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3286         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3287
3288         expect_pending_htlcs_forwardable!(nodes[1]);
3289
3290         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3291         assert_eq!(events_2.len(), 1);
3292         payment_event = SendEvent::from_event(events_2.remove(0));
3293         assert_eq!(payment_event.msgs.len(), 1);
3294
3295         check_added_monitors!(nodes[1], 1);
3296         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3297         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3298         check_added_monitors!(nodes[2], 1);
3299         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3300
3301         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3302         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3303         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3304
3305         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3306         check_closed_broadcast!(nodes[2], true);
3307         check_added_monitors!(nodes[2], 1);
3308         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3309         let tx = {
3310                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3311                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3312                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3313                 // back to nodes[1] upon timeout otherwise.
3314                 assert_eq!(node_txn.len(), 1);
3315                 node_txn.remove(0)
3316         };
3317
3318         mine_transaction(&nodes[1], &tx);
3319
3320         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3321         check_closed_broadcast!(nodes[1], true);
3322         check_added_monitors!(nodes[1], 1);
3323         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3324
3325         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3326         {
3327                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3328                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3329         }
3330         mine_transaction(&nodes[2], &tx);
3331         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3332         assert_eq!(node_txn.len(), 1);
3333         assert_eq!(node_txn[0].input.len(), 1);
3334         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3335         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3336         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3337
3338         check_spends!(node_txn[0], tx);
3339 }
3340
3341 #[test]
3342 fn test_dup_events_on_peer_disconnect() {
3343         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3344         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3345         // as we used to generate the event immediately upon receipt of the payment preimage in the
3346         // update_fulfill_htlc message.
3347
3348         let chanmon_cfgs = create_chanmon_cfgs(2);
3349         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3350         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3351         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3352         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3353
3354         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3355
3356         assert!(nodes[1].node.claim_funds(payment_preimage));
3357         check_added_monitors!(nodes[1], 1);
3358         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3359         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3360         expect_payment_sent!(nodes[0], payment_preimage);
3361
3362         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3363         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3364
3365         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3366         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3367 }
3368
3369 #[test]
3370 fn test_simple_peer_disconnect() {
3371         // Test that we can reconnect when there are no lost messages
3372         let chanmon_cfgs = create_chanmon_cfgs(3);
3373         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3374         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3375         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3376         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3377         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3378
3379         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3380         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3381         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3382
3383         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3384         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3385         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3386         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3387
3388         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3389         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3390         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3391
3392         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3393         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3394         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3395         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3396
3397         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3398         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3399
3400         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3401         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3402
3403         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3404         {
3405                 let events = nodes[0].node.get_and_clear_pending_events();
3406                 assert_eq!(events.len(), 2);
3407                 match events[0] {
3408                         Event::PaymentSent { payment_preimage, payment_hash } => {
3409                                 assert_eq!(payment_preimage, payment_preimage_3);
3410                                 assert_eq!(payment_hash, payment_hash_3);
3411                         },
3412                         _ => panic!("Unexpected event"),
3413                 }
3414                 match events[1] {
3415                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3416                                 assert_eq!(payment_hash, payment_hash_5);
3417                                 assert!(rejected_by_dest);
3418                         },
3419                         _ => panic!("Unexpected event"),
3420                 }
3421         }
3422
3423         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3424         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3425 }
3426
3427 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3428         // Test that we can reconnect when in-flight HTLC updates get dropped
3429         let chanmon_cfgs = create_chanmon_cfgs(2);
3430         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3431         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3432         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3433
3434         let mut as_funding_locked = None;
3435         if messages_delivered == 0 {
3436                 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3437                 as_funding_locked = Some(funding_locked);
3438                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3439                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3440                 // it before the channel_reestablish message.
3441         } else {
3442                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3443         }
3444
3445         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3446
3447         let payment_event = {
3448                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3449                 check_added_monitors!(nodes[0], 1);
3450
3451                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3452                 assert_eq!(events.len(), 1);
3453                 SendEvent::from_event(events.remove(0))
3454         };
3455         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3456
3457         if messages_delivered < 2 {
3458                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3459         } else {
3460                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3461                 if messages_delivered >= 3 {
3462                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3463                         check_added_monitors!(nodes[1], 1);
3464                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3465
3466                         if messages_delivered >= 4 {
3467                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3468                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3469                                 check_added_monitors!(nodes[0], 1);
3470
3471                                 if messages_delivered >= 5 {
3472                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3473                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3474                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3475                                         check_added_monitors!(nodes[0], 1);
3476
3477                                         if messages_delivered >= 6 {
3478                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3479                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3480                                                 check_added_monitors!(nodes[1], 1);
3481                                         }
3482                                 }
3483                         }
3484                 }
3485         }
3486
3487         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3488         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3489         if messages_delivered < 3 {
3490                 if simulate_broken_lnd {
3491                         // lnd has a long-standing bug where they send a funding_locked prior to a
3492                         // channel_reestablish if you reconnect prior to funding_locked time.
3493                         //
3494                         // Here we simulate that behavior, delivering a funding_locked immediately on
3495                         // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3496                         // in `reconnect_nodes` but we currently don't fail based on that.
3497                         //
3498                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3499                         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3500                 }
3501                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3502                 // received on either side, both sides will need to resend them.
3503                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3504         } else if messages_delivered == 3 {
3505                 // nodes[0] still wants its RAA + commitment_signed
3506                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3507         } else if messages_delivered == 4 {
3508                 // nodes[0] still wants its commitment_signed
3509                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3510         } else if messages_delivered == 5 {
3511                 // nodes[1] still wants its final RAA
3512                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3513         } else if messages_delivered == 6 {
3514                 // Everything was delivered...
3515                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3516         }
3517
3518         let events_1 = nodes[1].node.get_and_clear_pending_events();
3519         assert_eq!(events_1.len(), 1);
3520         match events_1[0] {
3521                 Event::PendingHTLCsForwardable { .. } => { },
3522                 _ => panic!("Unexpected event"),
3523         };
3524
3525         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3526         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3527         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3528
3529         nodes[1].node.process_pending_htlc_forwards();
3530
3531         let events_2 = nodes[1].node.get_and_clear_pending_events();
3532         assert_eq!(events_2.len(), 1);
3533         match events_2[0] {
3534                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3535                         assert_eq!(payment_hash_1, *payment_hash);
3536                         assert_eq!(amt, 1000000);
3537                         match &purpose {
3538                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3539                                         assert!(payment_preimage.is_none());
3540                                         assert_eq!(payment_secret_1, *payment_secret);
3541                                 },
3542                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3543                         }
3544                 },
3545                 _ => panic!("Unexpected event"),
3546         }
3547
3548         nodes[1].node.claim_funds(payment_preimage_1);
3549         check_added_monitors!(nodes[1], 1);
3550
3551         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3552         assert_eq!(events_3.len(), 1);
3553         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3554                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3555                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3556                         assert!(updates.update_add_htlcs.is_empty());
3557                         assert!(updates.update_fail_htlcs.is_empty());
3558                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3559                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3560                         assert!(updates.update_fee.is_none());
3561                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3562                 },
3563                 _ => panic!("Unexpected event"),
3564         };
3565
3566         if messages_delivered >= 1 {
3567                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3568
3569                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3570                 assert_eq!(events_4.len(), 1);
3571                 match events_4[0] {
3572                         Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
3573                                 assert_eq!(payment_preimage_1, *payment_preimage);
3574                                 assert_eq!(payment_hash_1, *payment_hash);
3575                         },
3576                         _ => panic!("Unexpected event"),
3577                 }
3578
3579                 if messages_delivered >= 2 {
3580                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3581                         check_added_monitors!(nodes[0], 1);
3582                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3583
3584                         if messages_delivered >= 3 {
3585                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3586                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3587                                 check_added_monitors!(nodes[1], 1);
3588
3589                                 if messages_delivered >= 4 {
3590                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3591                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3592                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3593                                         check_added_monitors!(nodes[1], 1);
3594
3595                                         if messages_delivered >= 5 {
3596                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3597                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3598                                                 check_added_monitors!(nodes[0], 1);
3599                                         }
3600                                 }
3601                         }
3602                 }
3603         }
3604
3605         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3606         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3607         if messages_delivered < 2 {
3608                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3609                 if messages_delivered < 1 {
3610                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3611                         assert_eq!(events_4.len(), 1);
3612                         match events_4[0] {
3613                                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
3614                                         assert_eq!(payment_preimage_1, *payment_preimage);
3615                                         assert_eq!(payment_hash_1, *payment_hash);
3616                                 },
3617                                 _ => panic!("Unexpected event"),
3618                         }
3619                 } else {
3620                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3621                 }
3622         } else if messages_delivered == 2 {
3623                 // nodes[0] still wants its RAA + commitment_signed
3624                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3625         } else if messages_delivered == 3 {
3626                 // nodes[0] still wants its commitment_signed
3627                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3628         } else if messages_delivered == 4 {
3629                 // nodes[1] still wants its final RAA
3630                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3631         } else if messages_delivered == 5 {
3632                 // Everything was delivered...
3633                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3634         }
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         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3639
3640         // Channel should still work fine...
3641         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3642         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3643         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3644 }
3645
3646 #[test]
3647 fn test_drop_messages_peer_disconnect_a() {
3648         do_test_drop_messages_peer_disconnect(0, true);
3649         do_test_drop_messages_peer_disconnect(0, false);
3650         do_test_drop_messages_peer_disconnect(1, false);
3651         do_test_drop_messages_peer_disconnect(2, false);
3652 }
3653
3654 #[test]
3655 fn test_drop_messages_peer_disconnect_b() {
3656         do_test_drop_messages_peer_disconnect(3, false);
3657         do_test_drop_messages_peer_disconnect(4, false);
3658         do_test_drop_messages_peer_disconnect(5, false);
3659         do_test_drop_messages_peer_disconnect(6, false);
3660 }
3661
3662 #[test]
3663 fn test_funding_peer_disconnect() {
3664         // Test that we can lock in our funding tx while disconnected
3665         let chanmon_cfgs = create_chanmon_cfgs(2);
3666         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3667         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3668         let persister: test_utils::TestPersister;
3669         let new_chain_monitor: test_utils::TestChainMonitor;
3670         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3671         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3672         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3673
3674         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3675         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3676
3677         confirm_transaction(&nodes[0], &tx);
3678         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3679         let chan_id;
3680         assert_eq!(events_1.len(), 1);
3681         match events_1[0] {
3682                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3683                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3684                         chan_id = msg.channel_id;
3685                 },
3686                 _ => panic!("Unexpected event"),
3687         }
3688
3689         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3690
3691         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3692         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3693
3694         confirm_transaction(&nodes[1], &tx);
3695         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3696         assert_eq!(events_2.len(), 2);
3697         let funding_locked = match events_2[0] {
3698                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3699                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3700                         msg.clone()
3701                 },
3702                 _ => panic!("Unexpected event"),
3703         };
3704         let bs_announcement_sigs = match events_2[1] {
3705                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3706                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3707                         msg.clone()
3708                 },
3709                 _ => panic!("Unexpected event"),
3710         };
3711
3712         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3713
3714         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3715         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3716         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3717         assert_eq!(events_3.len(), 2);
3718         let as_announcement_sigs = match events_3[0] {
3719                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3720                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3721                         msg.clone()
3722                 },
3723                 _ => panic!("Unexpected event"),
3724         };
3725         let (as_announcement, as_update) = match events_3[1] {
3726                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3727                         (msg.clone(), update_msg.clone())
3728                 },
3729                 _ => panic!("Unexpected event"),
3730         };
3731
3732         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3733         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3734         assert_eq!(events_4.len(), 1);
3735         let (_, bs_update) = match events_4[0] {
3736                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3737                         (msg.clone(), update_msg.clone())
3738                 },
3739                 _ => panic!("Unexpected event"),
3740         };
3741
3742         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3743         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3744         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3745
3746         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3747         let (payment_preimage, _, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3748         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3749
3750         // Check that after deserialization and reconnection we can still generate an identical
3751         // channel_announcement from the cached signatures.
3752         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3753
3754         let nodes_0_serialized = nodes[0].node.encode();
3755         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3756         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3757
3758         persister = test_utils::TestPersister::new();
3759         let keys_manager = &chanmon_cfgs[0].keys_manager;
3760         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);
3761         nodes[0].chain_monitor = &new_chain_monitor;
3762         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3763         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3764                 &mut chan_0_monitor_read, keys_manager).unwrap();
3765         assert!(chan_0_monitor_read.is_empty());
3766
3767         let mut nodes_0_read = &nodes_0_serialized[..];
3768         let (_, nodes_0_deserialized_tmp) = {
3769                 let mut channel_monitors = HashMap::new();
3770                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3771                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3772                         default_config: UserConfig::default(),
3773                         keys_manager,
3774                         fee_estimator: node_cfgs[0].fee_estimator,
3775                         chain_monitor: nodes[0].chain_monitor,
3776                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3777                         logger: nodes[0].logger,
3778                         channel_monitors,
3779                 }).unwrap()
3780         };
3781         nodes_0_deserialized = nodes_0_deserialized_tmp;
3782         assert!(nodes_0_read.is_empty());
3783
3784         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3785         nodes[0].node = &nodes_0_deserialized;
3786         check_added_monitors!(nodes[0], 1);
3787
3788         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3789
3790         // as_announcement should be re-generated exactly by broadcast_node_announcement.
3791         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3792         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3793         let mut found_announcement = false;
3794         for event in msgs.iter() {
3795                 match event {
3796                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3797                                 if *msg == as_announcement { found_announcement = true; }
3798                         },
3799                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3800                         _ => panic!("Unexpected event"),
3801                 }
3802         }
3803         assert!(found_announcement);
3804 }
3805
3806 #[test]
3807 fn test_drop_messages_peer_disconnect_dual_htlc() {
3808         // Test that we can handle reconnecting when both sides of a channel have pending
3809         // commitment_updates when we disconnect.
3810         let chanmon_cfgs = create_chanmon_cfgs(2);
3811         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3812         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3813         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3814         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3815
3816         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3817
3818         // Now try to send a second payment which will fail to send
3819         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3820         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
3821         check_added_monitors!(nodes[0], 1);
3822
3823         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3824         assert_eq!(events_1.len(), 1);
3825         match events_1[0] {
3826                 MessageSendEvent::UpdateHTLCs { .. } => {},
3827                 _ => panic!("Unexpected event"),
3828         }
3829
3830         assert!(nodes[1].node.claim_funds(payment_preimage_1));
3831         check_added_monitors!(nodes[1], 1);
3832
3833         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3834         assert_eq!(events_2.len(), 1);
3835         match events_2[0] {
3836                 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 } } => {
3837                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3838                         assert!(update_add_htlcs.is_empty());
3839                         assert_eq!(update_fulfill_htlcs.len(), 1);
3840                         assert!(update_fail_htlcs.is_empty());
3841                         assert!(update_fail_malformed_htlcs.is_empty());
3842                         assert!(update_fee.is_none());
3843
3844                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3845                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3846                         assert_eq!(events_3.len(), 1);
3847                         match events_3[0] {
3848                                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
3849                                         assert_eq!(*payment_preimage, payment_preimage_1);
3850                                         assert_eq!(*payment_hash, payment_hash_1);
3851                                 },
3852                                 _ => panic!("Unexpected event"),
3853                         }
3854
3855                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3856                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3857                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3858                         check_added_monitors!(nodes[0], 1);
3859                 },
3860                 _ => panic!("Unexpected event"),
3861         }
3862
3863         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3864         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3865
3866         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3867         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3868         assert_eq!(reestablish_1.len(), 1);
3869         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3870         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3871         assert_eq!(reestablish_2.len(), 1);
3872
3873         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3874         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3875         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3876         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3877
3878         assert!(as_resp.0.is_none());
3879         assert!(bs_resp.0.is_none());
3880
3881         assert!(bs_resp.1.is_none());
3882         assert!(bs_resp.2.is_none());
3883
3884         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3885
3886         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3887         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3888         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3889         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3890         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3891         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3892         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3893         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3894         // No commitment_signed so get_event_msg's assert(len == 1) passes
3895         check_added_monitors!(nodes[1], 1);
3896
3897         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3898         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3899         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3900         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3901         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3902         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3903         assert!(bs_second_commitment_signed.update_fee.is_none());
3904         check_added_monitors!(nodes[1], 1);
3905
3906         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3907         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3908         assert!(as_commitment_signed.update_add_htlcs.is_empty());
3909         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3910         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3911         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3912         assert!(as_commitment_signed.update_fee.is_none());
3913         check_added_monitors!(nodes[0], 1);
3914
3915         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3916         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3917         // No commitment_signed so get_event_msg's assert(len == 1) passes
3918         check_added_monitors!(nodes[0], 1);
3919
3920         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3921         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3922         // No commitment_signed so get_event_msg's assert(len == 1) passes
3923         check_added_monitors!(nodes[1], 1);
3924
3925         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3926         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3927         check_added_monitors!(nodes[1], 1);
3928
3929         expect_pending_htlcs_forwardable!(nodes[1]);
3930
3931         let events_5 = nodes[1].node.get_and_clear_pending_events();
3932         assert_eq!(events_5.len(), 1);
3933         match events_5[0] {
3934                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
3935                         assert_eq!(payment_hash_2, *payment_hash);
3936                         match &purpose {
3937                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3938                                         assert!(payment_preimage.is_none());
3939                                         assert_eq!(payment_secret_2, *payment_secret);
3940                                 },
3941                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3942                         }
3943                 },
3944                 _ => panic!("Unexpected event"),
3945         }
3946
3947         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3948         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3949         check_added_monitors!(nodes[0], 1);
3950
3951         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3952 }
3953
3954 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3955         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3956         // to avoid our counterparty failing the channel.
3957         let chanmon_cfgs = create_chanmon_cfgs(2);
3958         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3959         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3960         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3961
3962         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3963
3964         let our_payment_hash = if send_partial_mpp {
3965                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
3966                 // Use the utility function send_payment_along_path to send the payment with MPP data which
3967                 // indicates there are more HTLCs coming.
3968                 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.
3969                 let payment_id = PaymentId([42; 32]);
3970                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height, payment_id, &None).unwrap();
3971                 check_added_monitors!(nodes[0], 1);
3972                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3973                 assert_eq!(events.len(), 1);
3974                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3975                 // hop should *not* yet generate any PaymentReceived event(s).
3976                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
3977                 our_payment_hash
3978         } else {
3979                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3980         };
3981
3982         let mut block = Block {
3983                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3984                 txdata: vec![],
3985         };
3986         connect_block(&nodes[0], &block);
3987         connect_block(&nodes[1], &block);
3988         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
3989         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
3990                 block.header.prev_blockhash = block.block_hash();
3991                 connect_block(&nodes[0], &block);
3992                 connect_block(&nodes[1], &block);
3993         }
3994
3995         expect_pending_htlcs_forwardable!(nodes[1]);
3996
3997         check_added_monitors!(nodes[1], 1);
3998         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3999         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4000         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4001         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4002         assert!(htlc_timeout_updates.update_fee.is_none());
4003
4004         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4005         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4006         // 100_000 msat as u64, followed by the height at which we failed back above
4007         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4008         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4009         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4010 }
4011
4012 #[test]
4013 fn test_htlc_timeout() {
4014         do_test_htlc_timeout(true);
4015         do_test_htlc_timeout(false);
4016 }
4017
4018 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4019         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4020         let chanmon_cfgs = create_chanmon_cfgs(3);
4021         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4022         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4023         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4024         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4025         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4026
4027         // Make sure all nodes are at the same starting height
4028         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4029         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4030         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4031
4032         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4033         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4034         {
4035                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4036         }
4037         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4038         check_added_monitors!(nodes[1], 1);
4039
4040         // Now attempt to route a second payment, which should be placed in the holding cell
4041         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4042         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4043         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4044         if forwarded_htlc {
4045                 check_added_monitors!(nodes[0], 1);
4046                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4047                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4048                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4049                 expect_pending_htlcs_forwardable!(nodes[1]);
4050         }
4051         check_added_monitors!(nodes[1], 0);
4052
4053         connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4054         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4055         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4056         connect_blocks(&nodes[1], 1);
4057
4058         if forwarded_htlc {
4059                 expect_pending_htlcs_forwardable!(nodes[1]);
4060                 check_added_monitors!(nodes[1], 1);
4061                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4062                 assert_eq!(fail_commit.len(), 1);
4063                 match fail_commit[0] {
4064                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4065                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4066                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4067                         },
4068                         _ => unreachable!(),
4069                 }
4070                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4071         } else {
4072                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4073         }
4074 }
4075
4076 #[test]
4077 fn test_holding_cell_htlc_add_timeouts() {
4078         do_test_holding_cell_htlc_add_timeouts(false);
4079         do_test_holding_cell_htlc_add_timeouts(true);
4080 }
4081
4082 #[test]
4083 fn test_no_txn_manager_serialize_deserialize() {
4084         let chanmon_cfgs = create_chanmon_cfgs(2);
4085         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4086         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4087         let logger: test_utils::TestLogger;
4088         let fee_estimator: test_utils::TestFeeEstimator;
4089         let persister: test_utils::TestPersister;
4090         let new_chain_monitor: test_utils::TestChainMonitor;
4091         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4092         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4093
4094         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4095
4096         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4097
4098         let nodes_0_serialized = nodes[0].node.encode();
4099         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4100         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4101                 .write(&mut chan_0_monitor_serialized).unwrap();
4102
4103         logger = test_utils::TestLogger::new();
4104         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4105         persister = test_utils::TestPersister::new();
4106         let keys_manager = &chanmon_cfgs[0].keys_manager;
4107         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4108         nodes[0].chain_monitor = &new_chain_monitor;
4109         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4110         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4111                 &mut chan_0_monitor_read, keys_manager).unwrap();
4112         assert!(chan_0_monitor_read.is_empty());
4113
4114         let mut nodes_0_read = &nodes_0_serialized[..];
4115         let config = UserConfig::default();
4116         let (_, nodes_0_deserialized_tmp) = {
4117                 let mut channel_monitors = HashMap::new();
4118                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4119                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4120                         default_config: config,
4121                         keys_manager,
4122                         fee_estimator: &fee_estimator,
4123                         chain_monitor: nodes[0].chain_monitor,
4124                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4125                         logger: &logger,
4126                         channel_monitors,
4127                 }).unwrap()
4128         };
4129         nodes_0_deserialized = nodes_0_deserialized_tmp;
4130         assert!(nodes_0_read.is_empty());
4131
4132         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4133         nodes[0].node = &nodes_0_deserialized;
4134         assert_eq!(nodes[0].node.list_channels().len(), 1);
4135         check_added_monitors!(nodes[0], 1);
4136
4137         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4138         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4139         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4140         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4141
4142         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4143         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4144         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4145         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4146
4147         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4148         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4149         for node in nodes.iter() {
4150                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4151                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4152                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4153         }
4154
4155         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4156 }
4157
4158 #[test]
4159 fn test_dup_htlc_onchain_fails_on_reload() {
4160         // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
4161         // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
4162         // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
4163         // the ChannelMonitor tells it to.
4164         //
4165         // If, due to an on-chain event, an HTLC is failed/claimed, and then we serialize the
4166         // ChannelManager, we generally expect there not to be a duplicate HTLC fail/claim (eg via a
4167         // PaymentPathFailed event appearing). However, because we may not serialize the relevant
4168         // ChannelMonitor at the same time, this isn't strictly guaranteed. In order to provide this
4169         // consistency, the ChannelManager explicitly tracks pending-onchain-resolution outbound HTLCs
4170         // and de-duplicates ChannelMonitor events.
4171         //
4172         // This tests that explicit tracking behavior.
4173         let chanmon_cfgs = create_chanmon_cfgs(2);
4174         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4175         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4176         let persister: test_utils::TestPersister;
4177         let new_chain_monitor: test_utils::TestChainMonitor;
4178         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4179         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4180
4181         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4182
4183         // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
4184         // nodes[0].
4185         let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 10000000);
4186         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
4187         check_closed_broadcast!(nodes[0], true);
4188         check_added_monitors!(nodes[0], 1);
4189         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4190
4191         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4192         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4193
4194         // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
4195         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
4196         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4197         assert_eq!(node_txn.len(), 3);
4198         assert_eq!(node_txn[0], node_txn[1]);
4199
4200         assert!(nodes[1].node.claim_funds(payment_preimage));
4201         check_added_monitors!(nodes[1], 1);
4202
4203         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4204         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4205         check_closed_broadcast!(nodes[1], true);
4206         check_added_monitors!(nodes[1], 1);
4207         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4208         let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4209
4210         header.prev_blockhash = nodes[0].best_block_hash();
4211         connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4212
4213         // Serialize out the ChannelMonitor before connecting the on-chain claim transactions. This is
4214         // fairly normal behavior as ChannelMonitor(s) are often not re-serialized when on-chain events
4215         // happen, unlike ChannelManager which tends to be re-serialized after any relevant event(s).
4216         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4217         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4218
4219         header.prev_blockhash = nodes[0].best_block_hash();
4220         let claim_block = Block { header, txdata: claim_txn};
4221         connect_block(&nodes[0], &claim_block);
4222         expect_payment_sent!(nodes[0], payment_preimage);
4223
4224         // ChannelManagers generally get re-serialized after any relevant event(s). Since we just
4225         // connected a highly-relevant block, it likely gets serialized out now.
4226         let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
4227         nodes[0].node.write(&mut chan_manager_serialized).unwrap();
4228
4229         // Now reload nodes[0]...
4230         persister = test_utils::TestPersister::new();
4231         let keys_manager = &chanmon_cfgs[0].keys_manager;
4232         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);
4233         nodes[0].chain_monitor = &new_chain_monitor;
4234         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4235         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4236                 &mut chan_0_monitor_read, keys_manager).unwrap();
4237         assert!(chan_0_monitor_read.is_empty());
4238
4239         let (_, nodes_0_deserialized_tmp) = {
4240                 let mut channel_monitors = HashMap::new();
4241                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4242                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
4243                         ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
4244                                 default_config: Default::default(),
4245                                 keys_manager,
4246                                 fee_estimator: node_cfgs[0].fee_estimator,
4247                                 chain_monitor: nodes[0].chain_monitor,
4248                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4249                                 logger: nodes[0].logger,
4250                                 channel_monitors,
4251                         }).unwrap()
4252         };
4253         nodes_0_deserialized = nodes_0_deserialized_tmp;
4254
4255         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4256         check_added_monitors!(nodes[0], 1);
4257         nodes[0].node = &nodes_0_deserialized;
4258
4259         // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
4260         // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
4261         // payment events should kick in, leaving us with no pending events here.
4262         let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
4263         nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
4264         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4265 }
4266
4267 #[test]
4268 fn test_manager_serialize_deserialize_events() {
4269         // This test makes sure the events field in ChannelManager survives de/serialization
4270         let chanmon_cfgs = create_chanmon_cfgs(2);
4271         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4272         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4273         let fee_estimator: test_utils::TestFeeEstimator;
4274         let persister: test_utils::TestPersister;
4275         let logger: test_utils::TestLogger;
4276         let new_chain_monitor: test_utils::TestChainMonitor;
4277         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4278         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4279
4280         // Start creating a channel, but stop right before broadcasting the funding transaction
4281         let channel_value = 100000;
4282         let push_msat = 10001;
4283         let a_flags = InitFeatures::known();
4284         let b_flags = InitFeatures::known();
4285         let node_a = nodes.remove(0);
4286         let node_b = nodes.remove(0);
4287         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4288         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()));
4289         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()));
4290
4291         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4292
4293         node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4294         check_added_monitors!(node_a, 0);
4295
4296         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()));
4297         {
4298                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4299                 assert_eq!(added_monitors.len(), 1);
4300                 assert_eq!(added_monitors[0].0, funding_output);
4301                 added_monitors.clear();
4302         }
4303
4304         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4305         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4306         {
4307                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4308                 assert_eq!(added_monitors.len(), 1);
4309                 assert_eq!(added_monitors[0].0, funding_output);
4310                 added_monitors.clear();
4311         }
4312         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4313
4314         nodes.push(node_a);
4315         nodes.push(node_b);
4316
4317         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4318         let nodes_0_serialized = nodes[0].node.encode();
4319         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4320         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4321
4322         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4323         logger = test_utils::TestLogger::new();
4324         persister = test_utils::TestPersister::new();
4325         let keys_manager = &chanmon_cfgs[0].keys_manager;
4326         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4327         nodes[0].chain_monitor = &new_chain_monitor;
4328         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4329         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4330                 &mut chan_0_monitor_read, keys_manager).unwrap();
4331         assert!(chan_0_monitor_read.is_empty());
4332
4333         let mut nodes_0_read = &nodes_0_serialized[..];
4334         let config = UserConfig::default();
4335         let (_, nodes_0_deserialized_tmp) = {
4336                 let mut channel_monitors = HashMap::new();
4337                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4338                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4339                         default_config: config,
4340                         keys_manager,
4341                         fee_estimator: &fee_estimator,
4342                         chain_monitor: nodes[0].chain_monitor,
4343                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4344                         logger: &logger,
4345                         channel_monitors,
4346                 }).unwrap()
4347         };
4348         nodes_0_deserialized = nodes_0_deserialized_tmp;
4349         assert!(nodes_0_read.is_empty());
4350
4351         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4352
4353         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4354         nodes[0].node = &nodes_0_deserialized;
4355
4356         // After deserializing, make sure the funding_transaction is still held by the channel manager
4357         let events_4 = nodes[0].node.get_and_clear_pending_events();
4358         assert_eq!(events_4.len(), 0);
4359         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4360         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4361
4362         // Make sure the channel is functioning as though the de/serialization never happened
4363         assert_eq!(nodes[0].node.list_channels().len(), 1);
4364         check_added_monitors!(nodes[0], 1);
4365
4366         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4367         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4368         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4369         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4370
4371         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4372         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4373         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4374         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4375
4376         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4377         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4378         for node in nodes.iter() {
4379                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4380                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4381                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4382         }
4383
4384         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4385 }
4386
4387 #[test]
4388 fn test_simple_manager_serialize_deserialize() {
4389         let chanmon_cfgs = create_chanmon_cfgs(2);
4390         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4391         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4392         let logger: test_utils::TestLogger;
4393         let fee_estimator: test_utils::TestFeeEstimator;
4394         let persister: test_utils::TestPersister;
4395         let new_chain_monitor: test_utils::TestChainMonitor;
4396         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4397         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4398         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4399
4400         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4401         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4402
4403         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4404
4405         let nodes_0_serialized = nodes[0].node.encode();
4406         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4407         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4408
4409         logger = test_utils::TestLogger::new();
4410         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4411         persister = test_utils::TestPersister::new();
4412         let keys_manager = &chanmon_cfgs[0].keys_manager;
4413         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4414         nodes[0].chain_monitor = &new_chain_monitor;
4415         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4416         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4417                 &mut chan_0_monitor_read, keys_manager).unwrap();
4418         assert!(chan_0_monitor_read.is_empty());
4419
4420         let mut nodes_0_read = &nodes_0_serialized[..];
4421         let (_, nodes_0_deserialized_tmp) = {
4422                 let mut channel_monitors = HashMap::new();
4423                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4424                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4425                         default_config: UserConfig::default(),
4426                         keys_manager,
4427                         fee_estimator: &fee_estimator,
4428                         chain_monitor: nodes[0].chain_monitor,
4429                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4430                         logger: &logger,
4431                         channel_monitors,
4432                 }).unwrap()
4433         };
4434         nodes_0_deserialized = nodes_0_deserialized_tmp;
4435         assert!(nodes_0_read.is_empty());
4436
4437         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4438         nodes[0].node = &nodes_0_deserialized;
4439         check_added_monitors!(nodes[0], 1);
4440
4441         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4442
4443         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4444         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4445 }
4446
4447 #[test]
4448 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4449         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4450         let chanmon_cfgs = create_chanmon_cfgs(4);
4451         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4452         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4453         let logger: test_utils::TestLogger;
4454         let fee_estimator: test_utils::TestFeeEstimator;
4455         let persister: test_utils::TestPersister;
4456         let new_chain_monitor: test_utils::TestChainMonitor;
4457         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4458         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4459         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4460         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4461         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4462
4463         let mut node_0_stale_monitors_serialized = Vec::new();
4464         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4465                 let mut writer = test_utils::TestVecWriter(Vec::new());
4466                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4467                 node_0_stale_monitors_serialized.push(writer.0);
4468         }
4469
4470         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4471
4472         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4473         let nodes_0_serialized = nodes[0].node.encode();
4474
4475         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4476         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4477         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4478         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4479
4480         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4481         // nodes[3])
4482         let mut node_0_monitors_serialized = Vec::new();
4483         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4484                 let mut writer = test_utils::TestVecWriter(Vec::new());
4485                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4486                 node_0_monitors_serialized.push(writer.0);
4487         }
4488
4489         logger = test_utils::TestLogger::new();
4490         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4491         persister = test_utils::TestPersister::new();
4492         let keys_manager = &chanmon_cfgs[0].keys_manager;
4493         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4494         nodes[0].chain_monitor = &new_chain_monitor;
4495
4496
4497         let mut node_0_stale_monitors = Vec::new();
4498         for serialized in node_0_stale_monitors_serialized.iter() {
4499                 let mut read = &serialized[..];
4500                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4501                 assert!(read.is_empty());
4502                 node_0_stale_monitors.push(monitor);
4503         }
4504
4505         let mut node_0_monitors = Vec::new();
4506         for serialized in node_0_monitors_serialized.iter() {
4507                 let mut read = &serialized[..];
4508                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4509                 assert!(read.is_empty());
4510                 node_0_monitors.push(monitor);
4511         }
4512
4513         let mut nodes_0_read = &nodes_0_serialized[..];
4514         if let Err(msgs::DecodeError::InvalidValue) =
4515                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4516                 default_config: UserConfig::default(),
4517                 keys_manager,
4518                 fee_estimator: &fee_estimator,
4519                 chain_monitor: nodes[0].chain_monitor,
4520                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4521                 logger: &logger,
4522                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4523         }) { } else {
4524                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4525         };
4526
4527         let mut nodes_0_read = &nodes_0_serialized[..];
4528         let (_, nodes_0_deserialized_tmp) =
4529                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4530                 default_config: UserConfig::default(),
4531                 keys_manager,
4532                 fee_estimator: &fee_estimator,
4533                 chain_monitor: nodes[0].chain_monitor,
4534                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4535                 logger: &logger,
4536                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4537         }).unwrap();
4538         nodes_0_deserialized = nodes_0_deserialized_tmp;
4539         assert!(nodes_0_read.is_empty());
4540
4541         { // Channel close should result in a commitment tx
4542                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4543                 assert_eq!(txn.len(), 1);
4544                 check_spends!(txn[0], funding_tx);
4545                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4546         }
4547
4548         for monitor in node_0_monitors.drain(..) {
4549                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4550                 check_added_monitors!(nodes[0], 1);
4551         }
4552         nodes[0].node = &nodes_0_deserialized;
4553         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4554
4555         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4556         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4557         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4558         //... and we can even still claim the payment!
4559         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4560
4561         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4562         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4563         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4564         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4565         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4566         assert_eq!(msg_events.len(), 1);
4567         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4568                 match action {
4569                         &ErrorAction::SendErrorMessage { ref msg } => {
4570                                 assert_eq!(msg.channel_id, channel_id);
4571                         },
4572                         _ => panic!("Unexpected event!"),
4573                 }
4574         }
4575 }
4576
4577 macro_rules! check_spendable_outputs {
4578         ($node: expr, $keysinterface: expr) => {
4579                 {
4580                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4581                         let mut txn = Vec::new();
4582                         let mut all_outputs = Vec::new();
4583                         let secp_ctx = Secp256k1::new();
4584                         for event in events.drain(..) {
4585                                 match event {
4586                                         Event::SpendableOutputs { mut outputs } => {
4587                                                 for outp in outputs.drain(..) {
4588                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4589                                                         all_outputs.push(outp);
4590                                                 }
4591                                         },
4592                                         _ => panic!("Unexpected event"),
4593                                 };
4594                         }
4595                         if all_outputs.len() > 1 {
4596                                 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) {
4597                                         txn.push(tx);
4598                                 }
4599                         }
4600                         txn
4601                 }
4602         }
4603 }
4604
4605 #[test]
4606 fn test_claim_sizeable_push_msat() {
4607         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4608         let chanmon_cfgs = create_chanmon_cfgs(2);
4609         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4610         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4611         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4612
4613         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4614         nodes[1].node.force_close_channel(&chan.2).unwrap();
4615         check_closed_broadcast!(nodes[1], true);
4616         check_added_monitors!(nodes[1], 1);
4617         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4618         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4619         assert_eq!(node_txn.len(), 1);
4620         check_spends!(node_txn[0], chan.3);
4621         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
4622
4623         mine_transaction(&nodes[1], &node_txn[0]);
4624         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4625
4626         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4627         assert_eq!(spend_txn.len(), 1);
4628         assert_eq!(spend_txn[0].input.len(), 1);
4629         check_spends!(spend_txn[0], node_txn[0]);
4630         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4631 }
4632
4633 #[test]
4634 fn test_claim_on_remote_sizeable_push_msat() {
4635         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4636         // to_remote output is encumbered by a P2WPKH
4637         let chanmon_cfgs = create_chanmon_cfgs(2);
4638         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4639         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4640         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4641
4642         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4643         nodes[0].node.force_close_channel(&chan.2).unwrap();
4644         check_closed_broadcast!(nodes[0], true);
4645         check_added_monitors!(nodes[0], 1);
4646         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4647
4648         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4649         assert_eq!(node_txn.len(), 1);
4650         check_spends!(node_txn[0], chan.3);
4651         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
4652
4653         mine_transaction(&nodes[1], &node_txn[0]);
4654         check_closed_broadcast!(nodes[1], true);
4655         check_added_monitors!(nodes[1], 1);
4656         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4657         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4658
4659         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4660         assert_eq!(spend_txn.len(), 1);
4661         check_spends!(spend_txn[0], node_txn[0]);
4662 }
4663
4664 #[test]
4665 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4666         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4667         // to_remote output is encumbered by a P2WPKH
4668
4669         let chanmon_cfgs = create_chanmon_cfgs(2);
4670         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4671         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4672         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4673
4674         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4675         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4676         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4677         assert_eq!(revoked_local_txn[0].input.len(), 1);
4678         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4679
4680         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4681         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4682         check_closed_broadcast!(nodes[1], true);
4683         check_added_monitors!(nodes[1], 1);
4684         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4685
4686         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4687         mine_transaction(&nodes[1], &node_txn[0]);
4688         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4689
4690         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4691         assert_eq!(spend_txn.len(), 3);
4692         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4693         check_spends!(spend_txn[1], node_txn[0]);
4694         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4695 }
4696
4697 #[test]
4698 fn test_static_spendable_outputs_preimage_tx() {
4699         let chanmon_cfgs = create_chanmon_cfgs(2);
4700         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4701         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4702         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4703
4704         // Create some initial channels
4705         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4706
4707         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4708
4709         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4710         assert_eq!(commitment_tx[0].input.len(), 1);
4711         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4712
4713         // Settle A's commitment tx on B's chain
4714         assert!(nodes[1].node.claim_funds(payment_preimage));
4715         check_added_monitors!(nodes[1], 1);
4716         mine_transaction(&nodes[1], &commitment_tx[0]);
4717         check_added_monitors!(nodes[1], 1);
4718         let events = nodes[1].node.get_and_clear_pending_msg_events();
4719         match events[0] {
4720                 MessageSendEvent::UpdateHTLCs { .. } => {},
4721                 _ => panic!("Unexpected event"),
4722         }
4723         match events[1] {
4724                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4725                 _ => panic!("Unexepected event"),
4726         }
4727
4728         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4729         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4730         assert_eq!(node_txn.len(), 3);
4731         check_spends!(node_txn[0], commitment_tx[0]);
4732         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4733         check_spends!(node_txn[1], chan_1.3);
4734         check_spends!(node_txn[2], node_txn[1]);
4735
4736         mine_transaction(&nodes[1], &node_txn[0]);
4737         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4738         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4739
4740         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4741         assert_eq!(spend_txn.len(), 1);
4742         check_spends!(spend_txn[0], node_txn[0]);
4743 }
4744
4745 #[test]
4746 fn test_static_spendable_outputs_timeout_tx() {
4747         let chanmon_cfgs = create_chanmon_cfgs(2);
4748         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4749         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4750         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4751
4752         // Create some initial channels
4753         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4754
4755         // Rebalance the network a bit by relaying one payment through all the channels ...
4756         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4757
4758         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4759
4760         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4761         assert_eq!(commitment_tx[0].input.len(), 1);
4762         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4763
4764         // Settle A's commitment tx on B' chain
4765         mine_transaction(&nodes[1], &commitment_tx[0]);
4766         check_added_monitors!(nodes[1], 1);
4767         let events = nodes[1].node.get_and_clear_pending_msg_events();
4768         match events[0] {
4769                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4770                 _ => panic!("Unexpected event"),
4771         }
4772         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4773
4774         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4775         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4776         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4777         check_spends!(node_txn[0], chan_1.3.clone());
4778         check_spends!(node_txn[1],  commitment_tx[0].clone());
4779         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4780
4781         mine_transaction(&nodes[1], &node_txn[1]);
4782         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4783         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4784         expect_payment_failed!(nodes[1], our_payment_hash, true);
4785
4786         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4787         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4788         check_spends!(spend_txn[0], commitment_tx[0]);
4789         check_spends!(spend_txn[1], node_txn[1]);
4790         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4791 }
4792
4793 #[test]
4794 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4795         let chanmon_cfgs = create_chanmon_cfgs(2);
4796         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4797         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4798         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4799
4800         // Create some initial channels
4801         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4802
4803         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4804         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4805         assert_eq!(revoked_local_txn[0].input.len(), 1);
4806         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4807
4808         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4809
4810         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4811         check_closed_broadcast!(nodes[1], true);
4812         check_added_monitors!(nodes[1], 1);
4813         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4814
4815         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4816         assert_eq!(node_txn.len(), 2);
4817         assert_eq!(node_txn[0].input.len(), 2);
4818         check_spends!(node_txn[0], revoked_local_txn[0]);
4819
4820         mine_transaction(&nodes[1], &node_txn[0]);
4821         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4822
4823         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4824         assert_eq!(spend_txn.len(), 1);
4825         check_spends!(spend_txn[0], node_txn[0]);
4826 }
4827
4828 #[test]
4829 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4830         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4831         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4832         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4833         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4834         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4835
4836         // Create some initial channels
4837         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4838
4839         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4840         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4841         assert_eq!(revoked_local_txn[0].input.len(), 1);
4842         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4843
4844         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4845
4846         // A will generate HTLC-Timeout from revoked commitment tx
4847         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4848         check_closed_broadcast!(nodes[0], true);
4849         check_added_monitors!(nodes[0], 1);
4850         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4851         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4852
4853         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4854         assert_eq!(revoked_htlc_txn.len(), 2);
4855         check_spends!(revoked_htlc_txn[0], chan_1.3);
4856         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4857         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4858         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4859         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4860
4861         // B will generate justice tx from A's revoked commitment/HTLC tx
4862         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4863         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4864         check_closed_broadcast!(nodes[1], true);
4865         check_added_monitors!(nodes[1], 1);
4866         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4867
4868         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4869         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4870         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4871         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4872         // transactions next...
4873         assert_eq!(node_txn[0].input.len(), 3);
4874         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4875
4876         assert_eq!(node_txn[1].input.len(), 2);
4877         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4878         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4879                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4880         } else {
4881                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4882                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4883         }
4884
4885         assert_eq!(node_txn[2].input.len(), 1);
4886         check_spends!(node_txn[2], chan_1.3);
4887
4888         mine_transaction(&nodes[1], &node_txn[1]);
4889         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4890
4891         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4892         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4893         assert_eq!(spend_txn.len(), 1);
4894         assert_eq!(spend_txn[0].input.len(), 1);
4895         check_spends!(spend_txn[0], node_txn[1]);
4896 }
4897
4898 #[test]
4899 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4900         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4901         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4902         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4903         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4904         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4905
4906         // Create some initial channels
4907         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4908
4909         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4910         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4911         assert_eq!(revoked_local_txn[0].input.len(), 1);
4912         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4913
4914         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4915         assert_eq!(revoked_local_txn[0].output.len(), 2);
4916
4917         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4918
4919         // B will generate HTLC-Success from revoked commitment tx
4920         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4921         check_closed_broadcast!(nodes[1], true);
4922         check_added_monitors!(nodes[1], 1);
4923         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4924         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4925
4926         assert_eq!(revoked_htlc_txn.len(), 2);
4927         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4928         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4929         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4930
4931         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4932         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4933         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4934
4935         // A will generate justice tx from B's revoked commitment/HTLC tx
4936         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4937         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4938         check_closed_broadcast!(nodes[0], true);
4939         check_added_monitors!(nodes[0], 1);
4940         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4941
4942         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4943         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4944
4945         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4946         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4947         // transactions next...
4948         assert_eq!(node_txn[0].input.len(), 2);
4949         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4950         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4951                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4952         } else {
4953                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4954                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4955         }
4956
4957         assert_eq!(node_txn[1].input.len(), 1);
4958         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4959
4960         check_spends!(node_txn[2], chan_1.3);
4961
4962         mine_transaction(&nodes[0], &node_txn[1]);
4963         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4964
4965         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4966         // didn't try to generate any new transactions.
4967
4968         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4969         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4970         assert_eq!(spend_txn.len(), 3);
4971         assert_eq!(spend_txn[0].input.len(), 1);
4972         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4973         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4974         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4975         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4976 }
4977
4978 #[test]
4979 fn test_onchain_to_onchain_claim() {
4980         // Test that in case of channel closure, we detect the state of output and claim HTLC
4981         // on downstream peer's remote commitment tx.
4982         // First, have C claim an HTLC against its own latest commitment transaction.
4983         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4984         // channel.
4985         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4986         // gets broadcast.
4987
4988         let chanmon_cfgs = create_chanmon_cfgs(3);
4989         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4990         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4991         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4992
4993         // Create some initial channels
4994         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4995         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4996
4997         // Ensure all nodes are at the same height
4998         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4999         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5000         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5001         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5002
5003         // Rebalance the network a bit by relaying one payment through all the channels ...
5004         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5005         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5006
5007         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5008         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5009         check_spends!(commitment_tx[0], chan_2.3);
5010         nodes[2].node.claim_funds(payment_preimage);
5011         check_added_monitors!(nodes[2], 1);
5012         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5013         assert!(updates.update_add_htlcs.is_empty());
5014         assert!(updates.update_fail_htlcs.is_empty());
5015         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5016         assert!(updates.update_fail_malformed_htlcs.is_empty());
5017
5018         mine_transaction(&nodes[2], &commitment_tx[0]);
5019         check_closed_broadcast!(nodes[2], true);
5020         check_added_monitors!(nodes[2], 1);
5021         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5022
5023         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5024         assert_eq!(c_txn.len(), 3);
5025         assert_eq!(c_txn[0], c_txn[2]);
5026         assert_eq!(commitment_tx[0], c_txn[1]);
5027         check_spends!(c_txn[1], chan_2.3);
5028         check_spends!(c_txn[2], c_txn[1]);
5029         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5030         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5031         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5032         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5033
5034         // 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
5035         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5036         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5037         check_added_monitors!(nodes[1], 1);
5038         let events = nodes[1].node.get_and_clear_pending_events();
5039         assert_eq!(events.len(), 2);
5040         match events[0] {
5041                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5042                 _ => panic!("Unexpected event"),
5043         }
5044         match events[1] {
5045                 Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
5046                         assert_eq!(fee_earned_msat, Some(1000));
5047                         assert_eq!(claim_from_onchain_tx, true);
5048                 },
5049                 _ => panic!("Unexpected event"),
5050         }
5051         {
5052                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5053                 // ChannelMonitor: claim tx
5054                 assert_eq!(b_txn.len(), 1);
5055                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5056                 b_txn.clear();
5057         }
5058         check_added_monitors!(nodes[1], 1);
5059         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5060         assert_eq!(msg_events.len(), 3);
5061         match msg_events[0] {
5062                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5063                 _ => panic!("Unexpected event"),
5064         }
5065         match msg_events[1] {
5066                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5067                 _ => panic!("Unexpected event"),
5068         }
5069         match msg_events[2] {
5070                 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, .. } } => {
5071                         assert!(update_add_htlcs.is_empty());
5072                         assert!(update_fail_htlcs.is_empty());
5073                         assert_eq!(update_fulfill_htlcs.len(), 1);
5074                         assert!(update_fail_malformed_htlcs.is_empty());
5075                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5076                 },
5077                 _ => panic!("Unexpected event"),
5078         };
5079         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5080         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5081         mine_transaction(&nodes[1], &commitment_tx[0]);
5082         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5083         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5084         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5085         assert_eq!(b_txn.len(), 3);
5086         check_spends!(b_txn[1], chan_1.3);
5087         check_spends!(b_txn[2], b_txn[1]);
5088         check_spends!(b_txn[0], commitment_tx[0]);
5089         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5090         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5091         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5092
5093         check_closed_broadcast!(nodes[1], true);
5094         check_added_monitors!(nodes[1], 1);
5095 }
5096
5097 #[test]
5098 fn test_duplicate_payment_hash_one_failure_one_success() {
5099         // Topology : A --> B --> C --> D
5100         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5101         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5102         // we forward one of the payments onwards to D.
5103         let chanmon_cfgs = create_chanmon_cfgs(4);
5104         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5105         // When this test was written, the default base fee floated based on the HTLC count.
5106         // It is now fixed, so we simply set the fee to the expected value here.
5107         let mut config = test_default_channel_config();
5108         config.channel_options.forwarding_fee_base_msat = 196;
5109         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5110                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5111         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5112
5113         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5114         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5115         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5116
5117         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5118         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5119         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5120         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5121         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5122
5123         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5124
5125         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, 0).unwrap();
5126         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5127         // script push size limit so that the below script length checks match
5128         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5129         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], vec![], 900000, TEST_FINAL_CLTV - 40);
5130         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5131
5132         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5133         assert_eq!(commitment_txn[0].input.len(), 1);
5134         check_spends!(commitment_txn[0], chan_2.3);
5135
5136         mine_transaction(&nodes[1], &commitment_txn[0]);
5137         check_closed_broadcast!(nodes[1], true);
5138         check_added_monitors!(nodes[1], 1);
5139         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5140         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5141
5142         let htlc_timeout_tx;
5143         { // Extract one of the two HTLC-Timeout transaction
5144                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5145                 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5146                 assert_eq!(node_txn.len(), 4);
5147                 check_spends!(node_txn[0], chan_2.3);
5148
5149                 check_spends!(node_txn[1], commitment_txn[0]);
5150                 assert_eq!(node_txn[1].input.len(), 1);
5151                 check_spends!(node_txn[2], commitment_txn[0]);
5152                 assert_eq!(node_txn[2].input.len(), 1);
5153                 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5154                 check_spends!(node_txn[3], commitment_txn[0]);
5155                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5156
5157                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5158                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5159                 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5160                 htlc_timeout_tx = node_txn[1].clone();
5161         }
5162
5163         nodes[2].node.claim_funds(our_payment_preimage);
5164         mine_transaction(&nodes[2], &commitment_txn[0]);
5165         check_added_monitors!(nodes[2], 2);
5166         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5167         let events = nodes[2].node.get_and_clear_pending_msg_events();
5168         match events[0] {
5169                 MessageSendEvent::UpdateHTLCs { .. } => {},
5170                 _ => panic!("Unexpected event"),
5171         }
5172         match events[1] {
5173                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5174                 _ => panic!("Unexepected event"),
5175         }
5176         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5177         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)
5178         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5179         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5180         assert_eq!(htlc_success_txn[0].input.len(), 1);
5181         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5182         assert_eq!(htlc_success_txn[1].input.len(), 1);
5183         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5184         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5185         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5186         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5187         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5188         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5189
5190         mine_transaction(&nodes[1], &htlc_timeout_tx);
5191         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5192         expect_pending_htlcs_forwardable!(nodes[1]);
5193         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5194         assert!(htlc_updates.update_add_htlcs.is_empty());
5195         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5196         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5197         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5198         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5199         check_added_monitors!(nodes[1], 1);
5200
5201         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5202         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5203         {
5204                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5205         }
5206         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5207
5208         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5209         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5210         // and nodes[2] fee) is rounded down and then claimed in full.
5211         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5212         expect_payment_forwarded!(nodes[1], Some(196*2), true);
5213         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5214         assert!(updates.update_add_htlcs.is_empty());
5215         assert!(updates.update_fail_htlcs.is_empty());
5216         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5217         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5218         assert!(updates.update_fail_malformed_htlcs.is_empty());
5219         check_added_monitors!(nodes[1], 1);
5220
5221         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5222         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5223
5224         let events = nodes[0].node.get_and_clear_pending_events();
5225         match events[0] {
5226                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
5227                         assert_eq!(*payment_preimage, our_payment_preimage);
5228                         assert_eq!(*payment_hash, duplicate_payment_hash);
5229                 }
5230                 _ => panic!("Unexpected event"),
5231         }
5232 }
5233
5234 #[test]
5235 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5236         let chanmon_cfgs = create_chanmon_cfgs(2);
5237         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5238         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5239         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5240
5241         // Create some initial channels
5242         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5243
5244         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5245         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5246         assert_eq!(local_txn.len(), 1);
5247         assert_eq!(local_txn[0].input.len(), 1);
5248         check_spends!(local_txn[0], chan_1.3);
5249
5250         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5251         nodes[1].node.claim_funds(payment_preimage);
5252         check_added_monitors!(nodes[1], 1);
5253         mine_transaction(&nodes[1], &local_txn[0]);
5254         check_added_monitors!(nodes[1], 1);
5255         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5256         let events = nodes[1].node.get_and_clear_pending_msg_events();
5257         match events[0] {
5258                 MessageSendEvent::UpdateHTLCs { .. } => {},
5259                 _ => panic!("Unexpected event"),
5260         }
5261         match events[1] {
5262                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5263                 _ => panic!("Unexepected event"),
5264         }
5265         let node_tx = {
5266                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5267                 assert_eq!(node_txn.len(), 3);
5268                 assert_eq!(node_txn[0], node_txn[2]);
5269                 assert_eq!(node_txn[1], local_txn[0]);
5270                 assert_eq!(node_txn[0].input.len(), 1);
5271                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5272                 check_spends!(node_txn[0], local_txn[0]);
5273                 node_txn[0].clone()
5274         };
5275
5276         mine_transaction(&nodes[1], &node_tx);
5277         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5278
5279         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5280         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5281         assert_eq!(spend_txn.len(), 1);
5282         assert_eq!(spend_txn[0].input.len(), 1);
5283         check_spends!(spend_txn[0], node_tx);
5284         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5285 }
5286
5287 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5288         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5289         // unrevoked commitment transaction.
5290         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5291         // a remote RAA before they could be failed backwards (and combinations thereof).
5292         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5293         // use the same payment hashes.
5294         // Thus, we use a six-node network:
5295         //
5296         // A \         / E
5297         //    - C - D -
5298         // B /         \ F
5299         // And test where C fails back to A/B when D announces its latest commitment transaction
5300         let chanmon_cfgs = create_chanmon_cfgs(6);
5301         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5302         // When this test was written, the default base fee floated based on the HTLC count.
5303         // It is now fixed, so we simply set the fee to the expected value here.
5304         let mut config = test_default_channel_config();
5305         config.channel_options.forwarding_fee_base_msat = 196;
5306         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5307                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5308         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5309
5310         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5311         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5312         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5313         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5314         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5315
5316         // Rebalance and check output sanity...
5317         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5318         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5319         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5320
5321         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5322         // 0th HTLC:
5323         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
5324         // 1st HTLC:
5325         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
5326         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5327         // 2nd HTLC:
5328         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
5329         // 3rd HTLC:
5330         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
5331         // 4th HTLC:
5332         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5333         // 5th HTLC:
5334         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5335         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5336         // 6th HTLC:
5337         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());
5338         // 7th HTLC:
5339         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());
5340
5341         // 8th HTLC:
5342         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5343         // 9th HTLC:
5344         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5345         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
5346
5347         // 10th HTLC:
5348         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
5349         // 11th HTLC:
5350         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5351         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());
5352
5353         // Double-check that six of the new HTLC were added
5354         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5355         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5356         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5357         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5358
5359         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5360         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5361         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5362         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5363         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5364         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5365         check_added_monitors!(nodes[4], 0);
5366         expect_pending_htlcs_forwardable!(nodes[4]);
5367         check_added_monitors!(nodes[4], 1);
5368
5369         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5370         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5371         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5372         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5373         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5374         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5375
5376         // Fail 3rd below-dust and 7th above-dust HTLCs
5377         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5378         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5379         check_added_monitors!(nodes[5], 0);
5380         expect_pending_htlcs_forwardable!(nodes[5]);
5381         check_added_monitors!(nodes[5], 1);
5382
5383         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5384         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5385         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5386         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5387
5388         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5389
5390         expect_pending_htlcs_forwardable!(nodes[3]);
5391         check_added_monitors!(nodes[3], 1);
5392         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5393         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5394         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5395         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5396         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5397         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5398         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5399         if deliver_last_raa {
5400                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5401         } else {
5402                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5403         }
5404
5405         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5406         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5407         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5408         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5409         //
5410         // We now broadcast the latest commitment transaction, which *should* result in failures for
5411         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5412         // the non-broadcast above-dust HTLCs.
5413         //
5414         // Alternatively, we may broadcast the previous commitment transaction, which should only
5415         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5416         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5417
5418         if announce_latest {
5419                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5420         } else {
5421                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5422         }
5423         let events = nodes[2].node.get_and_clear_pending_events();
5424         let close_event = if deliver_last_raa {
5425                 assert_eq!(events.len(), 2);
5426                 events[1].clone()
5427         } else {
5428                 assert_eq!(events.len(), 1);
5429                 events[0].clone()
5430         };
5431         match close_event {
5432                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5433                 _ => panic!("Unexpected event"),
5434         }
5435
5436         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5437         check_closed_broadcast!(nodes[2], true);
5438         if deliver_last_raa {
5439                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5440         } else {
5441                 expect_pending_htlcs_forwardable!(nodes[2]);
5442         }
5443         check_added_monitors!(nodes[2], 3);
5444
5445         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5446         assert_eq!(cs_msgs.len(), 2);
5447         let mut a_done = false;
5448         for msg in cs_msgs {
5449                 match msg {
5450                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5451                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5452                                 // should be failed-backwards here.
5453                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5454                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5455                                         for htlc in &updates.update_fail_htlcs {
5456                                                 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 });
5457                                         }
5458                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5459                                         assert!(!a_done);
5460                                         a_done = true;
5461                                         &nodes[0]
5462                                 } else {
5463                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5464                                         for htlc in &updates.update_fail_htlcs {
5465                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5466                                         }
5467                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5468                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5469                                         &nodes[1]
5470                                 };
5471                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5472                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5473                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5474                                 if announce_latest {
5475                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5476                                         if *node_id == nodes[0].node.get_our_node_id() {
5477                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5478                                         }
5479                                 }
5480                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5481                         },
5482                         _ => panic!("Unexpected event"),
5483                 }
5484         }
5485
5486         let as_events = nodes[0].node.get_and_clear_pending_events();
5487         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5488         let mut as_failds = HashSet::new();
5489         let mut as_updates = 0;
5490         for event in as_events.iter() {
5491                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5492                         assert!(as_failds.insert(*payment_hash));
5493                         if *payment_hash != payment_hash_2 {
5494                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5495                         } else {
5496                                 assert!(!rejected_by_dest);
5497                         }
5498                         if network_update.is_some() {
5499                                 as_updates += 1;
5500                         }
5501                 } else { panic!("Unexpected event"); }
5502         }
5503         assert!(as_failds.contains(&payment_hash_1));
5504         assert!(as_failds.contains(&payment_hash_2));
5505         if announce_latest {
5506                 assert!(as_failds.contains(&payment_hash_3));
5507                 assert!(as_failds.contains(&payment_hash_5));
5508         }
5509         assert!(as_failds.contains(&payment_hash_6));
5510
5511         let bs_events = nodes[1].node.get_and_clear_pending_events();
5512         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5513         let mut bs_failds = HashSet::new();
5514         let mut bs_updates = 0;
5515         for event in bs_events.iter() {
5516                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5517                         assert!(bs_failds.insert(*payment_hash));
5518                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5519                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5520                         } else {
5521                                 assert!(!rejected_by_dest);
5522                         }
5523                         if network_update.is_some() {
5524                                 bs_updates += 1;
5525                         }
5526                 } else { panic!("Unexpected event"); }
5527         }
5528         assert!(bs_failds.contains(&payment_hash_1));
5529         assert!(bs_failds.contains(&payment_hash_2));
5530         if announce_latest {
5531                 assert!(bs_failds.contains(&payment_hash_4));
5532         }
5533         assert!(bs_failds.contains(&payment_hash_5));
5534
5535         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5536         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5537         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5538         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5539         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5540         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5541 }
5542
5543 #[test]
5544 fn test_fail_backwards_latest_remote_announce_a() {
5545         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5546 }
5547
5548 #[test]
5549 fn test_fail_backwards_latest_remote_announce_b() {
5550         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5551 }
5552
5553 #[test]
5554 fn test_fail_backwards_previous_remote_announce() {
5555         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5556         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5557         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5558 }
5559
5560 #[test]
5561 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5562         let chanmon_cfgs = create_chanmon_cfgs(2);
5563         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5564         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5565         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5566
5567         // Create some initial channels
5568         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5569
5570         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5571         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5572         assert_eq!(local_txn[0].input.len(), 1);
5573         check_spends!(local_txn[0], chan_1.3);
5574
5575         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5576         mine_transaction(&nodes[0], &local_txn[0]);
5577         check_closed_broadcast!(nodes[0], true);
5578         check_added_monitors!(nodes[0], 1);
5579         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5580         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5581
5582         let htlc_timeout = {
5583                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5584                 assert_eq!(node_txn.len(), 2);
5585                 check_spends!(node_txn[0], chan_1.3);
5586                 assert_eq!(node_txn[1].input.len(), 1);
5587                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5588                 check_spends!(node_txn[1], local_txn[0]);
5589                 node_txn[1].clone()
5590         };
5591
5592         mine_transaction(&nodes[0], &htlc_timeout);
5593         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5594         expect_payment_failed!(nodes[0], our_payment_hash, true);
5595
5596         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5597         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5598         assert_eq!(spend_txn.len(), 3);
5599         check_spends!(spend_txn[0], local_txn[0]);
5600         assert_eq!(spend_txn[1].input.len(), 1);
5601         check_spends!(spend_txn[1], htlc_timeout);
5602         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5603         assert_eq!(spend_txn[2].input.len(), 2);
5604         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5605         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5606                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5607 }
5608
5609 #[test]
5610 fn test_key_derivation_params() {
5611         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5612         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5613         // let us re-derive the channel key set to then derive a delayed_payment_key.
5614
5615         let chanmon_cfgs = create_chanmon_cfgs(3);
5616
5617         // We manually create the node configuration to backup the seed.
5618         let seed = [42; 32];
5619         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5620         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);
5621         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() };
5622         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5623         node_cfgs.remove(0);
5624         node_cfgs.insert(0, node);
5625
5626         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5627         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5628
5629         // Create some initial channels
5630         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5631         // for node 0
5632         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5633         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5634         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5635
5636         // Ensure all nodes are at the same height
5637         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5638         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5639         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5640         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5641
5642         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5643         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5644         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5645         assert_eq!(local_txn_1[0].input.len(), 1);
5646         check_spends!(local_txn_1[0], chan_1.3);
5647
5648         // We check funding pubkey are unique
5649         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]));
5650         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]));
5651         if from_0_funding_key_0 == from_1_funding_key_0
5652             || from_0_funding_key_0 == from_1_funding_key_1
5653             || from_0_funding_key_1 == from_1_funding_key_0
5654             || from_0_funding_key_1 == from_1_funding_key_1 {
5655                 panic!("Funding pubkeys aren't unique");
5656         }
5657
5658         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5659         mine_transaction(&nodes[0], &local_txn_1[0]);
5660         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5661         check_closed_broadcast!(nodes[0], true);
5662         check_added_monitors!(nodes[0], 1);
5663         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5664
5665         let htlc_timeout = {
5666                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5667                 assert_eq!(node_txn[1].input.len(), 1);
5668                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5669                 check_spends!(node_txn[1], local_txn_1[0]);
5670                 node_txn[1].clone()
5671         };
5672
5673         mine_transaction(&nodes[0], &htlc_timeout);
5674         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5675         expect_payment_failed!(nodes[0], our_payment_hash, true);
5676
5677         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5678         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5679         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5680         assert_eq!(spend_txn.len(), 3);
5681         check_spends!(spend_txn[0], local_txn_1[0]);
5682         assert_eq!(spend_txn[1].input.len(), 1);
5683         check_spends!(spend_txn[1], htlc_timeout);
5684         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5685         assert_eq!(spend_txn[2].input.len(), 2);
5686         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5687         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5688                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5689 }
5690
5691 #[test]
5692 fn test_static_output_closing_tx() {
5693         let chanmon_cfgs = create_chanmon_cfgs(2);
5694         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5695         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5696         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5697
5698         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5699
5700         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5701         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5702
5703         mine_transaction(&nodes[0], &closing_tx);
5704         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5705         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5706
5707         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5708         assert_eq!(spend_txn.len(), 1);
5709         check_spends!(spend_txn[0], closing_tx);
5710
5711         mine_transaction(&nodes[1], &closing_tx);
5712         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5713         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5714
5715         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5716         assert_eq!(spend_txn.len(), 1);
5717         check_spends!(spend_txn[0], closing_tx);
5718 }
5719
5720 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5721         let chanmon_cfgs = create_chanmon_cfgs(2);
5722         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5723         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5724         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5725         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5726
5727         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5728
5729         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5730         // present in B's local commitment transaction, but none of A's commitment transactions.
5731         assert!(nodes[1].node.claim_funds(our_payment_preimage));
5732         check_added_monitors!(nodes[1], 1);
5733
5734         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5735         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5736         let events = nodes[0].node.get_and_clear_pending_events();
5737         assert_eq!(events.len(), 1);
5738         match events[0] {
5739                 Event::PaymentSent { payment_preimage, payment_hash } => {
5740                         assert_eq!(payment_preimage, our_payment_preimage);
5741                         assert_eq!(payment_hash, our_payment_hash);
5742                 },
5743                 _ => panic!("Unexpected event"),
5744         }
5745
5746         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5747         check_added_monitors!(nodes[0], 1);
5748         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5749         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5750         check_added_monitors!(nodes[1], 1);
5751
5752         let starting_block = nodes[1].best_block_info();
5753         let mut block = Block {
5754                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5755                 txdata: vec![],
5756         };
5757         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5758                 connect_block(&nodes[1], &block);
5759                 block.header.prev_blockhash = block.block_hash();
5760         }
5761         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5762         check_closed_broadcast!(nodes[1], true);
5763         check_added_monitors!(nodes[1], 1);
5764         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5765 }
5766
5767 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5768         let chanmon_cfgs = create_chanmon_cfgs(2);
5769         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5770         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5771         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5772         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5773
5774         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5775         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5776         check_added_monitors!(nodes[0], 1);
5777
5778         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5779
5780         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5781         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5782         // to "time out" the HTLC.
5783
5784         let starting_block = nodes[1].best_block_info();
5785         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5786
5787         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5788                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5789                 header.prev_blockhash = header.block_hash();
5790         }
5791         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5792         check_closed_broadcast!(nodes[0], true);
5793         check_added_monitors!(nodes[0], 1);
5794         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5795 }
5796
5797 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5798         let chanmon_cfgs = create_chanmon_cfgs(3);
5799         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5800         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5801         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5802         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5803
5804         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5805         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5806         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5807         // actually revoked.
5808         let htlc_value = if use_dust { 50000 } else { 3000000 };
5809         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5810         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5811         expect_pending_htlcs_forwardable!(nodes[1]);
5812         check_added_monitors!(nodes[1], 1);
5813
5814         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5815         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5816         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5817         check_added_monitors!(nodes[0], 1);
5818         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5819         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5820         check_added_monitors!(nodes[1], 1);
5821         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5822         check_added_monitors!(nodes[1], 1);
5823         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5824
5825         if check_revoke_no_close {
5826                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5827                 check_added_monitors!(nodes[0], 1);
5828         }
5829
5830         let starting_block = nodes[1].best_block_info();
5831         let mut block = Block {
5832                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5833                 txdata: vec![],
5834         };
5835         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5836                 connect_block(&nodes[0], &block);
5837                 block.header.prev_blockhash = block.block_hash();
5838         }
5839         if !check_revoke_no_close {
5840                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5841                 check_closed_broadcast!(nodes[0], true);
5842                 check_added_monitors!(nodes[0], 1);
5843                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5844         } else {
5845                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5846         }
5847 }
5848
5849 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5850 // There are only a few cases to test here:
5851 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5852 //    broadcastable commitment transactions result in channel closure,
5853 //  * its included in an unrevoked-but-previous remote commitment transaction,
5854 //  * its included in the latest remote or local commitment transactions.
5855 // We test each of the three possible commitment transactions individually and use both dust and
5856 // non-dust HTLCs.
5857 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5858 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5859 // tested for at least one of the cases in other tests.
5860 #[test]
5861 fn htlc_claim_single_commitment_only_a() {
5862         do_htlc_claim_local_commitment_only(true);
5863         do_htlc_claim_local_commitment_only(false);
5864
5865         do_htlc_claim_current_remote_commitment_only(true);
5866         do_htlc_claim_current_remote_commitment_only(false);
5867 }
5868
5869 #[test]
5870 fn htlc_claim_single_commitment_only_b() {
5871         do_htlc_claim_previous_remote_commitment_only(true, false);
5872         do_htlc_claim_previous_remote_commitment_only(false, false);
5873         do_htlc_claim_previous_remote_commitment_only(true, true);
5874         do_htlc_claim_previous_remote_commitment_only(false, true);
5875 }
5876
5877 #[test]
5878 #[should_panic]
5879 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5880         let chanmon_cfgs = create_chanmon_cfgs(2);
5881         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5882         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5883         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5884         //Force duplicate channel ids
5885         for node in nodes.iter() {
5886                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5887         }
5888
5889         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5890         let channel_value_satoshis=10000;
5891         let push_msat=10001;
5892         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5893         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5894         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5895
5896         //Create a second channel with a channel_id collision
5897         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5898 }
5899
5900 #[test]
5901 fn bolt2_open_channel_sending_node_checks_part2() {
5902         let chanmon_cfgs = create_chanmon_cfgs(2);
5903         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5904         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5905         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5906
5907         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5908         let channel_value_satoshis=2^24;
5909         let push_msat=10001;
5910         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5911
5912         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5913         let channel_value_satoshis=10000;
5914         // Test when push_msat is equal to 1000 * funding_satoshis.
5915         let push_msat=1000*channel_value_satoshis+1;
5916         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5917
5918         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5919         let channel_value_satoshis=10000;
5920         let push_msat=10001;
5921         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
5922         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5923         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5924
5925         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5926         // 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
5927         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5928
5929         // 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.
5930         assert!(BREAKDOWN_TIMEOUT>0);
5931         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5932
5933         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5934         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5935         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5936
5937         // 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.
5938         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5939         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5940         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5941         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5942         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5943 }
5944
5945 #[test]
5946 fn bolt2_open_channel_sane_dust_limit() {
5947         let chanmon_cfgs = create_chanmon_cfgs(2);
5948         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5949         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5950         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5951
5952         let channel_value_satoshis=1000000;
5953         let push_msat=10001;
5954         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5955         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5956         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5957         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5958
5959         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5960         let events = nodes[1].node.get_and_clear_pending_msg_events();
5961         let err_msg = match events[0] {
5962                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5963                         msg.clone()
5964                 },
5965                 _ => panic!("Unexpected event"),
5966         };
5967         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5968 }
5969
5970 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5971 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5972 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5973 // is no longer affordable once it's freed.
5974 #[test]
5975 fn test_fail_holding_cell_htlc_upon_free() {
5976         let chanmon_cfgs = create_chanmon_cfgs(2);
5977         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5978         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5979         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5980         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5981
5982         // First nodes[0] generates an update_fee, setting the channel's
5983         // pending_update_fee.
5984         {
5985                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5986                 *feerate_lock += 20;
5987         }
5988         nodes[0].node.timer_tick_occurred();
5989         check_added_monitors!(nodes[0], 1);
5990
5991         let events = nodes[0].node.get_and_clear_pending_msg_events();
5992         assert_eq!(events.len(), 1);
5993         let (update_msg, commitment_signed) = match events[0] {
5994                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5995                         (update_fee.as_ref(), commitment_signed)
5996                 },
5997                 _ => panic!("Unexpected event"),
5998         };
5999
6000         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6001
6002         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6003         let channel_reserve = chan_stat.channel_reserve_msat;
6004         let feerate = get_feerate!(nodes[0], chan.2);
6005
6006         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6007         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6008         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6009
6010         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6011         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6012         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6013         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6014
6015         // Flush the pending fee update.
6016         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6017         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6018         check_added_monitors!(nodes[1], 1);
6019         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6020         check_added_monitors!(nodes[0], 1);
6021
6022         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6023         // HTLC, but now that the fee has been raised the payment will now fail, causing
6024         // us to surface its failure to the user.
6025         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6026         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6027         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);
6028         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 {}",
6029                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6030         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6031
6032         // Check that the payment failed to be sent out.
6033         let events = nodes[0].node.get_and_clear_pending_events();
6034         assert_eq!(events.len(), 1);
6035         match &events[0] {
6036                 &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 } => {
6037                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6038                         assert_eq!(*rejected_by_dest, false);
6039                         assert_eq!(*all_paths_failed, true);
6040                         assert_eq!(*network_update, None);
6041                         assert_eq!(*short_channel_id, None);
6042                         assert_eq!(*error_code, None);
6043                         assert_eq!(*error_data, None);
6044                 },
6045                 _ => panic!("Unexpected event"),
6046         }
6047 }
6048
6049 // Test that if multiple HTLCs are released from the holding cell and one is
6050 // valid but the other is no longer valid upon release, the valid HTLC can be
6051 // successfully completed while the other one fails as expected.
6052 #[test]
6053 fn test_free_and_fail_holding_cell_htlcs() {
6054         let chanmon_cfgs = create_chanmon_cfgs(2);
6055         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6056         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6057         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6058         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6059
6060         // First nodes[0] generates an update_fee, setting the channel's
6061         // pending_update_fee.
6062         {
6063                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6064                 *feerate_lock += 200;
6065         }
6066         nodes[0].node.timer_tick_occurred();
6067         check_added_monitors!(nodes[0], 1);
6068
6069         let events = nodes[0].node.get_and_clear_pending_msg_events();
6070         assert_eq!(events.len(), 1);
6071         let (update_msg, commitment_signed) = match events[0] {
6072                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6073                         (update_fee.as_ref(), commitment_signed)
6074                 },
6075                 _ => panic!("Unexpected event"),
6076         };
6077
6078         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6079
6080         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6081         let channel_reserve = chan_stat.channel_reserve_msat;
6082         let feerate = get_feerate!(nodes[0], chan.2);
6083
6084         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6085         let amt_1 = 20000;
6086         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6087         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6088         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6089
6090         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6091         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6092         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6093         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6094         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6095         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6096         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6097
6098         // Flush the pending fee update.
6099         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6100         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6101         check_added_monitors!(nodes[1], 1);
6102         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6103         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6104         check_added_monitors!(nodes[0], 2);
6105
6106         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6107         // but now that the fee has been raised the second payment will now fail, causing us
6108         // to surface its failure to the user. The first payment should succeed.
6109         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6110         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6111         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);
6112         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 {}",
6113                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6114         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6115
6116         // Check that the second payment failed to be sent out.
6117         let events = nodes[0].node.get_and_clear_pending_events();
6118         assert_eq!(events.len(), 1);
6119         match &events[0] {
6120                 &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 } => {
6121                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6122                         assert_eq!(*rejected_by_dest, false);
6123                         assert_eq!(*all_paths_failed, true);
6124                         assert_eq!(*network_update, None);
6125                         assert_eq!(*short_channel_id, None);
6126                         assert_eq!(*error_code, None);
6127                         assert_eq!(*error_data, None);
6128                 },
6129                 _ => panic!("Unexpected event"),
6130         }
6131
6132         // Complete the first payment and the RAA from the fee update.
6133         let (payment_event, send_raa_event) = {
6134                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6135                 assert_eq!(msgs.len(), 2);
6136                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6137         };
6138         let raa = match send_raa_event {
6139                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6140                 _ => panic!("Unexpected event"),
6141         };
6142         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6143         check_added_monitors!(nodes[1], 1);
6144         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6145         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6146         let events = nodes[1].node.get_and_clear_pending_events();
6147         assert_eq!(events.len(), 1);
6148         match events[0] {
6149                 Event::PendingHTLCsForwardable { .. } => {},
6150                 _ => panic!("Unexpected event"),
6151         }
6152         nodes[1].node.process_pending_htlc_forwards();
6153         let events = nodes[1].node.get_and_clear_pending_events();
6154         assert_eq!(events.len(), 1);
6155         match events[0] {
6156                 Event::PaymentReceived { .. } => {},
6157                 _ => panic!("Unexpected event"),
6158         }
6159         nodes[1].node.claim_funds(payment_preimage_1);
6160         check_added_monitors!(nodes[1], 1);
6161         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6162         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6163         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6164         let events = nodes[0].node.get_and_clear_pending_events();
6165         assert_eq!(events.len(), 1);
6166         match events[0] {
6167                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
6168                         assert_eq!(*payment_preimage, payment_preimage_1);
6169                         assert_eq!(*payment_hash, payment_hash_1);
6170                 }
6171                 _ => panic!("Unexpected event"),
6172         }
6173 }
6174
6175 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6176 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6177 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6178 // once it's freed.
6179 #[test]
6180 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6181         let chanmon_cfgs = create_chanmon_cfgs(3);
6182         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6183         // When this test was written, the default base fee floated based on the HTLC count.
6184         // It is now fixed, so we simply set the fee to the expected value here.
6185         let mut config = test_default_channel_config();
6186         config.channel_options.forwarding_fee_base_msat = 196;
6187         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6188         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6189         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6190         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6191
6192         // First nodes[1] generates an update_fee, setting the channel's
6193         // pending_update_fee.
6194         {
6195                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6196                 *feerate_lock += 20;
6197         }
6198         nodes[1].node.timer_tick_occurred();
6199         check_added_monitors!(nodes[1], 1);
6200
6201         let events = nodes[1].node.get_and_clear_pending_msg_events();
6202         assert_eq!(events.len(), 1);
6203         let (update_msg, commitment_signed) = match events[0] {
6204                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6205                         (update_fee.as_ref(), commitment_signed)
6206                 },
6207                 _ => panic!("Unexpected event"),
6208         };
6209
6210         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6211
6212         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6213         let channel_reserve = chan_stat.channel_reserve_msat;
6214         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6215
6216         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6217         let feemsat = 239;
6218         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6219         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6220         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6221         let payment_event = {
6222                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6223                 check_added_monitors!(nodes[0], 1);
6224
6225                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6226                 assert_eq!(events.len(), 1);
6227
6228                 SendEvent::from_event(events.remove(0))
6229         };
6230         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6231         check_added_monitors!(nodes[1], 0);
6232         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6233         expect_pending_htlcs_forwardable!(nodes[1]);
6234
6235         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6236         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6237
6238         // Flush the pending fee update.
6239         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6240         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6241         check_added_monitors!(nodes[2], 1);
6242         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6243         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6244         check_added_monitors!(nodes[1], 2);
6245
6246         // A final RAA message is generated to finalize the fee update.
6247         let events = nodes[1].node.get_and_clear_pending_msg_events();
6248         assert_eq!(events.len(), 1);
6249
6250         let raa_msg = match &events[0] {
6251                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6252                         msg.clone()
6253                 },
6254                 _ => panic!("Unexpected event"),
6255         };
6256
6257         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6258         check_added_monitors!(nodes[2], 1);
6259         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6260
6261         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6262         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6263         assert_eq!(process_htlc_forwards_event.len(), 1);
6264         match &process_htlc_forwards_event[0] {
6265                 &Event::PendingHTLCsForwardable { .. } => {},
6266                 _ => panic!("Unexpected event"),
6267         }
6268
6269         // In response, we call ChannelManager's process_pending_htlc_forwards
6270         nodes[1].node.process_pending_htlc_forwards();
6271         check_added_monitors!(nodes[1], 1);
6272
6273         // This causes the HTLC to be failed backwards.
6274         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6275         assert_eq!(fail_event.len(), 1);
6276         let (fail_msg, commitment_signed) = match &fail_event[0] {
6277                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6278                         assert_eq!(updates.update_add_htlcs.len(), 0);
6279                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6280                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6281                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6282                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6283                 },
6284                 _ => panic!("Unexpected event"),
6285         };
6286
6287         // Pass the failure messages back to nodes[0].
6288         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6289         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6290
6291         // Complete the HTLC failure+removal process.
6292         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6293         check_added_monitors!(nodes[0], 1);
6294         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6295         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6296         check_added_monitors!(nodes[1], 2);
6297         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6298         assert_eq!(final_raa_event.len(), 1);
6299         let raa = match &final_raa_event[0] {
6300                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6301                 _ => panic!("Unexpected event"),
6302         };
6303         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6304         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6305         check_added_monitors!(nodes[0], 1);
6306 }
6307
6308 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6309 // 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.
6310 //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.
6311
6312 #[test]
6313 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6314         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6315         let chanmon_cfgs = create_chanmon_cfgs(2);
6316         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6317         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6318         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6319         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6320
6321         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6322         route.paths[0][0].fee_msat = 100;
6323
6324         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6325                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6326         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6327         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6328 }
6329
6330 #[test]
6331 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6332         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6333         let chanmon_cfgs = create_chanmon_cfgs(2);
6334         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6335         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6336         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6337         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6338
6339         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6340         route.paths[0][0].fee_msat = 0;
6341         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6342                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6343
6344         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6345         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6346 }
6347
6348 #[test]
6349 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6350         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6351         let chanmon_cfgs = create_chanmon_cfgs(2);
6352         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6353         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6354         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6355         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6356
6357         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6358         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6359         check_added_monitors!(nodes[0], 1);
6360         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6361         updates.update_add_htlcs[0].amount_msat = 0;
6362
6363         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6364         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6365         check_closed_broadcast!(nodes[1], true).unwrap();
6366         check_added_monitors!(nodes[1], 1);
6367         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6368 }
6369
6370 #[test]
6371 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6372         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6373         //It is enforced when constructing a route.
6374         let chanmon_cfgs = create_chanmon_cfgs(2);
6375         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6376         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6377         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6378         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6379
6380         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], vec![], 100000000, 500000001);
6381         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6382                 assert_eq!(err, &"Channel CLTV overflowed?"));
6383 }
6384
6385 #[test]
6386 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6387         //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.
6388         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6389         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6390         let chanmon_cfgs = create_chanmon_cfgs(2);
6391         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6392         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6393         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6394         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6395         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6396
6397         for i in 0..max_accepted_htlcs {
6398                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6399                 let payment_event = {
6400                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6401                         check_added_monitors!(nodes[0], 1);
6402
6403                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6404                         assert_eq!(events.len(), 1);
6405                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6406                                 assert_eq!(htlcs[0].htlc_id, i);
6407                         } else {
6408                                 assert!(false);
6409                         }
6410                         SendEvent::from_event(events.remove(0))
6411                 };
6412                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6413                 check_added_monitors!(nodes[1], 0);
6414                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6415
6416                 expect_pending_htlcs_forwardable!(nodes[1]);
6417                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6418         }
6419         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6420         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6421                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6422
6423         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6424         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6425 }
6426
6427 #[test]
6428 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6429         //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.
6430         let chanmon_cfgs = create_chanmon_cfgs(2);
6431         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6432         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6433         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6434         let channel_value = 100000;
6435         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6436         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6437
6438         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6439
6440         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6441         // Manually create a route over our max in flight (which our router normally automatically
6442         // limits us to.
6443         route.paths[0][0].fee_msat =  max_in_flight + 1;
6444         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6445                 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)));
6446
6447         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6448         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);
6449
6450         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6451 }
6452
6453 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6454 #[test]
6455 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6456         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6457         let chanmon_cfgs = create_chanmon_cfgs(2);
6458         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6459         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6460         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6461         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6462         let htlc_minimum_msat: u64;
6463         {
6464                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6465                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6466                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6467         }
6468
6469         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6470         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6471         check_added_monitors!(nodes[0], 1);
6472         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6473         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6474         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6475         assert!(nodes[1].node.list_channels().is_empty());
6476         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6477         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()));
6478         check_added_monitors!(nodes[1], 1);
6479         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6480 }
6481
6482 #[test]
6483 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6484         //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
6485         let chanmon_cfgs = create_chanmon_cfgs(2);
6486         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6487         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6488         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6489         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6490
6491         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6492         let channel_reserve = chan_stat.channel_reserve_msat;
6493         let feerate = get_feerate!(nodes[0], chan.2);
6494         // The 2* and +1 are for the fee spike reserve.
6495         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6496
6497         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6498         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6499         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6500         check_added_monitors!(nodes[0], 1);
6501         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6502
6503         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6504         // at this time channel-initiatee receivers are not required to enforce that senders
6505         // respect the fee_spike_reserve.
6506         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6507         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6508
6509         assert!(nodes[1].node.list_channels().is_empty());
6510         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6511         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6512         check_added_monitors!(nodes[1], 1);
6513         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6514 }
6515
6516 #[test]
6517 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6518         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6519         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6520         let chanmon_cfgs = create_chanmon_cfgs(2);
6521         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6522         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6523         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6524         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6525
6526         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6527         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6528         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6529         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6530         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6531         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6532
6533         let mut msg = msgs::UpdateAddHTLC {
6534                 channel_id: chan.2,
6535                 htlc_id: 0,
6536                 amount_msat: 1000,
6537                 payment_hash: our_payment_hash,
6538                 cltv_expiry: htlc_cltv,
6539                 onion_routing_packet: onion_packet.clone(),
6540         };
6541
6542         for i in 0..super::channel::OUR_MAX_HTLCS {
6543                 msg.htlc_id = i as u64;
6544                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6545         }
6546         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6547         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6548
6549         assert!(nodes[1].node.list_channels().is_empty());
6550         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6551         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6552         check_added_monitors!(nodes[1], 1);
6553         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6554 }
6555
6556 #[test]
6557 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6558         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6559         let chanmon_cfgs = create_chanmon_cfgs(2);
6560         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6561         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6562         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6563         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6564
6565         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6566         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6567         check_added_monitors!(nodes[0], 1);
6568         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6569         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6570         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6571
6572         assert!(nodes[1].node.list_channels().is_empty());
6573         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6574         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6575         check_added_monitors!(nodes[1], 1);
6576         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6577 }
6578
6579 #[test]
6580 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6581         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6582         let chanmon_cfgs = create_chanmon_cfgs(2);
6583         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6584         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6585         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6586
6587         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6588         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6589         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6590         check_added_monitors!(nodes[0], 1);
6591         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6592         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6593         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6594
6595         assert!(nodes[1].node.list_channels().is_empty());
6596         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6597         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6598         check_added_monitors!(nodes[1], 1);
6599         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6600 }
6601
6602 #[test]
6603 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6604         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6605         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6606         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6607         let chanmon_cfgs = create_chanmon_cfgs(2);
6608         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6609         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6610         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6611
6612         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6613         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6614         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6615         check_added_monitors!(nodes[0], 1);
6616         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6617         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6618
6619         //Disconnect and Reconnect
6620         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6621         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6622         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6623         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6624         assert_eq!(reestablish_1.len(), 1);
6625         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6626         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6627         assert_eq!(reestablish_2.len(), 1);
6628         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6629         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6630         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6631         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6632
6633         //Resend HTLC
6634         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6635         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6636         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6637         check_added_monitors!(nodes[1], 1);
6638         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6639
6640         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6641
6642         assert!(nodes[1].node.list_channels().is_empty());
6643         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6644         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6645         check_added_monitors!(nodes[1], 1);
6646         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6647 }
6648
6649 #[test]
6650 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6651         //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.
6652
6653         let chanmon_cfgs = create_chanmon_cfgs(2);
6654         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6655         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6656         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6657         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6658         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6659         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6660
6661         check_added_monitors!(nodes[0], 1);
6662         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6663         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6664
6665         let update_msg = msgs::UpdateFulfillHTLC{
6666                 channel_id: chan.2,
6667                 htlc_id: 0,
6668                 payment_preimage: our_payment_preimage,
6669         };
6670
6671         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6672
6673         assert!(nodes[0].node.list_channels().is_empty());
6674         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6675         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()));
6676         check_added_monitors!(nodes[0], 1);
6677         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6678 }
6679
6680 #[test]
6681 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6682         //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.
6683
6684         let chanmon_cfgs = create_chanmon_cfgs(2);
6685         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6686         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6687         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6688         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6689
6690         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6691         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6692         check_added_monitors!(nodes[0], 1);
6693         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6694         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6695
6696         let update_msg = msgs::UpdateFailHTLC{
6697                 channel_id: chan.2,
6698                 htlc_id: 0,
6699                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6700         };
6701
6702         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6703
6704         assert!(nodes[0].node.list_channels().is_empty());
6705         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6706         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()));
6707         check_added_monitors!(nodes[0], 1);
6708         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6709 }
6710
6711 #[test]
6712 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6713         //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions:     MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6714
6715         let chanmon_cfgs = create_chanmon_cfgs(2);
6716         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6717         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6718         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6719         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6720
6721         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6722         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6723         check_added_monitors!(nodes[0], 1);
6724         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6725         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6726         let update_msg = msgs::UpdateFailMalformedHTLC{
6727                 channel_id: chan.2,
6728                 htlc_id: 0,
6729                 sha256_of_onion: [1; 32],
6730                 failure_code: 0x8000,
6731         };
6732
6733         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6734
6735         assert!(nodes[0].node.list_channels().is_empty());
6736         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6737         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()));
6738         check_added_monitors!(nodes[0], 1);
6739         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6740 }
6741
6742 #[test]
6743 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6744         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6745
6746         let chanmon_cfgs = create_chanmon_cfgs(2);
6747         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6748         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6749         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6750         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6751
6752         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6753
6754         nodes[1].node.claim_funds(our_payment_preimage);
6755         check_added_monitors!(nodes[1], 1);
6756
6757         let events = nodes[1].node.get_and_clear_pending_msg_events();
6758         assert_eq!(events.len(), 1);
6759         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6760                 match events[0] {
6761                         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, .. } } => {
6762                                 assert!(update_add_htlcs.is_empty());
6763                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6764                                 assert!(update_fail_htlcs.is_empty());
6765                                 assert!(update_fail_malformed_htlcs.is_empty());
6766                                 assert!(update_fee.is_none());
6767                                 update_fulfill_htlcs[0].clone()
6768                         },
6769                         _ => panic!("Unexpected event"),
6770                 }
6771         };
6772
6773         update_fulfill_msg.htlc_id = 1;
6774
6775         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6776
6777         assert!(nodes[0].node.list_channels().is_empty());
6778         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6779         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6780         check_added_monitors!(nodes[0], 1);
6781         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6782 }
6783
6784 #[test]
6785 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6786         //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.
6787
6788         let chanmon_cfgs = create_chanmon_cfgs(2);
6789         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6790         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6791         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6792         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6793
6794         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6795
6796         nodes[1].node.claim_funds(our_payment_preimage);
6797         check_added_monitors!(nodes[1], 1);
6798
6799         let events = nodes[1].node.get_and_clear_pending_msg_events();
6800         assert_eq!(events.len(), 1);
6801         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6802                 match events[0] {
6803                         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, .. } } => {
6804                                 assert!(update_add_htlcs.is_empty());
6805                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6806                                 assert!(update_fail_htlcs.is_empty());
6807                                 assert!(update_fail_malformed_htlcs.is_empty());
6808                                 assert!(update_fee.is_none());
6809                                 update_fulfill_htlcs[0].clone()
6810                         },
6811                         _ => panic!("Unexpected event"),
6812                 }
6813         };
6814
6815         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6816
6817         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6818
6819         assert!(nodes[0].node.list_channels().is_empty());
6820         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6821         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6822         check_added_monitors!(nodes[0], 1);
6823         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6824 }
6825
6826 #[test]
6827 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6828         //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.
6829
6830         let chanmon_cfgs = create_chanmon_cfgs(2);
6831         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6832         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6833         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6834         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6835
6836         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6837         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6838         check_added_monitors!(nodes[0], 1);
6839
6840         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6841         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6842
6843         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6844         check_added_monitors!(nodes[1], 0);
6845         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6846
6847         let events = nodes[1].node.get_and_clear_pending_msg_events();
6848
6849         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6850                 match events[0] {
6851                         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, .. } } => {
6852                                 assert!(update_add_htlcs.is_empty());
6853                                 assert!(update_fulfill_htlcs.is_empty());
6854                                 assert!(update_fail_htlcs.is_empty());
6855                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6856                                 assert!(update_fee.is_none());
6857                                 update_fail_malformed_htlcs[0].clone()
6858                         },
6859                         _ => panic!("Unexpected event"),
6860                 }
6861         };
6862         update_msg.failure_code &= !0x8000;
6863         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6864
6865         assert!(nodes[0].node.list_channels().is_empty());
6866         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6867         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6868         check_added_monitors!(nodes[0], 1);
6869         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6870 }
6871
6872 #[test]
6873 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6874         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6875         //    * 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.
6876
6877         let chanmon_cfgs = create_chanmon_cfgs(3);
6878         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6879         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6880         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6881         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6882         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6883
6884         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6885
6886         //First hop
6887         let mut payment_event = {
6888                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6889                 check_added_monitors!(nodes[0], 1);
6890                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6891                 assert_eq!(events.len(), 1);
6892                 SendEvent::from_event(events.remove(0))
6893         };
6894         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6895         check_added_monitors!(nodes[1], 0);
6896         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6897         expect_pending_htlcs_forwardable!(nodes[1]);
6898         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6899         assert_eq!(events_2.len(), 1);
6900         check_added_monitors!(nodes[1], 1);
6901         payment_event = SendEvent::from_event(events_2.remove(0));
6902         assert_eq!(payment_event.msgs.len(), 1);
6903
6904         //Second Hop
6905         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6906         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6907         check_added_monitors!(nodes[2], 0);
6908         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6909
6910         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6911         assert_eq!(events_3.len(), 1);
6912         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6913                 match events_3[0] {
6914                         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 } } => {
6915                                 assert!(update_add_htlcs.is_empty());
6916                                 assert!(update_fulfill_htlcs.is_empty());
6917                                 assert!(update_fail_htlcs.is_empty());
6918                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6919                                 assert!(update_fee.is_none());
6920                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6921                         },
6922                         _ => panic!("Unexpected event"),
6923                 }
6924         };
6925
6926         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6927
6928         check_added_monitors!(nodes[1], 0);
6929         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6930         expect_pending_htlcs_forwardable!(nodes[1]);
6931         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6932         assert_eq!(events_4.len(), 1);
6933
6934         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6935         match events_4[0] {
6936                 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, .. } } => {
6937                         assert!(update_add_htlcs.is_empty());
6938                         assert!(update_fulfill_htlcs.is_empty());
6939                         assert_eq!(update_fail_htlcs.len(), 1);
6940                         assert!(update_fail_malformed_htlcs.is_empty());
6941                         assert!(update_fee.is_none());
6942                 },
6943                 _ => panic!("Unexpected event"),
6944         };
6945
6946         check_added_monitors!(nodes[1], 1);
6947 }
6948
6949 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6950         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6951         // 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
6952         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6953
6954         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6955         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6956         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6957         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6958         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6959         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6960
6961         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6962
6963         // We route 2 dust-HTLCs between A and B
6964         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6965         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6966         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6967
6968         // Cache one local commitment tx as previous
6969         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6970
6971         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6972         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
6973         check_added_monitors!(nodes[1], 0);
6974         expect_pending_htlcs_forwardable!(nodes[1]);
6975         check_added_monitors!(nodes[1], 1);
6976
6977         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6978         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6979         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6980         check_added_monitors!(nodes[0], 1);
6981
6982         // Cache one local commitment tx as lastest
6983         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6984
6985         let events = nodes[0].node.get_and_clear_pending_msg_events();
6986         match events[0] {
6987                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6988                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6989                 },
6990                 _ => panic!("Unexpected event"),
6991         }
6992         match events[1] {
6993                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6994                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6995                 },
6996                 _ => panic!("Unexpected event"),
6997         }
6998
6999         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7000         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7001         if announce_latest {
7002                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7003         } else {
7004                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7005         }
7006
7007         check_closed_broadcast!(nodes[0], true);
7008         check_added_monitors!(nodes[0], 1);
7009         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7010
7011         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7012         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7013         let events = nodes[0].node.get_and_clear_pending_events();
7014         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7015         assert_eq!(events.len(), 2);
7016         let mut first_failed = false;
7017         for event in events {
7018                 match event {
7019                         Event::PaymentPathFailed { payment_hash, .. } => {
7020                                 if payment_hash == payment_hash_1 {
7021                                         assert!(!first_failed);
7022                                         first_failed = true;
7023                                 } else {
7024                                         assert_eq!(payment_hash, payment_hash_2);
7025                                 }
7026                         }
7027                         _ => panic!("Unexpected event"),
7028                 }
7029         }
7030 }
7031
7032 #[test]
7033 fn test_failure_delay_dust_htlc_local_commitment() {
7034         do_test_failure_delay_dust_htlc_local_commitment(true);
7035         do_test_failure_delay_dust_htlc_local_commitment(false);
7036 }
7037
7038 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7039         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7040         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7041         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7042         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7043         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7044         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7045
7046         let chanmon_cfgs = create_chanmon_cfgs(3);
7047         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7048         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7049         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7050         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7051
7052         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7053
7054         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7055         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7056
7057         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7058         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7059
7060         // We revoked bs_commitment_tx
7061         if revoked {
7062                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7063                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7064         }
7065
7066         let mut timeout_tx = Vec::new();
7067         if local {
7068                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7069                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7070                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7071                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7072                 expect_payment_failed!(nodes[0], dust_hash, true);
7073
7074                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7075                 check_closed_broadcast!(nodes[0], true);
7076                 check_added_monitors!(nodes[0], 1);
7077                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7078                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7079                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7080                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7081                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7082                 mine_transaction(&nodes[0], &timeout_tx[0]);
7083                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7084                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7085         } else {
7086                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7087                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7088                 check_closed_broadcast!(nodes[0], true);
7089                 check_added_monitors!(nodes[0], 1);
7090                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7091                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7092                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7093                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7094                 if !revoked {
7095                         expect_payment_failed!(nodes[0], dust_hash, true);
7096                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7097                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7098                         mine_transaction(&nodes[0], &timeout_tx[0]);
7099                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7100                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7101                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7102                 } else {
7103                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7104                         // commitment tx
7105                         let events = nodes[0].node.get_and_clear_pending_events();
7106                         assert_eq!(events.len(), 2);
7107                         let first;
7108                         match events[0] {
7109                                 Event::PaymentPathFailed { payment_hash, .. } => {
7110                                         if payment_hash == dust_hash { first = true; }
7111                                         else { first = false; }
7112                                 },
7113                                 _ => panic!("Unexpected event"),
7114                         }
7115                         match events[1] {
7116                                 Event::PaymentPathFailed { payment_hash, .. } => {
7117                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7118                                         else { assert_eq!(payment_hash, dust_hash); }
7119                                 },
7120                                 _ => panic!("Unexpected event"),
7121                         }
7122                 }
7123         }
7124 }
7125
7126 #[test]
7127 fn test_sweep_outbound_htlc_failure_update() {
7128         do_test_sweep_outbound_htlc_failure_update(false, true);
7129         do_test_sweep_outbound_htlc_failure_update(false, false);
7130         do_test_sweep_outbound_htlc_failure_update(true, false);
7131 }
7132
7133 #[test]
7134 fn test_user_configurable_csv_delay() {
7135         // We test our channel constructors yield errors when we pass them absurd csv delay
7136
7137         let mut low_our_to_self_config = UserConfig::default();
7138         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7139         let mut high_their_to_self_config = UserConfig::default();
7140         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7141         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7142         let chanmon_cfgs = create_chanmon_cfgs(2);
7143         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7144         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7145         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7146
7147         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7148         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) {
7149                 match error {
7150                         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())); },
7151                         _ => panic!("Unexpected event"),
7152                 }
7153         } else { assert!(false) }
7154
7155         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7156         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7157         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7158         open_channel.to_self_delay = 200;
7159         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) {
7160                 match error {
7161                         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()));  },
7162                         _ => panic!("Unexpected event"),
7163                 }
7164         } else { assert!(false); }
7165
7166         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7167         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7168         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()));
7169         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7170         accept_channel.to_self_delay = 200;
7171         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7172         let reason_msg;
7173         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7174                 match action {
7175                         &ErrorAction::SendErrorMessage { ref msg } => {
7176                                 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()));
7177                                 reason_msg = msg.data.clone();
7178                         },
7179                         _ => { panic!(); }
7180                 }
7181         } else { panic!(); }
7182         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7183
7184         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7185         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7186         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7187         open_channel.to_self_delay = 200;
7188         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) {
7189                 match error {
7190                         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())); },
7191                         _ => panic!("Unexpected event"),
7192                 }
7193         } else { assert!(false); }
7194 }
7195
7196 #[test]
7197 fn test_data_loss_protect() {
7198         // We want to be sure that :
7199         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7200         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7201         // * we close channel in case of detecting other being fallen behind
7202         // * we are able to claim our own outputs thanks to to_remote being static
7203         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7204         let persister;
7205         let logger;
7206         let fee_estimator;
7207         let tx_broadcaster;
7208         let chain_source;
7209         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7210         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7211         // during signing due to revoked tx
7212         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7213         let keys_manager = &chanmon_cfgs[0].keys_manager;
7214         let monitor;
7215         let node_state_0;
7216         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7217         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7218         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7219
7220         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7221
7222         // Cache node A state before any channel update
7223         let previous_node_state = nodes[0].node.encode();
7224         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7225         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7226
7227         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7228         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7229
7230         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7231         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7232
7233         // Restore node A from previous state
7234         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7235         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7236         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7237         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7238         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7239         persister = test_utils::TestPersister::new();
7240         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7241         node_state_0 = {
7242                 let mut channel_monitors = HashMap::new();
7243                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7244                 <(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 {
7245                         keys_manager: keys_manager,
7246                         fee_estimator: &fee_estimator,
7247                         chain_monitor: &monitor,
7248                         logger: &logger,
7249                         tx_broadcaster: &tx_broadcaster,
7250                         default_config: UserConfig::default(),
7251                         channel_monitors,
7252                 }).unwrap().1
7253         };
7254         nodes[0].node = &node_state_0;
7255         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7256         nodes[0].chain_monitor = &monitor;
7257         nodes[0].chain_source = &chain_source;
7258
7259         check_added_monitors!(nodes[0], 1);
7260
7261         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7262         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7263
7264         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7265
7266         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7267         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7268         check_added_monitors!(nodes[0], 1);
7269
7270         {
7271                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7272                 assert_eq!(node_txn.len(), 0);
7273         }
7274
7275         let mut reestablish_1 = Vec::with_capacity(1);
7276         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7277                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7278                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7279                         reestablish_1.push(msg.clone());
7280                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7281                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7282                         match action {
7283                                 &ErrorAction::SendErrorMessage { ref msg } => {
7284                                         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");
7285                                 },
7286                                 _ => panic!("Unexpected event!"),
7287                         }
7288                 } else {
7289                         panic!("Unexpected event")
7290                 }
7291         }
7292
7293         // Check we close channel detecting A is fallen-behind
7294         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7295         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7296         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7297         check_added_monitors!(nodes[1], 1);
7298
7299         // Check A is able to claim to_remote output
7300         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7301         assert_eq!(node_txn.len(), 1);
7302         check_spends!(node_txn[0], chan.3);
7303         assert_eq!(node_txn[0].output.len(), 2);
7304         mine_transaction(&nodes[0], &node_txn[0]);
7305         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7306         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() });
7307         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7308         assert_eq!(spend_txn.len(), 1);
7309         check_spends!(spend_txn[0], node_txn[0]);
7310 }
7311
7312 #[test]
7313 fn test_check_htlc_underpaying() {
7314         // Send payment through A -> B but A is maliciously
7315         // sending a probe payment (i.e less than expected value0
7316         // to B, B should refuse payment.
7317
7318         let chanmon_cfgs = create_chanmon_cfgs(2);
7319         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7320         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7321         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7322
7323         // Create some initial channels
7324         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7325
7326         let scorer = Scorer::new(0);
7327         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();
7328         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7329         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, 0).unwrap();
7330         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7331         check_added_monitors!(nodes[0], 1);
7332
7333         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7334         assert_eq!(events.len(), 1);
7335         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7336         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7337         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7338
7339         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7340         // and then will wait a second random delay before failing the HTLC back:
7341         expect_pending_htlcs_forwardable!(nodes[1]);
7342         expect_pending_htlcs_forwardable!(nodes[1]);
7343
7344         // Node 3 is expecting payment of 100_000 but received 10_000,
7345         // it should fail htlc like we didn't know the preimage.
7346         nodes[1].node.process_pending_htlc_forwards();
7347
7348         let events = nodes[1].node.get_and_clear_pending_msg_events();
7349         assert_eq!(events.len(), 1);
7350         let (update_fail_htlc, commitment_signed) = match events[0] {
7351                 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 } } => {
7352                         assert!(update_add_htlcs.is_empty());
7353                         assert!(update_fulfill_htlcs.is_empty());
7354                         assert_eq!(update_fail_htlcs.len(), 1);
7355                         assert!(update_fail_malformed_htlcs.is_empty());
7356                         assert!(update_fee.is_none());
7357                         (update_fail_htlcs[0].clone(), commitment_signed)
7358                 },
7359                 _ => panic!("Unexpected event"),
7360         };
7361         check_added_monitors!(nodes[1], 1);
7362
7363         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7364         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7365
7366         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7367         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7368         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7369         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7370 }
7371
7372 #[test]
7373 fn test_announce_disable_channels() {
7374         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7375         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7376
7377         let chanmon_cfgs = create_chanmon_cfgs(2);
7378         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7379         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7380         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7381
7382         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7383         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7384         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7385
7386         // Disconnect peers
7387         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7388         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7389
7390         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7391         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7392         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7393         assert_eq!(msg_events.len(), 3);
7394         let mut chans_disabled: HashSet<u64> = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7395         for e in msg_events {
7396                 match e {
7397                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7398                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7399                                 // Check that each channel gets updated exactly once
7400                                 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7401                                         panic!("Generated ChannelUpdate for wrong chan!");
7402                                 }
7403                         },
7404                         _ => panic!("Unexpected event"),
7405                 }
7406         }
7407         // Reconnect peers
7408         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7409         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7410         assert_eq!(reestablish_1.len(), 3);
7411         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7412         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7413         assert_eq!(reestablish_2.len(), 3);
7414
7415         // Reestablish chan_1
7416         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7417         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7418         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7419         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7420         // Reestablish chan_2
7421         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7422         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7423         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7424         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7425         // Reestablish chan_3
7426         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7427         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7428         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7429         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7430
7431         nodes[0].node.timer_tick_occurred();
7432         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7433         nodes[0].node.timer_tick_occurred();
7434         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7435         assert_eq!(msg_events.len(), 3);
7436         chans_disabled = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7437         for e in msg_events {
7438                 match e {
7439                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7440                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7441                                 // Check that each channel gets updated exactly once
7442                                 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7443                                         panic!("Generated ChannelUpdate for wrong chan!");
7444                                 }
7445                         },
7446                         _ => panic!("Unexpected event"),
7447                 }
7448         }
7449 }
7450
7451 #[test]
7452 fn test_priv_forwarding_rejection() {
7453         // If we have a private channel with outbound liquidity, and
7454         // UserConfig::accept_forwards_to_priv_channels is set to false, we should reject any attempts
7455         // to forward through that channel.
7456         let chanmon_cfgs = create_chanmon_cfgs(3);
7457         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7458         let mut no_announce_cfg = test_default_channel_config();
7459         no_announce_cfg.channel_options.announced_channel = false;
7460         no_announce_cfg.accept_forwards_to_priv_channels = false;
7461         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]);
7462         let persister: test_utils::TestPersister;
7463         let new_chain_monitor: test_utils::TestChainMonitor;
7464         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
7465         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7466
7467         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;
7468
7469         // Note that the create_*_chan functions in utils requires announcement_signatures, which we do
7470         // not send for private channels.
7471         nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
7472         let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[2].node.get_our_node_id());
7473         nodes[2].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
7474         let accept_channel = get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
7475         nodes[1].node.handle_accept_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7476
7477         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[1], 1_000_000, 42);
7478         nodes[1].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
7479         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()));
7480         check_added_monitors!(nodes[2], 1);
7481
7482         let cs_funding_signed = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[1].node.get_our_node_id());
7483         nodes[1].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &cs_funding_signed);
7484         check_added_monitors!(nodes[1], 1);
7485
7486         let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[2].best_block_info().1 + 1);
7487         confirm_transaction_at(&nodes[1], &tx, conf_height);
7488         connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
7489         confirm_transaction_at(&nodes[2], &tx, conf_height);
7490         connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
7491         let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[2].node.get_our_node_id());
7492         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()));
7493         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7494         nodes[2].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
7495         get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7496
7497         assert!(nodes[0].node.list_usable_channels()[0].is_public);
7498         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
7499         assert!(!nodes[2].node.list_usable_channels()[0].is_public);
7500
7501         // We should always be able to forward through nodes[1] as long as its out through a public
7502         // channel:
7503         send_payment(&nodes[2], &[&nodes[1], &nodes[0]], 10_000);
7504
7505         // ... however, if we send to nodes[2], we will have to pass the private channel from nodes[1]
7506         // to nodes[2], which should be rejected:
7507         let route_hint = RouteHint(vec![RouteHintHop {
7508                 src_node_id: nodes[1].node.get_our_node_id(),
7509                 short_channel_id: nodes[2].node.list_channels()[0].short_channel_id.unwrap(),
7510                 fees: RoutingFees { base_msat: 1000, proportional_millionths: 0 },
7511                 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
7512                 htlc_minimum_msat: None,
7513                 htlc_maximum_msat: None,
7514         }]);
7515         let last_hops = vec![&route_hint];
7516         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);
7517
7518         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7519         check_added_monitors!(nodes[0], 1);
7520         let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7521         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7522         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
7523
7524         let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7525         assert!(htlc_fail_updates.update_add_htlcs.is_empty());
7526         assert_eq!(htlc_fail_updates.update_fail_htlcs.len(), 1);
7527         assert!(htlc_fail_updates.update_fail_malformed_htlcs.is_empty());
7528         assert!(htlc_fail_updates.update_fee.is_none());
7529
7530         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
7531         commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, true, true);
7532         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, nodes[2].node.list_channels()[0].short_channel_id.unwrap(), true);
7533
7534         // Now disconnect nodes[1] from its peers and restart with accept_forwards_to_priv_channels set
7535         // to true. Sadly there is currently no way to change it at runtime.
7536
7537         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7538         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7539
7540         let nodes_1_serialized = nodes[1].node.encode();
7541         let mut monitor_a_serialized = test_utils::TestVecWriter(Vec::new());
7542         let mut monitor_b_serialized = test_utils::TestVecWriter(Vec::new());
7543         get_monitor!(nodes[1], chan_id_1).write(&mut monitor_a_serialized).unwrap();
7544         get_monitor!(nodes[1], cs_funding_signed.channel_id).write(&mut monitor_b_serialized).unwrap();
7545
7546         persister = test_utils::TestPersister::new();
7547         let keys_manager = &chanmon_cfgs[1].keys_manager;
7548         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);
7549         nodes[1].chain_monitor = &new_chain_monitor;
7550
7551         let mut monitor_a_read = &monitor_a_serialized.0[..];
7552         let mut monitor_b_read = &monitor_b_serialized.0[..];
7553         let (_, mut monitor_a) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_a_read, keys_manager).unwrap();
7554         let (_, mut monitor_b) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_b_read, keys_manager).unwrap();
7555         assert!(monitor_a_read.is_empty());
7556         assert!(monitor_b_read.is_empty());
7557
7558         no_announce_cfg.accept_forwards_to_priv_channels = true;
7559
7560         let mut nodes_1_read = &nodes_1_serialized[..];
7561         let (_, nodes_1_deserialized_tmp) = {
7562                 let mut channel_monitors = HashMap::new();
7563                 channel_monitors.insert(monitor_a.get_funding_txo().0, &mut monitor_a);
7564                 channel_monitors.insert(monitor_b.get_funding_txo().0, &mut monitor_b);
7565                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
7566                         default_config: no_announce_cfg,
7567                         keys_manager,
7568                         fee_estimator: node_cfgs[1].fee_estimator,
7569                         chain_monitor: nodes[1].chain_monitor,
7570                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
7571                         logger: nodes[1].logger,
7572                         channel_monitors,
7573                 }).unwrap()
7574         };
7575         assert!(nodes_1_read.is_empty());
7576         nodes_1_deserialized = nodes_1_deserialized_tmp;
7577
7578         assert!(nodes[1].chain_monitor.watch_channel(monitor_a.get_funding_txo().0, monitor_a).is_ok());
7579         assert!(nodes[1].chain_monitor.watch_channel(monitor_b.get_funding_txo().0, monitor_b).is_ok());
7580         check_added_monitors!(nodes[1], 2);
7581         nodes[1].node = &nodes_1_deserialized;
7582
7583         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7584         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7585         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7586         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
7587         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
7588         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7589         get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7590         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
7591
7592         nodes[1].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7593         nodes[2].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7594         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[2].node.get_our_node_id());
7595         let cs_reestablish = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7596         nodes[2].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7597         nodes[1].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &cs_reestablish);
7598         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7599         get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7600
7601         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7602         check_added_monitors!(nodes[0], 1);
7603         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 10_000, our_payment_hash, our_payment_secret);
7604         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage);
7605 }
7606
7607 #[test]
7608 fn test_bump_penalty_txn_on_revoked_commitment() {
7609         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7610         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7611
7612         let chanmon_cfgs = create_chanmon_cfgs(2);
7613         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7614         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7615         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7616
7617         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7618
7619         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7620         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], vec![], 3000000, 30);
7621         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7622
7623         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7624         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7625         assert_eq!(revoked_txn[0].output.len(), 4);
7626         assert_eq!(revoked_txn[0].input.len(), 1);
7627         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7628         let revoked_txid = revoked_txn[0].txid();
7629
7630         let mut penalty_sum = 0;
7631         for outp in revoked_txn[0].output.iter() {
7632                 if outp.script_pubkey.is_v0_p2wsh() {
7633                         penalty_sum += outp.value;
7634                 }
7635         }
7636
7637         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7638         let header_114 = connect_blocks(&nodes[1], 14);
7639
7640         // Actually revoke tx by claiming a HTLC
7641         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7642         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7643         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7644         check_added_monitors!(nodes[1], 1);
7645
7646         // One or more justice tx should have been broadcast, check it
7647         let penalty_1;
7648         let feerate_1;
7649         {
7650                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7651                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7652                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7653                 assert_eq!(node_txn[0].output.len(), 1);
7654                 check_spends!(node_txn[0], revoked_txn[0]);
7655                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7656                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7657                 penalty_1 = node_txn[0].txid();
7658                 node_txn.clear();
7659         };
7660
7661         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7662         connect_blocks(&nodes[1], 15);
7663         let mut penalty_2 = penalty_1;
7664         let mut feerate_2 = 0;
7665         {
7666                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7667                 assert_eq!(node_txn.len(), 1);
7668                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7669                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7670                         assert_eq!(node_txn[0].output.len(), 1);
7671                         check_spends!(node_txn[0], revoked_txn[0]);
7672                         penalty_2 = node_txn[0].txid();
7673                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7674                         assert_ne!(penalty_2, penalty_1);
7675                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7676                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7677                         // Verify 25% bump heuristic
7678                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7679                         node_txn.clear();
7680                 }
7681         }
7682         assert_ne!(feerate_2, 0);
7683
7684         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7685         connect_blocks(&nodes[1], 1);
7686         let penalty_3;
7687         let mut feerate_3 = 0;
7688         {
7689                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7690                 assert_eq!(node_txn.len(), 1);
7691                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7692                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7693                         assert_eq!(node_txn[0].output.len(), 1);
7694                         check_spends!(node_txn[0], revoked_txn[0]);
7695                         penalty_3 = node_txn[0].txid();
7696                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7697                         assert_ne!(penalty_3, penalty_2);
7698                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7699                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7700                         // Verify 25% bump heuristic
7701                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7702                         node_txn.clear();
7703                 }
7704         }
7705         assert_ne!(feerate_3, 0);
7706
7707         nodes[1].node.get_and_clear_pending_events();
7708         nodes[1].node.get_and_clear_pending_msg_events();
7709 }
7710
7711 #[test]
7712 fn test_bump_penalty_txn_on_revoked_htlcs() {
7713         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7714         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7715
7716         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7717         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7718         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7719         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7720         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7721
7722         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7723         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7724         let scorer = Scorer::new(0);
7725         let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph,
7726                 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger, &scorer).unwrap();
7727         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7728         let route = get_route(&nodes[1].node.get_our_node_id(), &nodes[1].net_graph_msg_handler.network_graph,
7729                 &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger, &scorer).unwrap();
7730         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7731
7732         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7733         assert_eq!(revoked_local_txn[0].input.len(), 1);
7734         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7735
7736         // Revoke local commitment tx
7737         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7738
7739         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7740         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7741         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7742         check_closed_broadcast!(nodes[1], true);
7743         check_added_monitors!(nodes[1], 1);
7744         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7745         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7746
7747         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7748         assert_eq!(revoked_htlc_txn.len(), 3);
7749         check_spends!(revoked_htlc_txn[1], chan.3);
7750
7751         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7752         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7753         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7754
7755         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7756         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7757         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7758         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7759
7760         // Broadcast set of revoked txn on A
7761         let hash_128 = connect_blocks(&nodes[0], 40);
7762         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7763         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7764         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7765         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7766         let events = nodes[0].node.get_and_clear_pending_events();
7767         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7768         match events[1] {
7769                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7770                 _ => panic!("Unexpected event"),
7771         }
7772         let first;
7773         let feerate_1;
7774         let penalty_txn;
7775         {
7776                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7777                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7778                 // Verify claim tx are spending revoked HTLC txn
7779
7780                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7781                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7782                 // which are included in the same block (they are broadcasted because we scan the
7783                 // transactions linearly and generate claims as we go, they likely should be removed in the
7784                 // future).
7785                 assert_eq!(node_txn[0].input.len(), 1);
7786                 check_spends!(node_txn[0], revoked_local_txn[0]);
7787                 assert_eq!(node_txn[1].input.len(), 1);
7788                 check_spends!(node_txn[1], revoked_local_txn[0]);
7789                 assert_eq!(node_txn[2].input.len(), 1);
7790                 check_spends!(node_txn[2], revoked_local_txn[0]);
7791
7792                 // Each of the three justice transactions claim a separate (single) output of the three
7793                 // available, which we check here:
7794                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7795                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7796                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7797
7798                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7799                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7800
7801                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7802                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7803                 // a remote commitment tx has already been confirmed).
7804                 check_spends!(node_txn[3], chan.3);
7805
7806                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7807                 // output, checked above).
7808                 assert_eq!(node_txn[4].input.len(), 2);
7809                 assert_eq!(node_txn[4].output.len(), 1);
7810                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7811
7812                 first = node_txn[4].txid();
7813                 // Store both feerates for later comparison
7814                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7815                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7816                 penalty_txn = vec![node_txn[2].clone()];
7817                 node_txn.clear();
7818         }
7819
7820         // Connect one more block to see if bumped penalty are issued for HTLC txn
7821         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7822         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7823         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7824         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7825         {
7826                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7827                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7828
7829                 check_spends!(node_txn[0], revoked_local_txn[0]);
7830                 check_spends!(node_txn[1], revoked_local_txn[0]);
7831                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7832                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7833                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7834                 } else {
7835                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7836                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7837                 }
7838
7839                 node_txn.clear();
7840         };
7841
7842         // Few more blocks to confirm penalty txn
7843         connect_blocks(&nodes[0], 4);
7844         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7845         let header_144 = connect_blocks(&nodes[0], 9);
7846         let node_txn = {
7847                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7848                 assert_eq!(node_txn.len(), 1);
7849
7850                 assert_eq!(node_txn[0].input.len(), 2);
7851                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7852                 // Verify bumped tx is different and 25% bump heuristic
7853                 assert_ne!(first, node_txn[0].txid());
7854                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7855                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7856                 assert!(feerate_2 * 100 > feerate_1 * 125);
7857                 let txn = vec![node_txn[0].clone()];
7858                 node_txn.clear();
7859                 txn
7860         };
7861         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7862         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7863         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7864         connect_blocks(&nodes[0], 20);
7865         {
7866                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7867                 // We verify than no new transaction has been broadcast because previously
7868                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7869                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7870                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7871                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7872                 // up bumped justice generation.
7873                 assert_eq!(node_txn.len(), 0);
7874                 node_txn.clear();
7875         }
7876         check_closed_broadcast!(nodes[0], true);
7877         check_added_monitors!(nodes[0], 1);
7878 }
7879
7880 #[test]
7881 fn test_bump_penalty_txn_on_remote_commitment() {
7882         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7883         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7884
7885         // Create 2 HTLCs
7886         // Provide preimage for one
7887         // Check aggregation
7888
7889         let chanmon_cfgs = create_chanmon_cfgs(2);
7890         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7891         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7892         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7893
7894         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7895         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7896         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7897
7898         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7899         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7900         assert_eq!(remote_txn[0].output.len(), 4);
7901         assert_eq!(remote_txn[0].input.len(), 1);
7902         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7903
7904         // Claim a HTLC without revocation (provide B monitor with preimage)
7905         nodes[1].node.claim_funds(payment_preimage);
7906         mine_transaction(&nodes[1], &remote_txn[0]);
7907         check_added_monitors!(nodes[1], 2);
7908         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7909
7910         // One or more claim tx should have been broadcast, check it
7911         let timeout;
7912         let preimage;
7913         let preimage_bump;
7914         let feerate_timeout;
7915         let feerate_preimage;
7916         {
7917                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7918                 // 9 transactions including:
7919                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7920                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7921                 // 2 * HTLC-Success (one RBF bump we'll check later)
7922                 // 1 * HTLC-Timeout
7923                 assert_eq!(node_txn.len(), 8);
7924                 assert_eq!(node_txn[0].input.len(), 1);
7925                 assert_eq!(node_txn[6].input.len(), 1);
7926                 check_spends!(node_txn[0], remote_txn[0]);
7927                 check_spends!(node_txn[6], remote_txn[0]);
7928                 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7929                 preimage_bump = node_txn[3].clone();
7930
7931                 check_spends!(node_txn[1], chan.3);
7932                 check_spends!(node_txn[2], node_txn[1]);
7933                 assert_eq!(node_txn[1], node_txn[4]);
7934                 assert_eq!(node_txn[2], node_txn[5]);
7935
7936                 timeout = node_txn[6].txid();
7937                 let index = node_txn[6].input[0].previous_output.vout;
7938                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
7939                 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
7940
7941                 preimage = node_txn[0].txid();
7942                 let index = node_txn[0].input[0].previous_output.vout;
7943                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7944                 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7945
7946                 node_txn.clear();
7947         };
7948         assert_ne!(feerate_timeout, 0);
7949         assert_ne!(feerate_preimage, 0);
7950
7951         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7952         connect_blocks(&nodes[1], 15);
7953         {
7954                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7955                 assert_eq!(node_txn.len(), 1);
7956                 assert_eq!(node_txn[0].input.len(), 1);
7957                 assert_eq!(preimage_bump.input.len(), 1);
7958                 check_spends!(node_txn[0], remote_txn[0]);
7959                 check_spends!(preimage_bump, remote_txn[0]);
7960
7961                 let index = preimage_bump.input[0].previous_output.vout;
7962                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7963                 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
7964                 assert!(new_feerate * 100 > feerate_timeout * 125);
7965                 assert_ne!(timeout, preimage_bump.txid());
7966
7967                 let index = node_txn[0].input[0].previous_output.vout;
7968                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7969                 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7970                 assert!(new_feerate * 100 > feerate_preimage * 125);
7971                 assert_ne!(preimage, node_txn[0].txid());
7972
7973                 node_txn.clear();
7974         }
7975
7976         nodes[1].node.get_and_clear_pending_events();
7977         nodes[1].node.get_and_clear_pending_msg_events();
7978 }
7979
7980 #[test]
7981 fn test_counterparty_raa_skip_no_crash() {
7982         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7983         // commitment transaction, we would have happily carried on and provided them the next
7984         // commitment transaction based on one RAA forward. This would probably eventually have led to
7985         // channel closure, but it would not have resulted in funds loss. Still, our
7986         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7987         // check simply that the channel is closed in response to such an RAA, but don't check whether
7988         // we decide to punish our counterparty for revoking their funds (as we don't currently
7989         // implement that).
7990         let chanmon_cfgs = create_chanmon_cfgs(2);
7991         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7992         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7993         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7994         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7995
7996         let mut guard = nodes[0].node.channel_state.lock().unwrap();
7997         let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7998
7999         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8000
8001         // Make signer believe we got a counterparty signature, so that it allows the revocation
8002         keys.get_enforcement_state().last_holder_commitment -= 1;
8003         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8004
8005         // Must revoke without gaps
8006         keys.get_enforcement_state().last_holder_commitment -= 1;
8007         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8008
8009         keys.get_enforcement_state().last_holder_commitment -= 1;
8010         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8011                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8012
8013         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8014                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8015         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8016         check_added_monitors!(nodes[1], 1);
8017         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8018 }
8019
8020 #[test]
8021 fn test_bump_txn_sanitize_tracking_maps() {
8022         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8023         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8024
8025         let chanmon_cfgs = create_chanmon_cfgs(2);
8026         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8027         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8028         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8029
8030         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8031         // Lock HTLC in both directions
8032         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8033         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8034
8035         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8036         assert_eq!(revoked_local_txn[0].input.len(), 1);
8037         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8038
8039         // Revoke local commitment tx
8040         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8041
8042         // Broadcast set of revoked txn on A
8043         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8044         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8045         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8046
8047         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8048         check_closed_broadcast!(nodes[0], true);
8049         check_added_monitors!(nodes[0], 1);
8050         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8051         let penalty_txn = {
8052                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8053                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8054                 check_spends!(node_txn[0], revoked_local_txn[0]);
8055                 check_spends!(node_txn[1], revoked_local_txn[0]);
8056                 check_spends!(node_txn[2], revoked_local_txn[0]);
8057                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8058                 node_txn.clear();
8059                 penalty_txn
8060         };
8061         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8062         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8063         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8064         {
8065                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8066                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8067                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8068         }
8069 }
8070
8071 #[test]
8072 fn test_override_channel_config() {
8073         let chanmon_cfgs = create_chanmon_cfgs(2);
8074         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8075         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8076         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8077
8078         // Node0 initiates a channel to node1 using the override config.
8079         let mut override_config = UserConfig::default();
8080         override_config.own_channel_config.our_to_self_delay = 200;
8081
8082         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8083
8084         // Assert the channel created by node0 is using the override config.
8085         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8086         assert_eq!(res.channel_flags, 0);
8087         assert_eq!(res.to_self_delay, 200);
8088 }
8089
8090 #[test]
8091 fn test_override_0msat_htlc_minimum() {
8092         let mut zero_config = UserConfig::default();
8093         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8094         let chanmon_cfgs = create_chanmon_cfgs(2);
8095         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8096         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8097         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8098
8099         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8100         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8101         assert_eq!(res.htlc_minimum_msat, 1);
8102
8103         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8104         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8105         assert_eq!(res.htlc_minimum_msat, 1);
8106 }
8107
8108 #[test]
8109 fn test_simple_mpp() {
8110         // Simple test of sending a multi-path payment.
8111         let chanmon_cfgs = create_chanmon_cfgs(4);
8112         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8113         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8114         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8115
8116         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8117         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8118         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8119         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8120
8121         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8122         let path = route.paths[0].clone();
8123         route.paths.push(path);
8124         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8125         route.paths[0][0].short_channel_id = chan_1_id;
8126         route.paths[0][1].short_channel_id = chan_3_id;
8127         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8128         route.paths[1][0].short_channel_id = chan_2_id;
8129         route.paths[1][1].short_channel_id = chan_4_id;
8130         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8131         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8132 }
8133
8134 #[test]
8135 fn test_preimage_storage() {
8136         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8137         let chanmon_cfgs = create_chanmon_cfgs(2);
8138         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8139         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8140         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8141
8142         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8143
8144         {
8145                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, 42);
8146                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8147                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8148                 check_added_monitors!(nodes[0], 1);
8149                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8150                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8151                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8152                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8153         }
8154         // Note that after leaving the above scope we have no knowledge of any arguments or return
8155         // values from previous calls.
8156         expect_pending_htlcs_forwardable!(nodes[1]);
8157         let events = nodes[1].node.get_and_clear_pending_events();
8158         assert_eq!(events.len(), 1);
8159         match events[0] {
8160                 Event::PaymentReceived { ref purpose, .. } => {
8161                         match &purpose {
8162                                 PaymentPurpose::InvoicePayment { payment_preimage, user_payment_id, .. } => {
8163                                         assert_eq!(*user_payment_id, 42);
8164                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8165                                 },
8166                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8167                         }
8168                 },
8169                 _ => panic!("Unexpected event"),
8170         }
8171 }
8172
8173 #[test]
8174 fn test_secret_timeout() {
8175         // Simple test of payment secret storage time outs
8176         let chanmon_cfgs = create_chanmon_cfgs(2);
8177         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8178         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8179         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8180
8181         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8182
8183         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8184
8185         // We should fail to register the same payment hash twice, at least until we've connected a
8186         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8187         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8188                 assert_eq!(err, "Duplicate payment hash");
8189         } else { panic!(); }
8190         let mut block = {
8191                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8192                 Block {
8193                         header: BlockHeader {
8194                                 version: 0x2000000,
8195                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8196                                 merkle_root: Default::default(),
8197                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8198                         txdata: vec![],
8199                 }
8200         };
8201         connect_block(&nodes[1], &block);
8202         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8203                 assert_eq!(err, "Duplicate payment hash");
8204         } else { panic!(); }
8205
8206         // If we then connect the second block, we should be able to register the same payment hash
8207         // again with a different user_payment_id (this time getting a new payment secret).
8208         block.header.prev_blockhash = block.header.block_hash();
8209         block.header.time += 1;
8210         connect_block(&nodes[1], &block);
8211         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 42).unwrap();
8212         assert_ne!(payment_secret_1, our_payment_secret);
8213
8214         {
8215                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8216                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8217                 check_added_monitors!(nodes[0], 1);
8218                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8219                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8220                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8221                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8222         }
8223         // Note that after leaving the above scope we have no knowledge of any arguments or return
8224         // values from previous calls.
8225         expect_pending_htlcs_forwardable!(nodes[1]);
8226         let events = nodes[1].node.get_and_clear_pending_events();
8227         assert_eq!(events.len(), 1);
8228         match events[0] {
8229                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, user_payment_id }, .. } => {
8230                         assert!(payment_preimage.is_none());
8231                         assert_eq!(user_payment_id, 42);
8232                         assert_eq!(payment_secret, our_payment_secret);
8233                         // We don't actually have the payment preimage with which to claim this payment!
8234                 },
8235                 _ => panic!("Unexpected event"),
8236         }
8237 }
8238
8239 #[test]
8240 fn test_bad_secret_hash() {
8241         // Simple test of unregistered payment hash/invalid payment secret handling
8242         let chanmon_cfgs = create_chanmon_cfgs(2);
8243         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8244         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8245         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8246
8247         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8248
8249         let random_payment_hash = PaymentHash([42; 32]);
8250         let random_payment_secret = PaymentSecret([43; 32]);
8251         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8252         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8253
8254         // All the below cases should end up being handled exactly identically, so we macro the
8255         // resulting events.
8256         macro_rules! handle_unknown_invalid_payment_data {
8257                 () => {
8258                         check_added_monitors!(nodes[0], 1);
8259                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8260                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8261                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8262                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8263
8264                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8265                         // again to process the pending backwards-failure of the HTLC
8266                         expect_pending_htlcs_forwardable!(nodes[1]);
8267                         expect_pending_htlcs_forwardable!(nodes[1]);
8268                         check_added_monitors!(nodes[1], 1);
8269
8270                         // We should fail the payment back
8271                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8272                         match events.pop().unwrap() {
8273                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8274                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8275                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8276                                 },
8277                                 _ => panic!("Unexpected event"),
8278                         }
8279                 }
8280         }
8281
8282         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8283         // Error data is the HTLC value (100,000) and current block height
8284         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8285
8286         // Send a payment with the right payment hash but the wrong payment secret
8287         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8288         handle_unknown_invalid_payment_data!();
8289         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8290
8291         // Send a payment with a random payment hash, but the right payment secret
8292         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8293         handle_unknown_invalid_payment_data!();
8294         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8295
8296         // Send a payment with a random payment hash and random payment secret
8297         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8298         handle_unknown_invalid_payment_data!();
8299         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8300 }
8301
8302 #[test]
8303 fn test_update_err_monitor_lockdown() {
8304         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8305         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8306         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8307         //
8308         // This scenario may happen in a watchtower setup, where watchtower process a block height
8309         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8310         // commitment at same time.
8311
8312         let chanmon_cfgs = create_chanmon_cfgs(2);
8313         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8314         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8315         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8316
8317         // Create some initial channel
8318         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8319         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8320
8321         // Rebalance the network to generate htlc in the two directions
8322         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8323
8324         // Route a HTLC from node 0 to node 1 (but don't settle)
8325         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8326
8327         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8328         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8329         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8330         let persister = test_utils::TestPersister::new();
8331         let watchtower = {
8332                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8333                 let mut w = test_utils::TestVecWriter(Vec::new());
8334                 monitor.write(&mut w).unwrap();
8335                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8336                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8337                 assert!(new_monitor == *monitor);
8338                 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);
8339                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8340                 watchtower
8341         };
8342         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8343         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8344         // transaction lock time requirements here.
8345         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8346         watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8347
8348         // Try to update ChannelMonitor
8349         assert!(nodes[1].node.claim_funds(preimage));
8350         check_added_monitors!(nodes[1], 1);
8351         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8352         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8353         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8354         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8355                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8356                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8357                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8358                 } else { assert!(false); }
8359         } else { assert!(false); };
8360         // Our local monitor is in-sync and hasn't processed yet timeout
8361         check_added_monitors!(nodes[0], 1);
8362         let events = nodes[0].node.get_and_clear_pending_events();
8363         assert_eq!(events.len(), 1);
8364 }
8365
8366 #[test]
8367 fn test_concurrent_monitor_claim() {
8368         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8369         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8370         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8371         // state N+1 confirms. Alice claims output from state N+1.
8372
8373         let chanmon_cfgs = create_chanmon_cfgs(2);
8374         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8375         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8376         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8377
8378         // Create some initial channel
8379         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8380         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8381
8382         // Rebalance the network to generate htlc in the two directions
8383         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8384
8385         // Route a HTLC from node 0 to node 1 (but don't settle)
8386         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8387
8388         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8389         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8390         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8391         let persister = test_utils::TestPersister::new();
8392         let watchtower_alice = {
8393                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8394                 let mut w = test_utils::TestVecWriter(Vec::new());
8395                 monitor.write(&mut w).unwrap();
8396                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8397                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8398                 assert!(new_monitor == *monitor);
8399                 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);
8400                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8401                 watchtower
8402         };
8403         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8404         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8405         // transaction lock time requirements here.
8406         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8407         watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8408
8409         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8410         {
8411                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8412                 assert_eq!(txn.len(), 2);
8413                 txn.clear();
8414         }
8415
8416         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8417         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8418         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8419         let persister = test_utils::TestPersister::new();
8420         let watchtower_bob = {
8421                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8422                 let mut w = test_utils::TestVecWriter(Vec::new());
8423                 monitor.write(&mut w).unwrap();
8424                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8425                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8426                 assert!(new_monitor == *monitor);
8427                 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);
8428                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8429                 watchtower
8430         };
8431         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8432         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8433
8434         // Route another payment to generate another update with still previous HTLC pending
8435         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8436         {
8437                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8438         }
8439         check_added_monitors!(nodes[1], 1);
8440
8441         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8442         assert_eq!(updates.update_add_htlcs.len(), 1);
8443         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8444         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8445                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8446                         // Watchtower Alice should already have seen the block and reject the update
8447                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8448                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8449                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8450                 } else { assert!(false); }
8451         } else { assert!(false); };
8452         // Our local monitor is in-sync and hasn't processed yet timeout
8453         check_added_monitors!(nodes[0], 1);
8454
8455         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8456         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8457         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8458
8459         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8460         let bob_state_y;
8461         {
8462                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8463                 assert_eq!(txn.len(), 2);
8464                 bob_state_y = txn[0].clone();
8465                 txn.clear();
8466         };
8467
8468         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8469         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8470         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);
8471         {
8472                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8473                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8474                 // the onchain detection of the HTLC output
8475                 assert_eq!(htlc_txn.len(), 2);
8476                 check_spends!(htlc_txn[0], bob_state_y);
8477                 check_spends!(htlc_txn[1], bob_state_y);
8478         }
8479 }
8480
8481 #[test]
8482 fn test_pre_lockin_no_chan_closed_update() {
8483         // Test that if a peer closes a channel in response to a funding_created message we don't
8484         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8485         // message).
8486         //
8487         // Doing so would imply a channel monitor update before the initial channel monitor
8488         // registration, violating our API guarantees.
8489         //
8490         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8491         // then opening a second channel with the same funding output as the first (which is not
8492         // rejected because the first channel does not exist in the ChannelManager) and closing it
8493         // before receiving funding_signed.
8494         let chanmon_cfgs = create_chanmon_cfgs(2);
8495         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8496         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8497         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8498
8499         // Create an initial channel
8500         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8501         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8502         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8503         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8504         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8505
8506         // Move the first channel through the funding flow...
8507         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8508
8509         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8510         check_added_monitors!(nodes[0], 0);
8511
8512         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8513         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8514         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8515         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8516         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8517 }
8518
8519 #[test]
8520 fn test_htlc_no_detection() {
8521         // This test is a mutation to underscore the detection logic bug we had
8522         // before #653. HTLC value routed is above the remaining balance, thus
8523         // inverting HTLC and `to_remote` output. HTLC will come second and
8524         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8525         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8526         // outputs order detection for correct spending children filtring.
8527
8528         let chanmon_cfgs = create_chanmon_cfgs(2);
8529         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8530         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8531         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8532
8533         // Create some initial channels
8534         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8535
8536         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8537         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8538         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8539         assert_eq!(local_txn[0].input.len(), 1);
8540         assert_eq!(local_txn[0].output.len(), 3);
8541         check_spends!(local_txn[0], chan_1.3);
8542
8543         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8544         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8545         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8546         // We deliberately connect the local tx twice as this should provoke a failure calling
8547         // this test before #653 fix.
8548         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);
8549         check_closed_broadcast!(nodes[0], true);
8550         check_added_monitors!(nodes[0], 1);
8551         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8552         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8553
8554         let htlc_timeout = {
8555                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8556                 assert_eq!(node_txn[1].input.len(), 1);
8557                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8558                 check_spends!(node_txn[1], local_txn[0]);
8559                 node_txn[1].clone()
8560         };
8561
8562         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8563         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8564         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8565         expect_payment_failed!(nodes[0], our_payment_hash, true);
8566 }
8567
8568 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8569         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8570         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8571         // Carol, Alice would be the upstream node, and Carol the downstream.)
8572         //
8573         // Steps of the test:
8574         // 1) Alice sends a HTLC to Carol through Bob.
8575         // 2) Carol doesn't settle the HTLC.
8576         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8577         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8578         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8579         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8580         // 5) Carol release the preimage to Bob off-chain.
8581         // 6) Bob claims the offered output on the broadcasted commitment.
8582         let chanmon_cfgs = create_chanmon_cfgs(3);
8583         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8584         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8585         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8586
8587         // Create some initial channels
8588         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8589         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8590
8591         // Steps (1) and (2):
8592         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8593         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8594
8595         // Check that Alice's commitment transaction now contains an output for this HTLC.
8596         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8597         check_spends!(alice_txn[0], chan_ab.3);
8598         assert_eq!(alice_txn[0].output.len(), 2);
8599         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8600         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8601         assert_eq!(alice_txn.len(), 2);
8602
8603         // Steps (3) and (4):
8604         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8605         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8606         let mut force_closing_node = 0; // Alice force-closes
8607         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8608         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8609         check_closed_broadcast!(nodes[force_closing_node], true);
8610         check_added_monitors!(nodes[force_closing_node], 1);
8611         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8612         if go_onchain_before_fulfill {
8613                 let txn_to_broadcast = match broadcast_alice {
8614                         true => alice_txn.clone(),
8615                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8616                 };
8617                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8618                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8619                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8620                 if broadcast_alice {
8621                         check_closed_broadcast!(nodes[1], true);
8622                         check_added_monitors!(nodes[1], 1);
8623                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8624                 }
8625                 assert_eq!(bob_txn.len(), 1);
8626                 check_spends!(bob_txn[0], chan_ab.3);
8627         }
8628
8629         // Step (5):
8630         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8631         // process of removing the HTLC from their commitment transactions.
8632         assert!(nodes[2].node.claim_funds(payment_preimage));
8633         check_added_monitors!(nodes[2], 1);
8634         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8635         assert!(carol_updates.update_add_htlcs.is_empty());
8636         assert!(carol_updates.update_fail_htlcs.is_empty());
8637         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8638         assert!(carol_updates.update_fee.is_none());
8639         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8640
8641         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8642         expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8643         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8644         if !go_onchain_before_fulfill && broadcast_alice {
8645                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8646                 assert_eq!(events.len(), 1);
8647                 match events[0] {
8648                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8649                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8650                         },
8651                         _ => panic!("Unexpected event"),
8652                 };
8653         }
8654         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8655         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8656         // Carol<->Bob's updated commitment transaction info.
8657         check_added_monitors!(nodes[1], 2);
8658
8659         let events = nodes[1].node.get_and_clear_pending_msg_events();
8660         assert_eq!(events.len(), 2);
8661         let bob_revocation = match events[0] {
8662                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8663                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8664                         (*msg).clone()
8665                 },
8666                 _ => panic!("Unexpected event"),
8667         };
8668         let bob_updates = match events[1] {
8669                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8670                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8671                         (*updates).clone()
8672                 },
8673                 _ => panic!("Unexpected event"),
8674         };
8675
8676         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8677         check_added_monitors!(nodes[2], 1);
8678         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8679         check_added_monitors!(nodes[2], 1);
8680
8681         let events = nodes[2].node.get_and_clear_pending_msg_events();
8682         assert_eq!(events.len(), 1);
8683         let carol_revocation = match events[0] {
8684                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8685                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8686                         (*msg).clone()
8687                 },
8688                 _ => panic!("Unexpected event"),
8689         };
8690         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8691         check_added_monitors!(nodes[1], 1);
8692
8693         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8694         // here's where we put said channel's commitment tx on-chain.
8695         let mut txn_to_broadcast = alice_txn.clone();
8696         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8697         if !go_onchain_before_fulfill {
8698                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8699                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8700                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8701                 if broadcast_alice {
8702                         check_closed_broadcast!(nodes[1], true);
8703                         check_added_monitors!(nodes[1], 1);
8704                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8705                 }
8706                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8707                 if broadcast_alice {
8708                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8709                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8710                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8711                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8712                         // broadcasted.
8713                         assert_eq!(bob_txn.len(), 3);
8714                         check_spends!(bob_txn[1], chan_ab.3);
8715                 } else {
8716                         assert_eq!(bob_txn.len(), 2);
8717                         check_spends!(bob_txn[0], chan_ab.3);
8718                 }
8719         }
8720
8721         // Step (6):
8722         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8723         // broadcasted commitment transaction.
8724         {
8725                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8726                 if go_onchain_before_fulfill {
8727                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8728                         assert_eq!(bob_txn.len(), 2);
8729                 }
8730                 let script_weight = match broadcast_alice {
8731                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8732                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8733                 };
8734                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8735                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8736                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8737                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8738                 if broadcast_alice && !go_onchain_before_fulfill {
8739                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8740                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8741                 } else {
8742                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8743                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8744                 }
8745         }
8746 }
8747
8748 #[test]
8749 fn test_onchain_htlc_settlement_after_close() {
8750         do_test_onchain_htlc_settlement_after_close(true, true);
8751         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8752         do_test_onchain_htlc_settlement_after_close(true, false);
8753         do_test_onchain_htlc_settlement_after_close(false, false);
8754 }
8755
8756 #[test]
8757 fn test_duplicate_chan_id() {
8758         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8759         // already open we reject it and keep the old channel.
8760         //
8761         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8762         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8763         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8764         // updating logic for the existing channel.
8765         let chanmon_cfgs = create_chanmon_cfgs(2);
8766         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8767         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8768         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8769
8770         // Create an initial channel
8771         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8772         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8773         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8774         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()));
8775
8776         // Try to create a second channel with the same temporary_channel_id as the first and check
8777         // that it is rejected.
8778         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8779         {
8780                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8781                 assert_eq!(events.len(), 1);
8782                 match events[0] {
8783                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8784                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8785                                 // first (valid) and second (invalid) channels are closed, given they both have
8786                                 // the same non-temporary channel_id. However, currently we do not, so we just
8787                                 // move forward with it.
8788                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8789                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8790                         },
8791                         _ => panic!("Unexpected event"),
8792                 }
8793         }
8794
8795         // Move the first channel through the funding flow...
8796         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8797
8798         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8799         check_added_monitors!(nodes[0], 0);
8800
8801         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8802         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8803         {
8804                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8805                 assert_eq!(added_monitors.len(), 1);
8806                 assert_eq!(added_monitors[0].0, funding_output);
8807                 added_monitors.clear();
8808         }
8809         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8810
8811         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8812         let channel_id = funding_outpoint.to_channel_id();
8813
8814         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8815         // temporary one).
8816
8817         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8818         // Technically this is allowed by the spec, but we don't support it and there's little reason
8819         // to. Still, it shouldn't cause any other issues.
8820         open_chan_msg.temporary_channel_id = channel_id;
8821         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8822         {
8823                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8824                 assert_eq!(events.len(), 1);
8825                 match events[0] {
8826                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8827                                 // Technically, at this point, nodes[1] would be justified in thinking both
8828                                 // channels are closed, but currently we do not, so we just move forward with it.
8829                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8830                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8831                         },
8832                         _ => panic!("Unexpected event"),
8833                 }
8834         }
8835
8836         // Now try to create a second channel which has a duplicate funding output.
8837         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8838         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8839         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8840         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()));
8841         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8842
8843         let funding_created = {
8844                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8845                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8846                 let logger = test_utils::TestLogger::new();
8847                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8848         };
8849         check_added_monitors!(nodes[0], 0);
8850         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8851         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8852         // still needs to be cleared here.
8853         check_added_monitors!(nodes[1], 1);
8854
8855         // ...still, nodes[1] will reject the duplicate channel.
8856         {
8857                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8858                 assert_eq!(events.len(), 1);
8859                 match events[0] {
8860                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8861                                 // Technically, at this point, nodes[1] would be justified in thinking both
8862                                 // channels are closed, but currently we do not, so we just move forward with it.
8863                                 assert_eq!(msg.channel_id, channel_id);
8864                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8865                         },
8866                         _ => panic!("Unexpected event"),
8867                 }
8868         }
8869
8870         // finally, finish creating the original channel and send a payment over it to make sure
8871         // everything is functional.
8872         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8873         {
8874                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8875                 assert_eq!(added_monitors.len(), 1);
8876                 assert_eq!(added_monitors[0].0, funding_output);
8877                 added_monitors.clear();
8878         }
8879
8880         let events_4 = nodes[0].node.get_and_clear_pending_events();
8881         assert_eq!(events_4.len(), 0);
8882         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8883         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
8884
8885         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8886         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8887         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8888         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8889 }
8890
8891 #[test]
8892 fn test_error_chans_closed() {
8893         // Test that we properly handle error messages, closing appropriate channels.
8894         //
8895         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8896         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8897         // we can test various edge cases around it to ensure we don't regress.
8898         let chanmon_cfgs = create_chanmon_cfgs(3);
8899         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8900         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8901         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8902
8903         // Create some initial channels
8904         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8905         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8906         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8907
8908         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8909         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8910         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8911
8912         // Closing a channel from a different peer has no effect
8913         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8914         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8915
8916         // Closing one channel doesn't impact others
8917         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8918         check_added_monitors!(nodes[0], 1);
8919         check_closed_broadcast!(nodes[0], false);
8920         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8921         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8922         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8923         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);
8924         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);
8925
8926         // A null channel ID should close all channels
8927         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8928         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8929         check_added_monitors!(nodes[0], 2);
8930         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8931         let events = nodes[0].node.get_and_clear_pending_msg_events();
8932         assert_eq!(events.len(), 2);
8933         match events[0] {
8934                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8935                         assert_eq!(msg.contents.flags & 2, 2);
8936                 },
8937                 _ => panic!("Unexpected event"),
8938         }
8939         match events[1] {
8940                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8941                         assert_eq!(msg.contents.flags & 2, 2);
8942                 },
8943                 _ => panic!("Unexpected event"),
8944         }
8945         // Note that at this point users of a standard PeerHandler will end up calling
8946         // peer_disconnected with no_connection_possible set to false, duplicating the
8947         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8948         // users with their own peer handling logic. We duplicate the call here, however.
8949         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8950         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8951
8952         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8953         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8954         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8955 }
8956
8957 #[test]
8958 fn test_invalid_funding_tx() {
8959         // Test that we properly handle invalid funding transactions sent to us from a peer.
8960         //
8961         // Previously, all other major lightning implementations had failed to properly sanitize
8962         // funding transactions from their counterparties, leading to a multi-implementation critical
8963         // security vulnerability (though we always sanitized properly, we've previously had
8964         // un-released crashes in the sanitization process).
8965         let chanmon_cfgs = create_chanmon_cfgs(2);
8966         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8967         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8968         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8969
8970         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8971         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()));
8972         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()));
8973
8974         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
8975         for output in tx.output.iter_mut() {
8976                 // Make the confirmed funding transaction have a bogus script_pubkey
8977                 output.script_pubkey = bitcoin::Script::new();
8978         }
8979
8980         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
8981         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()));
8982         check_added_monitors!(nodes[1], 1);
8983
8984         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()));
8985         check_added_monitors!(nodes[0], 1);
8986
8987         let events_1 = nodes[0].node.get_and_clear_pending_events();
8988         assert_eq!(events_1.len(), 0);
8989
8990         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8991         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8992         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8993
8994         confirm_transaction_at(&nodes[1], &tx, 1);
8995         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8996         check_added_monitors!(nodes[1], 1);
8997         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8998         assert_eq!(events_2.len(), 1);
8999         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9000                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9001                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9002                         assert_eq!(msg.data, "funding tx had wrong script/value or output index");
9003                 } else { panic!(); }
9004         } else { panic!(); }
9005         assert_eq!(nodes[1].node.list_channels().len(), 0);
9006 }
9007
9008 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9009         // In the first version of the chain::Confirm interface, after a refactor was made to not
9010         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9011         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9012         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9013         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9014         // spending transaction until height N+1 (or greater). This was due to the way
9015         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9016         // spending transaction at the height the input transaction was confirmed at, not whether we
9017         // should broadcast a spending transaction at the current height.
9018         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9019         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9020         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9021         // until we learned about an additional block.
9022         //
9023         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9024         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9025         let chanmon_cfgs = create_chanmon_cfgs(3);
9026         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9027         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9028         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9029         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9030
9031         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9032         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9033         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9034         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9035         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9036
9037         nodes[1].node.force_close_channel(&channel_id).unwrap();
9038         check_closed_broadcast!(nodes[1], true);
9039         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9040         check_added_monitors!(nodes[1], 1);
9041         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9042         assert_eq!(node_txn.len(), 1);
9043
9044         let conf_height = nodes[1].best_block_info().1;
9045         if !test_height_before_timelock {
9046                 connect_blocks(&nodes[1], 24 * 6);
9047         }
9048         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9049                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9050         if test_height_before_timelock {
9051                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9052                 // generate any events or broadcast any transactions
9053                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9054                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9055         } else {
9056                 // We should broadcast an HTLC transaction spending our funding transaction first
9057                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9058                 assert_eq!(spending_txn.len(), 2);
9059                 assert_eq!(spending_txn[0], node_txn[0]);
9060                 check_spends!(spending_txn[1], node_txn[0]);
9061                 // We should also generate a SpendableOutputs event with the to_self output (as its
9062                 // timelock is up).
9063                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9064                 assert_eq!(descriptor_spend_txn.len(), 1);
9065
9066                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9067                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9068                 // additional block built on top of the current chain.
9069                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9070                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9071                 expect_pending_htlcs_forwardable!(nodes[1]);
9072                 check_added_monitors!(nodes[1], 1);
9073
9074                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9075                 assert!(updates.update_add_htlcs.is_empty());
9076                 assert!(updates.update_fulfill_htlcs.is_empty());
9077                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9078                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9079                 assert!(updates.update_fee.is_none());
9080                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9081                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9082                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9083         }
9084 }
9085
9086 #[test]
9087 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9088         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9089         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9090 }
9091
9092 #[test]
9093 fn test_forwardable_regen() {
9094         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9095         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9096         // HTLCs.
9097         // We test it for both payment receipt and payment forwarding.
9098
9099         let chanmon_cfgs = create_chanmon_cfgs(3);
9100         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9101         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9102         let persister: test_utils::TestPersister;
9103         let new_chain_monitor: test_utils::TestChainMonitor;
9104         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9105         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9106         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9107         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9108
9109         // First send a payment to nodes[1]
9110         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9111         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9112         check_added_monitors!(nodes[0], 1);
9113
9114         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9115         assert_eq!(events.len(), 1);
9116         let payment_event = SendEvent::from_event(events.pop().unwrap());
9117         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9118         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9119
9120         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9121
9122         // Next send a payment which is forwarded by nodes[1]
9123         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9124         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9125         check_added_monitors!(nodes[0], 1);
9126
9127         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9128         assert_eq!(events.len(), 1);
9129         let payment_event = SendEvent::from_event(events.pop().unwrap());
9130         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9131         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9132
9133         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9134         // generated
9135         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9136
9137         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9138         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9139         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9140
9141         let nodes_1_serialized = nodes[1].node.encode();
9142         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9143         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9144         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9145         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9146
9147         persister = test_utils::TestPersister::new();
9148         let keys_manager = &chanmon_cfgs[1].keys_manager;
9149         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);
9150         nodes[1].chain_monitor = &new_chain_monitor;
9151
9152         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9153         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9154                 &mut chan_0_monitor_read, keys_manager).unwrap();
9155         assert!(chan_0_monitor_read.is_empty());
9156         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9157         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9158                 &mut chan_1_monitor_read, keys_manager).unwrap();
9159         assert!(chan_1_monitor_read.is_empty());
9160
9161         let mut nodes_1_read = &nodes_1_serialized[..];
9162         let (_, nodes_1_deserialized_tmp) = {
9163                 let mut channel_monitors = HashMap::new();
9164                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9165                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9166                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9167                         default_config: UserConfig::default(),
9168                         keys_manager,
9169                         fee_estimator: node_cfgs[1].fee_estimator,
9170                         chain_monitor: nodes[1].chain_monitor,
9171                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9172                         logger: nodes[1].logger,
9173                         channel_monitors,
9174                 }).unwrap()
9175         };
9176         nodes_1_deserialized = nodes_1_deserialized_tmp;
9177         assert!(nodes_1_read.is_empty());
9178
9179         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9180         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9181         nodes[1].node = &nodes_1_deserialized;
9182         check_added_monitors!(nodes[1], 2);
9183
9184         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9185         // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9186         // the commitment state.
9187         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9188
9189         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9190
9191         expect_pending_htlcs_forwardable!(nodes[1]);
9192         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9193         check_added_monitors!(nodes[1], 1);
9194
9195         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9196         assert_eq!(events.len(), 1);
9197         let payment_event = SendEvent::from_event(events.pop().unwrap());
9198         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9199         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9200         expect_pending_htlcs_forwardable!(nodes[2]);
9201         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9202
9203         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9204         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9205 }
9206
9207 #[test]
9208 fn test_keysend_payments_to_public_node() {
9209         let chanmon_cfgs = create_chanmon_cfgs(2);
9210         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9211         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9212         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9213
9214         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9215         let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
9216         let payer_pubkey = nodes[0].node.get_our_node_id();
9217         let payee_pubkey = nodes[1].node.get_our_node_id();
9218         let scorer = Scorer::new(0);
9219         let route = get_keysend_route(
9220                 &payer_pubkey, &network_graph, &payee_pubkey, None, &vec![], 10000, 40, nodes[0].logger, &scorer
9221         ).unwrap();
9222
9223         let test_preimage = PaymentPreimage([42; 32]);
9224         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9225         check_added_monitors!(nodes[0], 1);
9226         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9227         assert_eq!(events.len(), 1);
9228         let event = events.pop().unwrap();
9229         let path = vec![&nodes[1]];
9230         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9231         claim_payment(&nodes[0], &path, test_preimage);
9232 }
9233
9234 #[test]
9235 fn test_keysend_payments_to_private_node() {
9236         let chanmon_cfgs = create_chanmon_cfgs(2);
9237         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9238         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9239         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9240
9241         let payer_pubkey = nodes[0].node.get_our_node_id();
9242         let payee_pubkey = nodes[1].node.get_our_node_id();
9243         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known() });
9244         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known() });
9245
9246         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9247         let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
9248         let first_hops = nodes[0].node.list_usable_channels();
9249         let scorer = Scorer::new(0);
9250         let route = get_keysend_route(
9251                 &payer_pubkey, &network_graph, &payee_pubkey, Some(&first_hops.iter().collect::<Vec<_>>()),
9252                 &vec![], 10000, 40, nodes[0].logger, &scorer
9253         ).unwrap();
9254
9255         let test_preimage = PaymentPreimage([42; 32]);
9256         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9257         check_added_monitors!(nodes[0], 1);
9258         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9259         assert_eq!(events.len(), 1);
9260         let event = events.pop().unwrap();
9261         let path = vec![&nodes[1]];
9262         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9263         claim_payment(&nodes[0], &path, test_preimage);
9264 }