ca4fa3b3563baf8cc041886429cebe554d17c5ee
[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;
26 use routing::network_graph::{NetworkUpdate, RoutingFees};
27 use routing::router::{Route, RouteHop, RouteHint, RouteHintHop, get_route, get_keysend_route};
28 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
29 use ln::msgs;
30 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
31 use util::enforcing_trait_impls::EnforcingSigner;
32 use util::{byte_utils, test_utils};
33 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
34 use util::errors::APIError;
35 use util::ser::{Writeable, ReadableArgs};
36 use util::config::UserConfig;
37
38 use bitcoin::hash_types::BlockHash;
39 use bitcoin::blockdata::block::{Block, BlockHeader};
40 use bitcoin::blockdata::script::Builder;
41 use bitcoin::blockdata::opcodes;
42 use bitcoin::blockdata::constants::genesis_block;
43 use bitcoin::network::constants::Network;
44
45 use bitcoin::hashes::sha256::Hash as Sha256;
46 use bitcoin::hashes::Hash;
47
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
50
51 use regex;
52
53 use io;
54 use prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use sync::{Arc, Mutex};
58
59 use ln::functional_test_utils::*;
60 use ln::chan_utils::CommitmentTransaction;
61
62 #[test]
63 fn test_insane_channel_opens() {
64         // Stand up a network of 2 nodes
65         let chanmon_cfgs = create_chanmon_cfgs(2);
66         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
67         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
68         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
69
70         // Instantiate channel parameters where we push the maximum msats given our
71         // funding satoshis
72         let channel_value_sat = 31337; // same as funding satoshis
73         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
74         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
75
76         // Have node0 initiate a channel to node1 with aforementioned parameters
77         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
78
79         // Extract the channel open message from node0 to node1
80         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
81
82         // Test helper that asserts we get the correct error string given a mutator
83         // that supposedly makes the channel open message insane
84         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
85                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
86                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
87                 assert_eq!(msg_events.len(), 1);
88                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
89                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
90                         match action {
91                                 &ErrorAction::SendErrorMessage { .. } => {
92                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
93                                 },
94                                 _ => panic!("unexpected event!"),
95                         }
96                 } else { assert!(false); }
97         };
98
99         use ln::channel::MAX_FUNDING_SATOSHIS;
100         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
101
102         // Test all mutations that would make the channel open message insane
103         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 });
104
105         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
106
107         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 });
108
109         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
110
111         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 });
112
113         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 });
114
115         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 });
116
117         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
118
119         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
120 }
121
122 #[test]
123 fn test_async_inbound_update_fee() {
124         let chanmon_cfgs = create_chanmon_cfgs(2);
125         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
126         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
127         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
128         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
129
130         // balancing
131         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
132
133         // A                                        B
134         // update_fee                            ->
135         // send (1) commitment_signed            -.
136         //                                       <- update_add_htlc/commitment_signed
137         // send (2) RAA (awaiting remote revoke) -.
138         // (1) commitment_signed is delivered    ->
139         //                                       .- send (3) RAA (awaiting remote revoke)
140         // (2) RAA is delivered                  ->
141         //                                       .- send (4) commitment_signed
142         //                                       <- (3) RAA is delivered
143         // send (5) commitment_signed            -.
144         //                                       <- (4) commitment_signed is delivered
145         // send (6) RAA                          -.
146         // (5) commitment_signed is delivered    ->
147         //                                       <- RAA
148         // (6) RAA is delivered                  ->
149
150         // First nodes[0] generates an update_fee
151         {
152                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
153                 *feerate_lock += 20;
154         }
155         nodes[0].node.timer_tick_occurred();
156         check_added_monitors!(nodes[0], 1);
157
158         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
159         assert_eq!(events_0.len(), 1);
160         let (update_msg, commitment_signed) = match events_0[0] { // (1)
161                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
162                         (update_fee.as_ref(), commitment_signed)
163                 },
164                 _ => panic!("Unexpected event"),
165         };
166
167         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
168
169         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
170         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
171         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
172         check_added_monitors!(nodes[1], 1);
173
174         let payment_event = {
175                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
176                 assert_eq!(events_1.len(), 1);
177                 SendEvent::from_event(events_1.remove(0))
178         };
179         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
180         assert_eq!(payment_event.msgs.len(), 1);
181
182         // ...now when the messages get delivered everyone should be happy
183         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
184         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
185         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
186         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
187         check_added_monitors!(nodes[0], 1);
188
189         // deliver(1), generate (3):
190         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
191         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
192         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
193         check_added_monitors!(nodes[1], 1);
194
195         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
196         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
197         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
198         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
199         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
200         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
201         assert!(bs_update.update_fee.is_none()); // (4)
202         check_added_monitors!(nodes[1], 1);
203
204         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
205         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
206         assert!(as_update.update_add_htlcs.is_empty()); // (5)
207         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
208         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
209         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
210         assert!(as_update.update_fee.is_none()); // (5)
211         check_added_monitors!(nodes[0], 1);
212
213         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
214         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
215         // only (6) so get_event_msg's assert(len == 1) passes
216         check_added_monitors!(nodes[0], 1);
217
218         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
219         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
220         check_added_monitors!(nodes[1], 1);
221
222         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
223         check_added_monitors!(nodes[0], 1);
224
225         let events_2 = nodes[0].node.get_and_clear_pending_events();
226         assert_eq!(events_2.len(), 1);
227         match events_2[0] {
228                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
229                 _ => panic!("Unexpected event"),
230         }
231
232         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
233         check_added_monitors!(nodes[1], 1);
234 }
235
236 #[test]
237 fn test_update_fee_unordered_raa() {
238         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
239         // crash in an earlier version of the update_fee patch)
240         let chanmon_cfgs = create_chanmon_cfgs(2);
241         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
242         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
243         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
244         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
245
246         // balancing
247         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
248
249         // First nodes[0] generates an update_fee
250         {
251                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
252                 *feerate_lock += 20;
253         }
254         nodes[0].node.timer_tick_occurred();
255         check_added_monitors!(nodes[0], 1);
256
257         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
258         assert_eq!(events_0.len(), 1);
259         let update_msg = match events_0[0] { // (1)
260                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
261                         update_fee.as_ref()
262                 },
263                 _ => panic!("Unexpected event"),
264         };
265
266         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
267
268         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
269         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
270         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
271         check_added_monitors!(nodes[1], 1);
272
273         let payment_event = {
274                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
275                 assert_eq!(events_1.len(), 1);
276                 SendEvent::from_event(events_1.remove(0))
277         };
278         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
279         assert_eq!(payment_event.msgs.len(), 1);
280
281         // ...now when the messages get delivered everyone should be happy
282         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
283         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
284         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
285         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
286         check_added_monitors!(nodes[0], 1);
287
288         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
289         check_added_monitors!(nodes[1], 1);
290
291         // We can't continue, sadly, because our (1) now has a bogus signature
292 }
293
294 #[test]
295 fn test_multi_flight_update_fee() {
296         let chanmon_cfgs = create_chanmon_cfgs(2);
297         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
298         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
299         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
300         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
301
302         // A                                        B
303         // update_fee/commitment_signed          ->
304         //                                       .- send (1) RAA and (2) commitment_signed
305         // update_fee (never committed)          ->
306         // (3) update_fee                        ->
307         // We have to manually generate the above update_fee, it is allowed by the protocol but we
308         // don't track which updates correspond to which revoke_and_ack responses so we're in
309         // AwaitingRAA mode and will not generate the update_fee yet.
310         //                                       <- (1) RAA delivered
311         // (3) is generated and send (4) CS      -.
312         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
313         // know the per_commitment_point to use for it.
314         //                                       <- (2) commitment_signed delivered
315         // revoke_and_ack                        ->
316         //                                          B should send no response here
317         // (4) commitment_signed delivered       ->
318         //                                       <- RAA/commitment_signed delivered
319         // revoke_and_ack                        ->
320
321         // First nodes[0] generates an update_fee
322         let initial_feerate;
323         {
324                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
325                 initial_feerate = *feerate_lock;
326                 *feerate_lock = initial_feerate + 20;
327         }
328         nodes[0].node.timer_tick_occurred();
329         check_added_monitors!(nodes[0], 1);
330
331         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
332         assert_eq!(events_0.len(), 1);
333         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
334                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
335                         (update_fee.as_ref().unwrap(), commitment_signed)
336                 },
337                 _ => panic!("Unexpected event"),
338         };
339
340         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
341         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
342         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
343         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
344         check_added_monitors!(nodes[1], 1);
345
346         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
347         // transaction:
348         {
349                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
350                 *feerate_lock = initial_feerate + 40;
351         }
352         nodes[0].node.timer_tick_occurred();
353         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
354         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
355
356         // Create the (3) update_fee message that nodes[0] will generate before it does...
357         let mut update_msg_2 = msgs::UpdateFee {
358                 channel_id: update_msg_1.channel_id.clone(),
359                 feerate_per_kw: (initial_feerate + 30) as u32,
360         };
361
362         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
363
364         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
365         // Deliver (3)
366         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
367
368         // Deliver (1), generating (3) and (4)
369         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
370         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
371         check_added_monitors!(nodes[0], 1);
372         assert!(as_second_update.update_add_htlcs.is_empty());
373         assert!(as_second_update.update_fulfill_htlcs.is_empty());
374         assert!(as_second_update.update_fail_htlcs.is_empty());
375         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
376         // Check that the update_fee newly generated matches what we delivered:
377         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
378         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
379
380         // Deliver (2) commitment_signed
381         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
382         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
383         check_added_monitors!(nodes[0], 1);
384         // No commitment_signed so get_event_msg's assert(len == 1) passes
385
386         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
387         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
388         check_added_monitors!(nodes[1], 1);
389
390         // Delever (4)
391         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
392         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
393         check_added_monitors!(nodes[1], 1);
394
395         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
396         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
397         check_added_monitors!(nodes[0], 1);
398
399         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
400         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
401         // No commitment_signed so get_event_msg's assert(len == 1) passes
402         check_added_monitors!(nodes[0], 1);
403
404         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
405         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
406         check_added_monitors!(nodes[1], 1);
407 }
408
409 fn do_test_1_conf_open(connect_style: ConnectStyle) {
410         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
411         // tests that we properly send one in that case.
412         let mut alice_config = UserConfig::default();
413         alice_config.own_channel_config.minimum_depth = 1;
414         alice_config.channel_options.announced_channel = true;
415         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
416         let mut bob_config = UserConfig::default();
417         bob_config.own_channel_config.minimum_depth = 1;
418         bob_config.channel_options.announced_channel = true;
419         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
420         let chanmon_cfgs = create_chanmon_cfgs(2);
421         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
422         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
423         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
424         *nodes[0].connect_style.borrow_mut() = connect_style;
425
426         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
427         mine_transaction(&nodes[1], &tx);
428         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()));
429
430         mine_transaction(&nodes[0], &tx);
431         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
432         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
433
434         for node in nodes {
435                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
436                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
437                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
438         }
439 }
440 #[test]
441 fn test_1_conf_open() {
442         do_test_1_conf_open(ConnectStyle::BestBlockFirst);
443         do_test_1_conf_open(ConnectStyle::TransactionsFirst);
444         do_test_1_conf_open(ConnectStyle::FullBlockViaListen);
445 }
446
447 fn do_test_sanity_on_in_flight_opens(steps: u8) {
448         // Previously, we had issues deserializing channels when we hadn't connected the first block
449         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
450         // serialization round-trips and simply do steps towards opening a channel and then drop the
451         // Node objects.
452
453         let chanmon_cfgs = create_chanmon_cfgs(2);
454         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
455         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
456         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
457
458         if steps & 0b1000_0000 != 0{
459                 let block = Block {
460                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
461                         txdata: vec![],
462                 };
463                 connect_block(&nodes[0], &block);
464                 connect_block(&nodes[1], &block);
465         }
466
467         if steps & 0x0f == 0 { return; }
468         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
469         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
470
471         if steps & 0x0f == 1 { return; }
472         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
473         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
474
475         if steps & 0x0f == 2 { return; }
476         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
477
478         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
479
480         if steps & 0x0f == 3 { return; }
481         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
482         check_added_monitors!(nodes[0], 0);
483         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
484
485         if steps & 0x0f == 4 { return; }
486         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
487         {
488                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
489                 assert_eq!(added_monitors.len(), 1);
490                 assert_eq!(added_monitors[0].0, funding_output);
491                 added_monitors.clear();
492         }
493         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
494
495         if steps & 0x0f == 5 { return; }
496         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
497         {
498                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
499                 assert_eq!(added_monitors.len(), 1);
500                 assert_eq!(added_monitors[0].0, funding_output);
501                 added_monitors.clear();
502         }
503
504         let events_4 = nodes[0].node.get_and_clear_pending_events();
505         assert_eq!(events_4.len(), 0);
506
507         if steps & 0x0f == 6 { return; }
508         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
509
510         if steps & 0x0f == 7 { return; }
511         confirm_transaction_at(&nodes[0], &tx, 2);
512         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
513         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
514 }
515
516 #[test]
517 fn test_sanity_on_in_flight_opens() {
518         do_test_sanity_on_in_flight_opens(0);
519         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
520         do_test_sanity_on_in_flight_opens(1);
521         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
522         do_test_sanity_on_in_flight_opens(2);
523         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
524         do_test_sanity_on_in_flight_opens(3);
525         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
526         do_test_sanity_on_in_flight_opens(4);
527         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
528         do_test_sanity_on_in_flight_opens(5);
529         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
530         do_test_sanity_on_in_flight_opens(6);
531         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
532         do_test_sanity_on_in_flight_opens(7);
533         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
534         do_test_sanity_on_in_flight_opens(8);
535         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
536 }
537
538 #[test]
539 fn test_update_fee_vanilla() {
540         let chanmon_cfgs = create_chanmon_cfgs(2);
541         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
542         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
543         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
544         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
545
546         {
547                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
548                 *feerate_lock += 25;
549         }
550         nodes[0].node.timer_tick_occurred();
551         check_added_monitors!(nodes[0], 1);
552
553         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
554         assert_eq!(events_0.len(), 1);
555         let (update_msg, commitment_signed) = match events_0[0] {
556                         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 } } => {
557                         (update_fee.as_ref(), commitment_signed)
558                 },
559                 _ => panic!("Unexpected event"),
560         };
561         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
562
563         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
564         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
565         check_added_monitors!(nodes[1], 1);
566
567         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
568         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
569         check_added_monitors!(nodes[0], 1);
570
571         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
572         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
573         // No commitment_signed so get_event_msg's assert(len == 1) passes
574         check_added_monitors!(nodes[0], 1);
575
576         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
577         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
578         check_added_monitors!(nodes[1], 1);
579 }
580
581 #[test]
582 fn test_update_fee_that_funder_cannot_afford() {
583         let chanmon_cfgs = create_chanmon_cfgs(2);
584         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
585         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
586         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
587         let channel_value = 1888;
588         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
589         let channel_id = chan.2;
590
591         let feerate = 260;
592         {
593                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
594                 *feerate_lock = feerate;
595         }
596         nodes[0].node.timer_tick_occurred();
597         check_added_monitors!(nodes[0], 1);
598         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
599
600         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
601
602         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
603
604         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
605         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
606         {
607                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
608
609                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
610                 let num_htlcs = commitment_tx.output.len() - 2;
611                 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
612                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
613                 actual_fee = channel_value - actual_fee;
614                 assert_eq!(total_fee, actual_fee);
615         }
616
617         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
618         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
619         {
620                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
621                 *feerate_lock = feerate + 2;
622         }
623         nodes[0].node.timer_tick_occurred();
624         check_added_monitors!(nodes[0], 1);
625
626         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
627
628         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
629
630         //While producing the commitment_signed response after handling a received update_fee request the
631         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
632         //Should produce and error.
633         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
634         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
635         check_added_monitors!(nodes[1], 1);
636         check_closed_broadcast!(nodes[1], true);
637         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
638 }
639
640 #[test]
641 fn test_update_fee_with_fundee_update_add_htlc() {
642         let chanmon_cfgs = create_chanmon_cfgs(2);
643         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
644         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
645         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
646         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
647
648         // balancing
649         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
650
651         {
652                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
653                 *feerate_lock += 20;
654         }
655         nodes[0].node.timer_tick_occurred();
656         check_added_monitors!(nodes[0], 1);
657
658         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
659         assert_eq!(events_0.len(), 1);
660         let (update_msg, commitment_signed) = match events_0[0] {
661                         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 } } => {
662                         (update_fee.as_ref(), commitment_signed)
663                 },
664                 _ => panic!("Unexpected event"),
665         };
666         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
667         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
668         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
669         check_added_monitors!(nodes[1], 1);
670
671         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
672
673         // nothing happens since node[1] is in AwaitingRemoteRevoke
674         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
675         {
676                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
677                 assert_eq!(added_monitors.len(), 0);
678                 added_monitors.clear();
679         }
680         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
681         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
682         // node[1] has nothing to do
683
684         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
685         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
686         check_added_monitors!(nodes[0], 1);
687
688         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
689         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
690         // No commitment_signed so get_event_msg's assert(len == 1) passes
691         check_added_monitors!(nodes[0], 1);
692         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
693         check_added_monitors!(nodes[1], 1);
694         // AwaitingRemoteRevoke ends here
695
696         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
697         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
698         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
699         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
700         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
701         assert_eq!(commitment_update.update_fee.is_none(), true);
702
703         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
704         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
705         check_added_monitors!(nodes[0], 1);
706         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
707
708         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
709         check_added_monitors!(nodes[1], 1);
710         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
711
712         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
713         check_added_monitors!(nodes[1], 1);
714         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
715         // No commitment_signed so get_event_msg's assert(len == 1) passes
716
717         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
718         check_added_monitors!(nodes[0], 1);
719         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
720
721         expect_pending_htlcs_forwardable!(nodes[0]);
722
723         let events = nodes[0].node.get_and_clear_pending_events();
724         assert_eq!(events.len(), 1);
725         match events[0] {
726                 Event::PaymentReceived { .. } => { },
727                 _ => panic!("Unexpected event"),
728         };
729
730         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
731
732         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
733         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
734         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
735         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
736         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
737 }
738
739 #[test]
740 fn test_update_fee() {
741         let chanmon_cfgs = create_chanmon_cfgs(2);
742         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
743         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
744         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
745         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
746         let channel_id = chan.2;
747
748         // A                                        B
749         // (1) update_fee/commitment_signed      ->
750         //                                       <- (2) revoke_and_ack
751         //                                       .- send (3) commitment_signed
752         // (4) update_fee/commitment_signed      ->
753         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
754         //                                       <- (3) commitment_signed delivered
755         // send (6) revoke_and_ack               -.
756         //                                       <- (5) deliver revoke_and_ack
757         // (6) deliver revoke_and_ack            ->
758         //                                       .- send (7) commitment_signed in response to (4)
759         //                                       <- (7) deliver commitment_signed
760         // revoke_and_ack                        ->
761
762         // Create and deliver (1)...
763         let feerate;
764         {
765                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
766                 feerate = *feerate_lock;
767                 *feerate_lock = feerate + 20;
768         }
769         nodes[0].node.timer_tick_occurred();
770         check_added_monitors!(nodes[0], 1);
771
772         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
773         assert_eq!(events_0.len(), 1);
774         let (update_msg, commitment_signed) = match events_0[0] {
775                         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 } } => {
776                         (update_fee.as_ref(), commitment_signed)
777                 },
778                 _ => panic!("Unexpected event"),
779         };
780         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
781
782         // Generate (2) and (3):
783         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
784         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
785         check_added_monitors!(nodes[1], 1);
786
787         // Deliver (2):
788         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
789         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
790         check_added_monitors!(nodes[0], 1);
791
792         // Create and deliver (4)...
793         {
794                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
795                 *feerate_lock = feerate + 30;
796         }
797         nodes[0].node.timer_tick_occurred();
798         check_added_monitors!(nodes[0], 1);
799         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
800         assert_eq!(events_0.len(), 1);
801         let (update_msg, commitment_signed) = match events_0[0] {
802                         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 } } => {
803                         (update_fee.as_ref(), commitment_signed)
804                 },
805                 _ => panic!("Unexpected event"),
806         };
807
808         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
809         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
810         check_added_monitors!(nodes[1], 1);
811         // ... creating (5)
812         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
813         // No commitment_signed so get_event_msg's assert(len == 1) passes
814
815         // Handle (3), creating (6):
816         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
817         check_added_monitors!(nodes[0], 1);
818         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
819         // No commitment_signed so get_event_msg's assert(len == 1) passes
820
821         // Deliver (5):
822         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
823         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
824         check_added_monitors!(nodes[0], 1);
825
826         // Deliver (6), creating (7):
827         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
828         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
829         assert!(commitment_update.update_add_htlcs.is_empty());
830         assert!(commitment_update.update_fulfill_htlcs.is_empty());
831         assert!(commitment_update.update_fail_htlcs.is_empty());
832         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
833         assert!(commitment_update.update_fee.is_none());
834         check_added_monitors!(nodes[1], 1);
835
836         // Deliver (7)
837         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
838         check_added_monitors!(nodes[0], 1);
839         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
840         // No commitment_signed so get_event_msg's assert(len == 1) passes
841
842         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
843         check_added_monitors!(nodes[1], 1);
844         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
845
846         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
847         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
848         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
849         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
850         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
851 }
852
853 #[test]
854 fn fake_network_test() {
855         // Simple test which builds a network of ChannelManagers, connects them to each other, and
856         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
857         let chanmon_cfgs = create_chanmon_cfgs(4);
858         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
859         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
860         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
861
862         // Create some initial channels
863         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
864         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
865         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
866
867         // Rebalance the network a bit by relaying one payment through all the channels...
868         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
869         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
870         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
871         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
872
873         // Send some more payments
874         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
875         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
876         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
877
878         // Test failure packets
879         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
880         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
881
882         // Add a new channel that skips 3
883         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
884
885         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
886         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
887         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
888         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
889         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
890         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
891         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
892
893         // Do some rebalance loop payments, simultaneously
894         let mut hops = Vec::with_capacity(3);
895         hops.push(RouteHop {
896                 pubkey: nodes[2].node.get_our_node_id(),
897                 node_features: NodeFeatures::empty(),
898                 short_channel_id: chan_2.0.contents.short_channel_id,
899                 channel_features: ChannelFeatures::empty(),
900                 fee_msat: 0,
901                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
902         });
903         hops.push(RouteHop {
904                 pubkey: nodes[3].node.get_our_node_id(),
905                 node_features: NodeFeatures::empty(),
906                 short_channel_id: chan_3.0.contents.short_channel_id,
907                 channel_features: ChannelFeatures::empty(),
908                 fee_msat: 0,
909                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
910         });
911         hops.push(RouteHop {
912                 pubkey: nodes[1].node.get_our_node_id(),
913                 node_features: NodeFeatures::known(),
914                 short_channel_id: chan_4.0.contents.short_channel_id,
915                 channel_features: ChannelFeatures::known(),
916                 fee_msat: 1000000,
917                 cltv_expiry_delta: TEST_FINAL_CLTV,
918         });
919         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;
920         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;
921         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
922
923         let mut hops = Vec::with_capacity(3);
924         hops.push(RouteHop {
925                 pubkey: nodes[3].node.get_our_node_id(),
926                 node_features: NodeFeatures::empty(),
927                 short_channel_id: chan_4.0.contents.short_channel_id,
928                 channel_features: ChannelFeatures::empty(),
929                 fee_msat: 0,
930                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
931         });
932         hops.push(RouteHop {
933                 pubkey: nodes[2].node.get_our_node_id(),
934                 node_features: NodeFeatures::empty(),
935                 short_channel_id: chan_3.0.contents.short_channel_id,
936                 channel_features: ChannelFeatures::empty(),
937                 fee_msat: 0,
938                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
939         });
940         hops.push(RouteHop {
941                 pubkey: nodes[1].node.get_our_node_id(),
942                 node_features: NodeFeatures::known(),
943                 short_channel_id: chan_2.0.contents.short_channel_id,
944                 channel_features: ChannelFeatures::known(),
945                 fee_msat: 1000000,
946                 cltv_expiry_delta: TEST_FINAL_CLTV,
947         });
948         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;
949         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;
950         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
951
952         // Claim the rebalances...
953         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
954         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
955
956         // Add a duplicate new channel from 2 to 4
957         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
958
959         // Send some payments across both channels
960         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
961         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
962         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
963
964
965         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
966         let events = nodes[0].node.get_and_clear_pending_msg_events();
967         assert_eq!(events.len(), 0);
968         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);
969
970         //TODO: Test that routes work again here as we've been notified that the channel is full
971
972         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
973         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
974         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
975
976         // Close down the channels...
977         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
978         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
979         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
980         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
981         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
982         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
983         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
984         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
985         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
986         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
987         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
988         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
989         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
990         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
991         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
992 }
993
994 #[test]
995 fn holding_cell_htlc_counting() {
996         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
997         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
998         // commitment dance rounds.
999         let chanmon_cfgs = create_chanmon_cfgs(3);
1000         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1001         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1002         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1003         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1004         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1005
1006         let mut payments = Vec::new();
1007         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1008                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1009                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1010                 payments.push((payment_preimage, payment_hash));
1011         }
1012         check_added_monitors!(nodes[1], 1);
1013
1014         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1015         assert_eq!(events.len(), 1);
1016         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1017         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1018
1019         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1020         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1021         // another HTLC.
1022         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1023         {
1024                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1025                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1026                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1027                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1028         }
1029
1030         // This should also be true if we try to forward a payment.
1031         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1032         {
1033                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1034                 check_added_monitors!(nodes[0], 1);
1035         }
1036
1037         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1038         assert_eq!(events.len(), 1);
1039         let payment_event = SendEvent::from_event(events.pop().unwrap());
1040         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1041
1042         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1043         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1044         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1045         // fails), the second will process the resulting failure and fail the HTLC backward.
1046         expect_pending_htlcs_forwardable!(nodes[1]);
1047         expect_pending_htlcs_forwardable!(nodes[1]);
1048         check_added_monitors!(nodes[1], 1);
1049
1050         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1051         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1052         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1053
1054         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1055
1056         // Now forward all the pending HTLCs and claim them back
1057         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1058         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1059         check_added_monitors!(nodes[2], 1);
1060
1061         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1062         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1063         check_added_monitors!(nodes[1], 1);
1064         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1065
1066         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1067         check_added_monitors!(nodes[1], 1);
1068         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1069
1070         for ref update in as_updates.update_add_htlcs.iter() {
1071                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1072         }
1073         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1074         check_added_monitors!(nodes[2], 1);
1075         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1076         check_added_monitors!(nodes[2], 1);
1077         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1078
1079         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1080         check_added_monitors!(nodes[1], 1);
1081         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1082         check_added_monitors!(nodes[1], 1);
1083         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1084
1085         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1086         check_added_monitors!(nodes[2], 1);
1087
1088         expect_pending_htlcs_forwardable!(nodes[2]);
1089
1090         let events = nodes[2].node.get_and_clear_pending_events();
1091         assert_eq!(events.len(), payments.len());
1092         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1093                 match event {
1094                         &Event::PaymentReceived { ref payment_hash, .. } => {
1095                                 assert_eq!(*payment_hash, *hash);
1096                         },
1097                         _ => panic!("Unexpected event"),
1098                 };
1099         }
1100
1101         for (preimage, _) in payments.drain(..) {
1102                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1103         }
1104
1105         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1106 }
1107
1108 #[test]
1109 fn duplicate_htlc_test() {
1110         // Test that we accept duplicate payment_hash HTLCs across the network and that
1111         // claiming/failing them are all separate and don't affect each other
1112         let chanmon_cfgs = create_chanmon_cfgs(6);
1113         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1114         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1115         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1116
1117         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1118         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1119         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1120         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1121         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1122         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1123
1124         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1125
1126         *nodes[0].network_payment_count.borrow_mut() -= 1;
1127         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1128
1129         *nodes[0].network_payment_count.borrow_mut() -= 1;
1130         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1131
1132         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1133         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1134         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1135 }
1136
1137 #[test]
1138 fn test_duplicate_htlc_different_direction_onchain() {
1139         // Test that ChannelMonitor doesn't generate 2 preimage txn
1140         // when we have 2 HTLCs with same preimage that go across a node
1141         // in opposite directions, even with the same payment secret.
1142         let chanmon_cfgs = create_chanmon_cfgs(2);
1143         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1144         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1145         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1146
1147         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1148
1149         // balancing
1150         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1151
1152         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1153
1154         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1155         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, 0).unwrap();
1156         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1157
1158         // Provide preimage to node 0 by claiming payment
1159         nodes[0].node.claim_funds(payment_preimage);
1160         check_added_monitors!(nodes[0], 1);
1161
1162         // Broadcast node 1 commitment txn
1163         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1164
1165         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1166         let mut has_both_htlcs = 0; // check htlcs match ones committed
1167         for outp in remote_txn[0].output.iter() {
1168                 if outp.value == 800_000 / 1000 {
1169                         has_both_htlcs += 1;
1170                 } else if outp.value == 900_000 / 1000 {
1171                         has_both_htlcs += 1;
1172                 }
1173         }
1174         assert_eq!(has_both_htlcs, 2);
1175
1176         mine_transaction(&nodes[0], &remote_txn[0]);
1177         check_added_monitors!(nodes[0], 1);
1178         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1179         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1180
1181         // Check we only broadcast 1 timeout tx
1182         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1183         assert_eq!(claim_txn.len(), 8);
1184         assert_eq!(claim_txn[1], claim_txn[4]);
1185         assert_eq!(claim_txn[2], claim_txn[5]);
1186         check_spends!(claim_txn[1], chan_1.3);
1187         check_spends!(claim_txn[2], claim_txn[1]);
1188         check_spends!(claim_txn[7], claim_txn[1]);
1189
1190         assert_eq!(claim_txn[0].input.len(), 1);
1191         assert_eq!(claim_txn[3].input.len(), 1);
1192         assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1193
1194         assert_eq!(claim_txn[0].input.len(), 1);
1195         assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1196         check_spends!(claim_txn[0], remote_txn[0]);
1197         assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1198         assert_eq!(claim_txn[6].input.len(), 1);
1199         assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1200         check_spends!(claim_txn[6], remote_txn[0]);
1201         assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1202
1203         let events = nodes[0].node.get_and_clear_pending_msg_events();
1204         assert_eq!(events.len(), 3);
1205         for e in events {
1206                 match e {
1207                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1208                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1209                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1210                                 assert_eq!(msg.data, "Commitment or closing transaction was confirmed on chain.");
1211                         },
1212                         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, .. } } => {
1213                                 assert!(update_add_htlcs.is_empty());
1214                                 assert!(update_fail_htlcs.is_empty());
1215                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1216                                 assert!(update_fail_malformed_htlcs.is_empty());
1217                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1218                         },
1219                         _ => panic!("Unexpected event"),
1220                 }
1221         }
1222 }
1223
1224 #[test]
1225 fn test_basic_channel_reserve() {
1226         let chanmon_cfgs = create_chanmon_cfgs(2);
1227         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1228         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1229         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1230         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1231
1232         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1233         let channel_reserve = chan_stat.channel_reserve_msat;
1234
1235         // The 2* and +1 are for the fee spike reserve.
1236         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1237         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1238         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1239         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1240         match err {
1241                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1242                         match &fails[0] {
1243                                 &APIError::ChannelUnavailable{ref err} =>
1244                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1245                                 _ => panic!("Unexpected error variant"),
1246                         }
1247                 },
1248                 _ => panic!("Unexpected error variant"),
1249         }
1250         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1251         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);
1252
1253         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1254 }
1255
1256 #[test]
1257 fn test_fee_spike_violation_fails_htlc() {
1258         let chanmon_cfgs = create_chanmon_cfgs(2);
1259         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1260         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1261         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1262         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1263
1264         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1265         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1266         let secp_ctx = Secp256k1::new();
1267         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1268
1269         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1270
1271         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1272         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1273         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1274         let msg = msgs::UpdateAddHTLC {
1275                 channel_id: chan.2,
1276                 htlc_id: 0,
1277                 amount_msat: htlc_msat,
1278                 payment_hash: payment_hash,
1279                 cltv_expiry: htlc_cltv,
1280                 onion_routing_packet: onion_packet,
1281         };
1282
1283         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1284
1285         // Now manually create the commitment_signed message corresponding to the update_add
1286         // nodes[0] just sent. In the code for construction of this message, "local" refers
1287         // to the sender of the message, and "remote" refers to the receiver.
1288
1289         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1290
1291         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1292
1293         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1294         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1295         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1296                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1297                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1298                 let chan_signer = local_chan.get_signer();
1299                 // Make the signer believe we validated another commitment, so we can release the secret
1300                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1301
1302                 let pubkeys = chan_signer.pubkeys();
1303                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1304                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1305                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1306                  chan_signer.pubkeys().funding_pubkey)
1307         };
1308         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1309                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1310                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1311                 let chan_signer = remote_chan.get_signer();
1312                 let pubkeys = chan_signer.pubkeys();
1313                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1314                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1315                  chan_signer.pubkeys().funding_pubkey)
1316         };
1317
1318         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1319         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1320                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1321
1322         // Build the remote commitment transaction so we can sign it, and then later use the
1323         // signature for the commitment_signed message.
1324         let local_chan_balance = 1313;
1325
1326         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1327                 offered: false,
1328                 amount_msat: 3460001,
1329                 cltv_expiry: htlc_cltv,
1330                 payment_hash,
1331                 transaction_output_index: Some(1),
1332         };
1333
1334         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1335
1336         let res = {
1337                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1338                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1339                 let local_chan_signer = local_chan.get_signer();
1340                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1341                         commitment_number,
1342                         95000,
1343                         local_chan_balance,
1344                         false, local_funding, remote_funding,
1345                         commit_tx_keys.clone(),
1346                         feerate_per_kw,
1347                         &mut vec![(accepted_htlc_info, ())],
1348                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1349                 );
1350                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1351         };
1352
1353         let commit_signed_msg = msgs::CommitmentSigned {
1354                 channel_id: chan.2,
1355                 signature: res.0,
1356                 htlc_signatures: res.1
1357         };
1358
1359         // Send the commitment_signed message to the nodes[1].
1360         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1361         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1362
1363         // Send the RAA to nodes[1].
1364         let raa_msg = msgs::RevokeAndACK {
1365                 channel_id: chan.2,
1366                 per_commitment_secret: local_secret,
1367                 next_per_commitment_point: next_local_point
1368         };
1369         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1370
1371         let events = nodes[1].node.get_and_clear_pending_msg_events();
1372         assert_eq!(events.len(), 1);
1373         // Make sure the HTLC failed in the way we expect.
1374         match events[0] {
1375                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1376                         assert_eq!(update_fail_htlcs.len(), 1);
1377                         update_fail_htlcs[0].clone()
1378                 },
1379                 _ => panic!("Unexpected event"),
1380         };
1381         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1382                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1383
1384         check_added_monitors!(nodes[1], 2);
1385 }
1386
1387 #[test]
1388 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1389         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1390         // Set the fee rate for the channel very high, to the point where the fundee
1391         // sending any above-dust amount would result in a channel reserve violation.
1392         // In this test we check that we would be prevented from sending an HTLC in
1393         // this situation.
1394         let feerate_per_kw = 253;
1395         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1396         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1397         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1398         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1399         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1400
1401         let mut push_amt = 100_000_000;
1402         push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT + COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
1403         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1404
1405         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1406
1407         // Sending exactly enough to hit the reserve amount should be accepted
1408         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1409
1410         // However one more HTLC should be significantly over the reserve amount and fail.
1411         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1412         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1413                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1414         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1415         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);
1416 }
1417
1418 #[test]
1419 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1420         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1421         // Set the fee rate for the channel very high, to the point where the funder
1422         // receiving 1 update_add_htlc would result in them closing the channel due
1423         // to channel reserve violation. This close could also happen if the fee went
1424         // up a more realistic amount, but many HTLCs were outstanding at the time of
1425         // the update_add_htlc.
1426         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1427         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1428         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1429         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1430         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1431         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1432
1433         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1434         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1435         let secp_ctx = Secp256k1::new();
1436         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1437         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1438         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1439         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &Some(payment_secret), cur_height, &None).unwrap();
1440         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1441         let msg = msgs::UpdateAddHTLC {
1442                 channel_id: chan.2,
1443                 htlc_id: 1,
1444                 amount_msat: htlc_msat + 1,
1445                 payment_hash: payment_hash,
1446                 cltv_expiry: htlc_cltv,
1447                 onion_routing_packet: onion_packet,
1448         };
1449
1450         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1451         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1452         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);
1453         assert_eq!(nodes[0].node.list_channels().len(), 0);
1454         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1455         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1456         check_added_monitors!(nodes[0], 1);
1457         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() });
1458 }
1459
1460 #[test]
1461 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1462         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1463         // calculating our commitment transaction fee (this was previously broken).
1464         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1465         let feerate_per_kw = 253;
1466         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1467         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1468
1469         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1470         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1471         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1472
1473         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1474         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1475         // transaction fee with 0 HTLCs (183 sats)).
1476         let mut push_amt = 100_000_000;
1477         push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT) / 1000 * 1000;
1478         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1479         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1480
1481         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1482                 + feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000 * 1000 - 1;
1483         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1484         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1485         // commitment transaction fee.
1486         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1487
1488         // One more than the dust amt should fail, however.
1489         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1490         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1491                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1492 }
1493
1494 #[test]
1495 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1496         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1497         // calculating our counterparty's commitment transaction fee (this was previously broken).
1498         let chanmon_cfgs = create_chanmon_cfgs(2);
1499         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1500         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1501         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1502         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1503
1504         let payment_amt = 46000; // Dust amount
1505         // In the previous code, these first four payments would succeed.
1506         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1507         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1508         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1509         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1510
1511         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1512         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1513         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1514         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1515         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1516         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1517
1518         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1519         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1520         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1521         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1522 }
1523
1524 #[test]
1525 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1526         let chanmon_cfgs = create_chanmon_cfgs(3);
1527         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1528         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1529         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1530         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1531         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1532
1533         let feemsat = 239;
1534         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1535         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1536         let feerate = get_feerate!(nodes[0], chan.2);
1537
1538         // Add a 2* and +1 for the fee spike reserve.
1539         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1540         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;
1541         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1542
1543         // Add a pending HTLC.
1544         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1545         let payment_event_1 = {
1546                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1547                 check_added_monitors!(nodes[0], 1);
1548
1549                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1550                 assert_eq!(events.len(), 1);
1551                 SendEvent::from_event(events.remove(0))
1552         };
1553         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1554
1555         // Attempt to trigger a channel reserve violation --> payment failure.
1556         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1557         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;
1558         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1559         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1560
1561         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1562         let secp_ctx = Secp256k1::new();
1563         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1564         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1565         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1566         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1567         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1568         let msg = msgs::UpdateAddHTLC {
1569                 channel_id: chan.2,
1570                 htlc_id: 1,
1571                 amount_msat: htlc_msat + 1,
1572                 payment_hash: our_payment_hash_1,
1573                 cltv_expiry: htlc_cltv,
1574                 onion_routing_packet: onion_packet,
1575         };
1576
1577         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1578         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1579         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1580         assert_eq!(nodes[1].node.list_channels().len(), 1);
1581         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1582         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1583         check_added_monitors!(nodes[1], 1);
1584         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1585 }
1586
1587 #[test]
1588 fn test_inbound_outbound_capacity_is_not_zero() {
1589         let chanmon_cfgs = create_chanmon_cfgs(2);
1590         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1591         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1592         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1593         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1594         let channels0 = node_chanmgrs[0].list_channels();
1595         let channels1 = node_chanmgrs[1].list_channels();
1596         assert_eq!(channels0.len(), 1);
1597         assert_eq!(channels1.len(), 1);
1598
1599         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1600         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1601         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1602
1603         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1604         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1605 }
1606
1607 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1608         (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1609 }
1610
1611 #[test]
1612 fn test_channel_reserve_holding_cell_htlcs() {
1613         let chanmon_cfgs = create_chanmon_cfgs(3);
1614         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1615         // When this test was written, the default base fee floated based on the HTLC count.
1616         // It is now fixed, so we simply set the fee to the expected value here.
1617         let mut config = test_default_channel_config();
1618         config.channel_options.forwarding_fee_base_msat = 239;
1619         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1620         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1621         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1622         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1623
1624         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1625         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1626
1627         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1628         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1629
1630         macro_rules! expect_forward {
1631                 ($node: expr) => {{
1632                         let mut events = $node.node.get_and_clear_pending_msg_events();
1633                         assert_eq!(events.len(), 1);
1634                         check_added_monitors!($node, 1);
1635                         let payment_event = SendEvent::from_event(events.remove(0));
1636                         payment_event
1637                 }}
1638         }
1639
1640         let feemsat = 239; // set above
1641         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1642         let feerate = get_feerate!(nodes[0], chan_1.2);
1643
1644         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1645
1646         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1647         {
1648                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1649                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1650                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1651                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1652                         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)));
1653                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1654                 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);
1655         }
1656
1657         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1658         // nodes[0]'s wealth
1659         loop {
1660                 let amt_msat = recv_value_0 + total_fee_msat;
1661                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1662                 // Also, ensure that each payment has enough to be over the dust limit to
1663                 // ensure it'll be included in each commit tx fee calculation.
1664                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1665                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1666                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1667                         break;
1668                 }
1669                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1670
1671                 let (stat01_, stat11_, stat12_, stat22_) = (
1672                         get_channel_value_stat!(nodes[0], chan_1.2),
1673                         get_channel_value_stat!(nodes[1], chan_1.2),
1674                         get_channel_value_stat!(nodes[1], chan_2.2),
1675                         get_channel_value_stat!(nodes[2], chan_2.2),
1676                 );
1677
1678                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1679                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1680                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1681                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1682                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1683         }
1684
1685         // adding pending output.
1686         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1687         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1688         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1689         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1690         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1691         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1692         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1693         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1694         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1695         // policy.
1696         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
1697         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1698         let amt_msat_1 = recv_value_1 + total_fee_msat;
1699
1700         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);
1701         let payment_event_1 = {
1702                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1703                 check_added_monitors!(nodes[0], 1);
1704
1705                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1706                 assert_eq!(events.len(), 1);
1707                 SendEvent::from_event(events.remove(0))
1708         };
1709         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1710
1711         // channel reserve test with htlc pending output > 0
1712         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1713         {
1714                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1715                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1716                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1717                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1718         }
1719
1720         // split the rest to test holding cell
1721         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1722         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1723         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1724         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1725         {
1726                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1727                 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);
1728         }
1729
1730         // now see if they go through on both sides
1731         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);
1732         // but this will stuck in the holding cell
1733         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1734         check_added_monitors!(nodes[0], 0);
1735         let events = nodes[0].node.get_and_clear_pending_events();
1736         assert_eq!(events.len(), 0);
1737
1738         // test with outbound holding cell amount > 0
1739         {
1740                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1741                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1742                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1743                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1744                 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);
1745         }
1746
1747         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);
1748         // this will also stuck in the holding cell
1749         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1750         check_added_monitors!(nodes[0], 0);
1751         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1752         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1753
1754         // flush the pending htlc
1755         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1756         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1757         check_added_monitors!(nodes[1], 1);
1758
1759         // the pending htlc should be promoted to committed
1760         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1761         check_added_monitors!(nodes[0], 1);
1762         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1763
1764         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1765         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1766         // No commitment_signed so get_event_msg's assert(len == 1) passes
1767         check_added_monitors!(nodes[0], 1);
1768
1769         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1770         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1771         check_added_monitors!(nodes[1], 1);
1772
1773         expect_pending_htlcs_forwardable!(nodes[1]);
1774
1775         let ref payment_event_11 = expect_forward!(nodes[1]);
1776         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1777         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1778
1779         expect_pending_htlcs_forwardable!(nodes[2]);
1780         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1781
1782         // flush the htlcs in the holding cell
1783         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1784         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1785         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1786         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1787         expect_pending_htlcs_forwardable!(nodes[1]);
1788
1789         let ref payment_event_3 = expect_forward!(nodes[1]);
1790         assert_eq!(payment_event_3.msgs.len(), 2);
1791         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1792         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1793
1794         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1795         expect_pending_htlcs_forwardable!(nodes[2]);
1796
1797         let events = nodes[2].node.get_and_clear_pending_events();
1798         assert_eq!(events.len(), 2);
1799         match events[0] {
1800                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1801                         assert_eq!(our_payment_hash_21, *payment_hash);
1802                         assert_eq!(recv_value_21, amt);
1803                         match &purpose {
1804                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1805                                         assert!(payment_preimage.is_none());
1806                                         assert_eq!(our_payment_secret_21, *payment_secret);
1807                                 },
1808                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1809                         }
1810                 },
1811                 _ => panic!("Unexpected event"),
1812         }
1813         match events[1] {
1814                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1815                         assert_eq!(our_payment_hash_22, *payment_hash);
1816                         assert_eq!(recv_value_22, amt);
1817                         match &purpose {
1818                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1819                                         assert!(payment_preimage.is_none());
1820                                         assert_eq!(our_payment_secret_22, *payment_secret);
1821                                 },
1822                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1823                         }
1824                 },
1825                 _ => panic!("Unexpected event"),
1826         }
1827
1828         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1829         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1830         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1831
1832         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
1833         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1834         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1835
1836         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
1837         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);
1838         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1839         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1840         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1841
1842         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1843         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
1844 }
1845
1846 #[test]
1847 fn channel_reserve_in_flight_removes() {
1848         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1849         // can send to its counterparty, but due to update ordering, the other side may not yet have
1850         // considered those HTLCs fully removed.
1851         // This tests that we don't count HTLCs which will not be included in the next remote
1852         // commitment transaction towards the reserve value (as it implies no commitment transaction
1853         // will be generated which violates the remote reserve value).
1854         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1855         // To test this we:
1856         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1857         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1858         //    you only consider the value of the first HTLC, it may not),
1859         //  * start routing a third HTLC from A to B,
1860         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1861         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1862         //  * deliver the first fulfill from B
1863         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1864         //    claim,
1865         //  * deliver A's response CS and RAA.
1866         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1867         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
1868         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1869         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1870         let chanmon_cfgs = create_chanmon_cfgs(2);
1871         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1872         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1873         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1874         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1875
1876         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1877         // Route the first two HTLCs.
1878         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1879         let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1880
1881         // Start routing the third HTLC (this is just used to get everyone in the right state).
1882         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
1883         let send_1 = {
1884                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
1885                 check_added_monitors!(nodes[0], 1);
1886                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1887                 assert_eq!(events.len(), 1);
1888                 SendEvent::from_event(events.remove(0))
1889         };
1890
1891         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1892         // initial fulfill/CS.
1893         assert!(nodes[1].node.claim_funds(payment_preimage_1));
1894         check_added_monitors!(nodes[1], 1);
1895         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1896
1897         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1898         // remove the second HTLC when we send the HTLC back from B to A.
1899         assert!(nodes[1].node.claim_funds(payment_preimage_2));
1900         check_added_monitors!(nodes[1], 1);
1901         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1902
1903         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1904         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1905         check_added_monitors!(nodes[0], 1);
1906         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1907         expect_payment_sent!(nodes[0], payment_preimage_1);
1908
1909         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1910         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1911         check_added_monitors!(nodes[1], 1);
1912         // B is already AwaitingRAA, so cant generate a CS here
1913         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1914
1915         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1916         check_added_monitors!(nodes[1], 1);
1917         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1918
1919         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1920         check_added_monitors!(nodes[0], 1);
1921         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1922
1923         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1924         check_added_monitors!(nodes[1], 1);
1925         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1926
1927         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1928         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1929         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1930         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1931         // on-chain as necessary).
1932         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1933         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1934         check_added_monitors!(nodes[0], 1);
1935         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1936         expect_payment_sent!(nodes[0], payment_preimage_2);
1937
1938         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1939         check_added_monitors!(nodes[1], 1);
1940         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1941
1942         expect_pending_htlcs_forwardable!(nodes[1]);
1943         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
1944
1945         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1946         // resolve the second HTLC from A's point of view.
1947         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1948         check_added_monitors!(nodes[0], 1);
1949         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1950
1951         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1952         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1953         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
1954         let send_2 = {
1955                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
1956                 check_added_monitors!(nodes[1], 1);
1957                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1958                 assert_eq!(events.len(), 1);
1959                 SendEvent::from_event(events.remove(0))
1960         };
1961
1962         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1963         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1964         check_added_monitors!(nodes[0], 1);
1965         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1966
1967         // Now just resolve all the outstanding messages/HTLCs for completeness...
1968
1969         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1970         check_added_monitors!(nodes[1], 1);
1971         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1972
1973         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1974         check_added_monitors!(nodes[1], 1);
1975
1976         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1977         check_added_monitors!(nodes[0], 1);
1978         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1979
1980         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1981         check_added_monitors!(nodes[1], 1);
1982         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1983
1984         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1985         check_added_monitors!(nodes[0], 1);
1986
1987         expect_pending_htlcs_forwardable!(nodes[0]);
1988         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
1989
1990         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
1991         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
1992 }
1993
1994 #[test]
1995 fn channel_monitor_network_test() {
1996         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1997         // tests that ChannelMonitor is able to recover from various states.
1998         let chanmon_cfgs = create_chanmon_cfgs(5);
1999         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2000         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2001         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2002
2003         // Create some initial channels
2004         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2005         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2006         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2007         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2008
2009         // Make sure all nodes are at the same starting height
2010         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2011         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2012         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2013         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2014         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2015
2016         // Rebalance the network a bit by relaying one payment through all the channels...
2017         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2018         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2019         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2020         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2021
2022         // Simple case with no pending HTLCs:
2023         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2024         check_added_monitors!(nodes[1], 1);
2025         check_closed_broadcast!(nodes[1], false);
2026         {
2027                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2028                 assert_eq!(node_txn.len(), 1);
2029                 mine_transaction(&nodes[0], &node_txn[0]);
2030                 check_added_monitors!(nodes[0], 1);
2031                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2032         }
2033         check_closed_broadcast!(nodes[0], true);
2034         assert_eq!(nodes[0].node.list_channels().len(), 0);
2035         assert_eq!(nodes[1].node.list_channels().len(), 1);
2036         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2037         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2038
2039         // One pending HTLC is discarded by the force-close:
2040         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2041
2042         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2043         // broadcasted until we reach the timelock time).
2044         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2045         check_closed_broadcast!(nodes[1], false);
2046         check_added_monitors!(nodes[1], 1);
2047         {
2048                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2049                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2050                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2051                 mine_transaction(&nodes[2], &node_txn[0]);
2052                 check_added_monitors!(nodes[2], 1);
2053                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2054         }
2055         check_closed_broadcast!(nodes[2], true);
2056         assert_eq!(nodes[1].node.list_channels().len(), 0);
2057         assert_eq!(nodes[2].node.list_channels().len(), 1);
2058         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2059         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2060
2061         macro_rules! claim_funds {
2062                 ($node: expr, $prev_node: expr, $preimage: expr) => {
2063                         {
2064                                 assert!($node.node.claim_funds($preimage));
2065                                 check_added_monitors!($node, 1);
2066
2067                                 let events = $node.node.get_and_clear_pending_msg_events();
2068                                 assert_eq!(events.len(), 1);
2069                                 match events[0] {
2070                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2071                                                 assert!(update_add_htlcs.is_empty());
2072                                                 assert!(update_fail_htlcs.is_empty());
2073                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2074                                         },
2075                                         _ => panic!("Unexpected event"),
2076                                 };
2077                         }
2078                 }
2079         }
2080
2081         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2082         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2083         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2084         check_added_monitors!(nodes[2], 1);
2085         check_closed_broadcast!(nodes[2], false);
2086         let node2_commitment_txid;
2087         {
2088                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2089                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2090                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2091                 node2_commitment_txid = node_txn[0].txid();
2092
2093                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2094                 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2095                 mine_transaction(&nodes[3], &node_txn[0]);
2096                 check_added_monitors!(nodes[3], 1);
2097                 check_preimage_claim(&nodes[3], &node_txn);
2098         }
2099         check_closed_broadcast!(nodes[3], true);
2100         assert_eq!(nodes[2].node.list_channels().len(), 0);
2101         assert_eq!(nodes[3].node.list_channels().len(), 1);
2102         check_closed_event!(nodes[2], 1, ClosureReason::DisconnectedPeer);
2103         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2104
2105         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2106         // confusing us in the following tests.
2107         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2108
2109         // One pending HTLC to time out:
2110         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2111         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2112         // buffer space).
2113
2114         let (close_chan_update_1, close_chan_update_2) = {
2115                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2116                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2117                 assert_eq!(events.len(), 2);
2118                 let close_chan_update_1 = match events[0] {
2119                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2120                                 msg.clone()
2121                         },
2122                         _ => panic!("Unexpected event"),
2123                 };
2124                 match events[1] {
2125                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2126                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2127                         },
2128                         _ => panic!("Unexpected event"),
2129                 }
2130                 check_added_monitors!(nodes[3], 1);
2131
2132                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2133                 {
2134                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2135                         node_txn.retain(|tx| {
2136                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2137                                         false
2138                                 } else { true }
2139                         });
2140                 }
2141
2142                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2143
2144                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2145                 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2146
2147                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2148                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2149                 assert_eq!(events.len(), 2);
2150                 let close_chan_update_2 = match events[0] {
2151                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2152                                 msg.clone()
2153                         },
2154                         _ => panic!("Unexpected event"),
2155                 };
2156                 match events[1] {
2157                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2158                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2159                         },
2160                         _ => panic!("Unexpected event"),
2161                 }
2162                 check_added_monitors!(nodes[4], 1);
2163                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2164
2165                 mine_transaction(&nodes[4], &node_txn[0]);
2166                 check_preimage_claim(&nodes[4], &node_txn);
2167                 (close_chan_update_1, close_chan_update_2)
2168         };
2169         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2170         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2171         assert_eq!(nodes[3].node.list_channels().len(), 0);
2172         assert_eq!(nodes[4].node.list_channels().len(), 0);
2173
2174         nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2175         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2176         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2177 }
2178
2179 #[test]
2180 fn test_justice_tx() {
2181         // Test justice txn built on revoked HTLC-Success tx, against both sides
2182         let mut alice_config = UserConfig::default();
2183         alice_config.channel_options.announced_channel = true;
2184         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2185         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2186         let mut bob_config = UserConfig::default();
2187         bob_config.channel_options.announced_channel = true;
2188         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2189         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2190         let user_cfgs = [Some(alice_config), Some(bob_config)];
2191         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2192         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2193         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2194         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2195         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2196         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2197         // Create some new channels:
2198         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2199
2200         // A pending HTLC which will be revoked:
2201         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2202         // Get the will-be-revoked local txn from nodes[0]
2203         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2204         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2205         assert_eq!(revoked_local_txn[0].input.len(), 1);
2206         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2207         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2208         assert_eq!(revoked_local_txn[1].input.len(), 1);
2209         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2210         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2211         // Revoke the old state
2212         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2213
2214         {
2215                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2216                 {
2217                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2218                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2219                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2220
2221                         check_spends!(node_txn[0], revoked_local_txn[0]);
2222                         node_txn.swap_remove(0);
2223                         node_txn.truncate(1);
2224                 }
2225                 check_added_monitors!(nodes[1], 1);
2226                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2227                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2228
2229                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2230                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2231                 // Verify broadcast of revoked HTLC-timeout
2232                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2233                 check_added_monitors!(nodes[0], 1);
2234                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2235                 // Broadcast revoked HTLC-timeout on node 1
2236                 mine_transaction(&nodes[1], &node_txn[1]);
2237                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2238         }
2239         get_announce_close_broadcast_events(&nodes, 0, 1);
2240
2241         assert_eq!(nodes[0].node.list_channels().len(), 0);
2242         assert_eq!(nodes[1].node.list_channels().len(), 0);
2243
2244         // We test justice_tx build by A on B's revoked HTLC-Success tx
2245         // Create some new channels:
2246         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2247         {
2248                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2249                 node_txn.clear();
2250         }
2251
2252         // A pending HTLC which will be revoked:
2253         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2254         // Get the will-be-revoked local txn from B
2255         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2256         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2257         assert_eq!(revoked_local_txn[0].input.len(), 1);
2258         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2259         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2260         // Revoke the old state
2261         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2262         {
2263                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2264                 {
2265                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2266                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2267                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2268
2269                         check_spends!(node_txn[0], revoked_local_txn[0]);
2270                         node_txn.swap_remove(0);
2271                 }
2272                 check_added_monitors!(nodes[0], 1);
2273                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2274
2275                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2276                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2277                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2278                 check_added_monitors!(nodes[1], 1);
2279                 mine_transaction(&nodes[0], &node_txn[1]);
2280                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2281                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2282         }
2283         get_announce_close_broadcast_events(&nodes, 0, 1);
2284         assert_eq!(nodes[0].node.list_channels().len(), 0);
2285         assert_eq!(nodes[1].node.list_channels().len(), 0);
2286 }
2287
2288 #[test]
2289 fn revoked_output_claim() {
2290         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2291         // transaction is broadcast by its counterparty
2292         let chanmon_cfgs = create_chanmon_cfgs(2);
2293         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2294         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2295         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2296         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2297         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2298         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2299         assert_eq!(revoked_local_txn.len(), 1);
2300         // Only output is the full channel value back to nodes[0]:
2301         assert_eq!(revoked_local_txn[0].output.len(), 1);
2302         // Send a payment through, updating everyone's latest commitment txn
2303         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2304
2305         // Inform nodes[1] that nodes[0] broadcast a stale tx
2306         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2307         check_added_monitors!(nodes[1], 1);
2308         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2309         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2310         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2311
2312         check_spends!(node_txn[0], revoked_local_txn[0]);
2313         check_spends!(node_txn[1], chan_1.3);
2314
2315         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2316         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2317         get_announce_close_broadcast_events(&nodes, 0, 1);
2318         check_added_monitors!(nodes[0], 1);
2319         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2320 }
2321
2322 #[test]
2323 fn claim_htlc_outputs_shared_tx() {
2324         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2325         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2326         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2327         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2328         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2329         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2330
2331         // Create some new channel:
2332         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2333
2334         // Rebalance the network to generate htlc in the two directions
2335         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2336         // 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
2337         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2338         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2339
2340         // Get the will-be-revoked local txn from node[0]
2341         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2342         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2343         assert_eq!(revoked_local_txn[0].input.len(), 1);
2344         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2345         assert_eq!(revoked_local_txn[1].input.len(), 1);
2346         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2347         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2348         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2349
2350         //Revoke the old state
2351         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2352
2353         {
2354                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2355                 check_added_monitors!(nodes[0], 1);
2356                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2357                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2358                 check_added_monitors!(nodes[1], 1);
2359                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2360                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2361                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2362
2363                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2364                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2365
2366                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2367                 check_spends!(node_txn[0], revoked_local_txn[0]);
2368
2369                 let mut witness_lens = BTreeSet::new();
2370                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2371                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2372                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2373                 assert_eq!(witness_lens.len(), 3);
2374                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2375                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2376                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2377
2378                 // Next nodes[1] broadcasts its current local tx state:
2379                 assert_eq!(node_txn[1].input.len(), 1);
2380                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2381         }
2382         get_announce_close_broadcast_events(&nodes, 0, 1);
2383         assert_eq!(nodes[0].node.list_channels().len(), 0);
2384         assert_eq!(nodes[1].node.list_channels().len(), 0);
2385 }
2386
2387 #[test]
2388 fn claim_htlc_outputs_single_tx() {
2389         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2390         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2391         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2392         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2393         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2394         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2395
2396         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2397
2398         // Rebalance the network to generate htlc in the two directions
2399         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2400         // 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
2401         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2402         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2403         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2404
2405         // Get the will-be-revoked local txn from node[0]
2406         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2407
2408         //Revoke the old state
2409         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2410
2411         {
2412                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2413                 check_added_monitors!(nodes[0], 1);
2414                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2415                 check_added_monitors!(nodes[1], 1);
2416                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2417                 let mut events = nodes[0].node.get_and_clear_pending_events();
2418                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2419                 match events[1] {
2420                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2421                         _ => panic!("Unexpected event"),
2422                 }
2423
2424                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2425                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2426
2427                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2428                 assert_eq!(node_txn.len(), 9);
2429                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2430                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2431                 // 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)
2432                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2433
2434                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2435                 assert_eq!(node_txn[0].input.len(), 1);
2436                 check_spends!(node_txn[0], chan_1.3);
2437                 assert_eq!(node_txn[1].input.len(), 1);
2438                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2439                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2440                 check_spends!(node_txn[1], node_txn[0]);
2441
2442                 // Justice transactions are indices 1-2-4
2443                 assert_eq!(node_txn[2].input.len(), 1);
2444                 assert_eq!(node_txn[3].input.len(), 1);
2445                 assert_eq!(node_txn[4].input.len(), 1);
2446
2447                 check_spends!(node_txn[2], revoked_local_txn[0]);
2448                 check_spends!(node_txn[3], revoked_local_txn[0]);
2449                 check_spends!(node_txn[4], revoked_local_txn[0]);
2450
2451                 let mut witness_lens = BTreeSet::new();
2452                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2453                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2454                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2455                 assert_eq!(witness_lens.len(), 3);
2456                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2457                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2458                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2459         }
2460         get_announce_close_broadcast_events(&nodes, 0, 1);
2461         assert_eq!(nodes[0].node.list_channels().len(), 0);
2462         assert_eq!(nodes[1].node.list_channels().len(), 0);
2463 }
2464
2465 #[test]
2466 fn test_htlc_on_chain_success() {
2467         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2468         // the preimage backward accordingly. So here we test that ChannelManager is
2469         // broadcasting the right event to other nodes in payment path.
2470         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2471         // A --------------------> B ----------------------> C (preimage)
2472         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2473         // commitment transaction was broadcast.
2474         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2475         // towards B.
2476         // B should be able to claim via preimage if A then broadcasts its local tx.
2477         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2478         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2479         // PaymentSent event).
2480
2481         let chanmon_cfgs = create_chanmon_cfgs(3);
2482         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2483         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2484         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2485
2486         // Create some initial channels
2487         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2488         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2489
2490         // Ensure all nodes are at the same height
2491         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2492         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2493         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2494         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2495
2496         // Rebalance the network a bit by relaying one payment through all the channels...
2497         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2498         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2499
2500         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2501         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2502
2503         // Broadcast legit commitment tx from C on B's chain
2504         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2505         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2506         assert_eq!(commitment_tx.len(), 1);
2507         check_spends!(commitment_tx[0], chan_2.3);
2508         nodes[2].node.claim_funds(our_payment_preimage);
2509         nodes[2].node.claim_funds(our_payment_preimage_2);
2510         check_added_monitors!(nodes[2], 2);
2511         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2512         assert!(updates.update_add_htlcs.is_empty());
2513         assert!(updates.update_fail_htlcs.is_empty());
2514         assert!(updates.update_fail_malformed_htlcs.is_empty());
2515         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2516
2517         mine_transaction(&nodes[2], &commitment_tx[0]);
2518         check_closed_broadcast!(nodes[2], true);
2519         check_added_monitors!(nodes[2], 1);
2520         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2521         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)
2522         assert_eq!(node_txn.len(), 5);
2523         assert_eq!(node_txn[0], node_txn[3]);
2524         assert_eq!(node_txn[1], node_txn[4]);
2525         assert_eq!(node_txn[2], commitment_tx[0]);
2526         check_spends!(node_txn[0], commitment_tx[0]);
2527         check_spends!(node_txn[1], commitment_tx[0]);
2528         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2529         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2530         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2531         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2532         assert_eq!(node_txn[0].lock_time, 0);
2533         assert_eq!(node_txn[1].lock_time, 0);
2534
2535         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2536         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2537         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2538         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2539         {
2540                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2541                 assert_eq!(added_monitors.len(), 1);
2542                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2543                 added_monitors.clear();
2544         }
2545         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2546         assert_eq!(forwarded_events.len(), 3);
2547         match forwarded_events[0] {
2548                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2549                 _ => panic!("Unexpected event"),
2550         }
2551         if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[1] {
2552                 } else { panic!(); }
2553         if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[2] {
2554                 } else { panic!(); }
2555         let events = nodes[1].node.get_and_clear_pending_msg_events();
2556         {
2557                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2558                 assert_eq!(added_monitors.len(), 2);
2559                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2560                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2561                 added_monitors.clear();
2562         }
2563         assert_eq!(events.len(), 3);
2564         match events[0] {
2565                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2566                 _ => panic!("Unexpected event"),
2567         }
2568         match events[1] {
2569                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2570                 _ => panic!("Unexpected event"),
2571         }
2572
2573         match events[2] {
2574                 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, .. } } => {
2575                         assert!(update_add_htlcs.is_empty());
2576                         assert!(update_fail_htlcs.is_empty());
2577                         assert_eq!(update_fulfill_htlcs.len(), 1);
2578                         assert!(update_fail_malformed_htlcs.is_empty());
2579                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2580                 },
2581                 _ => panic!("Unexpected event"),
2582         };
2583         macro_rules! check_tx_local_broadcast {
2584                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2585                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2586                         assert_eq!(node_txn.len(), 3);
2587                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2588                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2589                         check_spends!(node_txn[1], $commitment_tx);
2590                         check_spends!(node_txn[2], $commitment_tx);
2591                         assert_ne!(node_txn[1].lock_time, 0);
2592                         assert_ne!(node_txn[2].lock_time, 0);
2593                         if $htlc_offered {
2594                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2595                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2596                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2597                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2598                         } else {
2599                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2600                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2601                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2602                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2603                         }
2604                         check_spends!(node_txn[0], $chan_tx);
2605                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2606                         node_txn.clear();
2607                 } }
2608         }
2609         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2610         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2611         // timeout-claim of the output that nodes[2] just claimed via success.
2612         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2613
2614         // Broadcast legit commitment tx from A on B's chain
2615         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2616         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2617         check_spends!(node_a_commitment_tx[0], chan_1.3);
2618         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2619         check_closed_broadcast!(nodes[1], true);
2620         check_added_monitors!(nodes[1], 1);
2621         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2622         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2623         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2624         let commitment_spend =
2625                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2626                         check_spends!(node_txn[1], commitment_tx[0]);
2627                         check_spends!(node_txn[2], commitment_tx[0]);
2628                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2629                         &node_txn[0]
2630                 } else {
2631                         check_spends!(node_txn[0], commitment_tx[0]);
2632                         check_spends!(node_txn[1], commitment_tx[0]);
2633                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2634                         &node_txn[2]
2635                 };
2636
2637         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2638         assert_eq!(commitment_spend.input.len(), 2);
2639         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2640         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2641         assert_eq!(commitment_spend.lock_time, 0);
2642         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2643         check_spends!(node_txn[3], chan_1.3);
2644         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2645         check_spends!(node_txn[4], node_txn[3]);
2646         check_spends!(node_txn[5], node_txn[3]);
2647         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2648         // we already checked the same situation with A.
2649
2650         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2651         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2652         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2653         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2654         check_closed_broadcast!(nodes[0], true);
2655         check_added_monitors!(nodes[0], 1);
2656         let events = nodes[0].node.get_and_clear_pending_events();
2657         assert_eq!(events.len(), 3);
2658         let mut first_claimed = false;
2659         for event in events {
2660                 match event {
2661                         Event::PaymentSent { payment_preimage, payment_hash } => {
2662                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2663                                         assert!(!first_claimed);
2664                                         first_claimed = true;
2665                                 } else {
2666                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2667                                         assert_eq!(payment_hash, payment_hash_2);
2668                                 }
2669                         },
2670                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2671                         _ => panic!("Unexpected event"),
2672                 }
2673         }
2674         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2675 }
2676
2677 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2678         // Test that in case of a unilateral close onchain, we detect the state of output and
2679         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2680         // broadcasting the right event to other nodes in payment path.
2681         // A ------------------> B ----------------------> C (timeout)
2682         //    B's commitment tx                 C's commitment tx
2683         //            \                                  \
2684         //         B's HTLC timeout tx               B's timeout tx
2685
2686         let chanmon_cfgs = create_chanmon_cfgs(3);
2687         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2688         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2689         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2690         *nodes[0].connect_style.borrow_mut() = connect_style;
2691         *nodes[1].connect_style.borrow_mut() = connect_style;
2692         *nodes[2].connect_style.borrow_mut() = connect_style;
2693
2694         // Create some intial channels
2695         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2696         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2697
2698         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2699         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2700         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2701
2702         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2703
2704         // Broadcast legit commitment tx from C on B's chain
2705         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2706         check_spends!(commitment_tx[0], chan_2.3);
2707         nodes[2].node.fail_htlc_backwards(&payment_hash);
2708         check_added_monitors!(nodes[2], 0);
2709         expect_pending_htlcs_forwardable!(nodes[2]);
2710         check_added_monitors!(nodes[2], 1);
2711
2712         let events = nodes[2].node.get_and_clear_pending_msg_events();
2713         assert_eq!(events.len(), 1);
2714         match events[0] {
2715                 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, .. } } => {
2716                         assert!(update_add_htlcs.is_empty());
2717                         assert!(!update_fail_htlcs.is_empty());
2718                         assert!(update_fulfill_htlcs.is_empty());
2719                         assert!(update_fail_malformed_htlcs.is_empty());
2720                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2721                 },
2722                 _ => panic!("Unexpected event"),
2723         };
2724         mine_transaction(&nodes[2], &commitment_tx[0]);
2725         check_closed_broadcast!(nodes[2], true);
2726         check_added_monitors!(nodes[2], 1);
2727         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2728         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2729         assert_eq!(node_txn.len(), 1);
2730         check_spends!(node_txn[0], chan_2.3);
2731         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2732
2733         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2734         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2735         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2736         mine_transaction(&nodes[1], &commitment_tx[0]);
2737         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2738         let timeout_tx;
2739         {
2740                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2741                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2742                 assert_eq!(node_txn[0], node_txn[3]);
2743                 assert_eq!(node_txn[1], node_txn[4]);
2744
2745                 check_spends!(node_txn[2], commitment_tx[0]);
2746                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2747
2748                 check_spends!(node_txn[0], chan_2.3);
2749                 check_spends!(node_txn[1], node_txn[0]);
2750                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2751                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2752
2753                 timeout_tx = node_txn[2].clone();
2754                 node_txn.clear();
2755         }
2756
2757         mine_transaction(&nodes[1], &timeout_tx);
2758         check_added_monitors!(nodes[1], 1);
2759         check_closed_broadcast!(nodes[1], true);
2760         {
2761                 // B will rebroadcast a fee-bumped timeout transaction here.
2762                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2763                 assert_eq!(node_txn.len(), 1);
2764                 check_spends!(node_txn[0], commitment_tx[0]);
2765         }
2766
2767         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2768         {
2769                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2770                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2771                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2772                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2773                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2774                 if node_txn.len() == 1 {
2775                         check_spends!(node_txn[0], chan_2.3);
2776                 } else {
2777                         assert_eq!(node_txn.len(), 0);
2778                 }
2779         }
2780
2781         expect_pending_htlcs_forwardable!(nodes[1]);
2782         check_added_monitors!(nodes[1], 1);
2783         let events = nodes[1].node.get_and_clear_pending_msg_events();
2784         assert_eq!(events.len(), 1);
2785         match events[0] {
2786                 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, .. } } => {
2787                         assert!(update_add_htlcs.is_empty());
2788                         assert!(!update_fail_htlcs.is_empty());
2789                         assert!(update_fulfill_htlcs.is_empty());
2790                         assert!(update_fail_malformed_htlcs.is_empty());
2791                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2792                 },
2793                 _ => panic!("Unexpected event"),
2794         };
2795
2796         // Broadcast legit commitment tx from B on A's chain
2797         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2798         check_spends!(commitment_tx[0], chan_1.3);
2799
2800         mine_transaction(&nodes[0], &commitment_tx[0]);
2801         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2802
2803         check_closed_broadcast!(nodes[0], true);
2804         check_added_monitors!(nodes[0], 1);
2805         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2806         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2807         assert_eq!(node_txn.len(), 2);
2808         check_spends!(node_txn[0], chan_1.3);
2809         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2810         check_spends!(node_txn[1], commitment_tx[0]);
2811         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2812 }
2813
2814 #[test]
2815 fn test_htlc_on_chain_timeout() {
2816         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2817         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2818         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2819 }
2820
2821 #[test]
2822 fn test_simple_commitment_revoked_fail_backward() {
2823         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2824         // and fail backward accordingly.
2825
2826         let chanmon_cfgs = create_chanmon_cfgs(3);
2827         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2828         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2829         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2830
2831         // Create some initial channels
2832         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2833         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2834
2835         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2836         // Get the will-be-revoked local txn from nodes[2]
2837         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2838         // Revoke the old state
2839         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2840
2841         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2842
2843         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2844         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2845         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2846         check_added_monitors!(nodes[1], 1);
2847         check_closed_broadcast!(nodes[1], true);
2848
2849         expect_pending_htlcs_forwardable!(nodes[1]);
2850         check_added_monitors!(nodes[1], 1);
2851         let events = nodes[1].node.get_and_clear_pending_msg_events();
2852         assert_eq!(events.len(), 1);
2853         match events[0] {
2854                 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, .. } } => {
2855                         assert!(update_add_htlcs.is_empty());
2856                         assert_eq!(update_fail_htlcs.len(), 1);
2857                         assert!(update_fulfill_htlcs.is_empty());
2858                         assert!(update_fail_malformed_htlcs.is_empty());
2859                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2860
2861                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2862                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2863                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
2864                 },
2865                 _ => panic!("Unexpected event"),
2866         }
2867 }
2868
2869 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2870         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2871         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2872         // commitment transaction anymore.
2873         // To do this, we have the peer which will broadcast a revoked commitment transaction send
2874         // a number of update_fail/commitment_signed updates without ever sending the RAA in
2875         // response to our commitment_signed. This is somewhat misbehavior-y, though not
2876         // technically disallowed and we should probably handle it reasonably.
2877         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2878         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2879         // transactions:
2880         // * Once we move it out of our holding cell/add it, we will immediately include it in a
2881         //   commitment_signed (implying it will be in the latest remote commitment transaction).
2882         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2883         //   and once they revoke the previous commitment transaction (allowing us to send a new
2884         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2885         let chanmon_cfgs = create_chanmon_cfgs(3);
2886         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2887         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2888         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2889
2890         // Create some initial channels
2891         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2892         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2893
2894         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 });
2895         // Get the will-be-revoked local txn from nodes[2]
2896         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2897         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2898         // Revoke the old state
2899         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2900
2901         let value = if use_dust {
2902                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2903                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2904                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
2905         } else { 3000000 };
2906
2907         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2908         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2909         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2910
2911         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2912         expect_pending_htlcs_forwardable!(nodes[2]);
2913         check_added_monitors!(nodes[2], 1);
2914         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2915         assert!(updates.update_add_htlcs.is_empty());
2916         assert!(updates.update_fulfill_htlcs.is_empty());
2917         assert!(updates.update_fail_malformed_htlcs.is_empty());
2918         assert_eq!(updates.update_fail_htlcs.len(), 1);
2919         assert!(updates.update_fee.is_none());
2920         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2921         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2922         // Drop the last RAA from 3 -> 2
2923
2924         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2925         expect_pending_htlcs_forwardable!(nodes[2]);
2926         check_added_monitors!(nodes[2], 1);
2927         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2928         assert!(updates.update_add_htlcs.is_empty());
2929         assert!(updates.update_fulfill_htlcs.is_empty());
2930         assert!(updates.update_fail_malformed_htlcs.is_empty());
2931         assert_eq!(updates.update_fail_htlcs.len(), 1);
2932         assert!(updates.update_fee.is_none());
2933         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2934         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2935         check_added_monitors!(nodes[1], 1);
2936         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2937         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2938         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2939         check_added_monitors!(nodes[2], 1);
2940
2941         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
2942         expect_pending_htlcs_forwardable!(nodes[2]);
2943         check_added_monitors!(nodes[2], 1);
2944         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2945         assert!(updates.update_add_htlcs.is_empty());
2946         assert!(updates.update_fulfill_htlcs.is_empty());
2947         assert!(updates.update_fail_malformed_htlcs.is_empty());
2948         assert_eq!(updates.update_fail_htlcs.len(), 1);
2949         assert!(updates.update_fee.is_none());
2950         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2951         // At this point first_payment_hash has dropped out of the latest two commitment
2952         // transactions that nodes[1] is tracking...
2953         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2954         check_added_monitors!(nodes[1], 1);
2955         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2956         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2957         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2958         check_added_monitors!(nodes[2], 1);
2959
2960         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2961         // on nodes[2]'s RAA.
2962         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
2963         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
2964         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2965         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2966         check_added_monitors!(nodes[1], 0);
2967
2968         if deliver_bs_raa {
2969                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
2970                 // One monitor for the new revocation preimage, no second on as we won't generate a new
2971                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2972                 check_added_monitors!(nodes[1], 1);
2973                 let events = nodes[1].node.get_and_clear_pending_events();
2974                 assert_eq!(events.len(), 1);
2975                 match events[0] {
2976                         Event::PendingHTLCsForwardable { .. } => { },
2977                         _ => panic!("Unexpected event"),
2978                 };
2979                 // Deliberately don't process the pending fail-back so they all fail back at once after
2980                 // block connection just like the !deliver_bs_raa case
2981         }
2982
2983         let mut failed_htlcs = HashSet::new();
2984         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2985
2986         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2987         check_added_monitors!(nodes[1], 1);
2988         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2989
2990         let events = nodes[1].node.get_and_clear_pending_events();
2991         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
2992         match events[0] {
2993                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
2994                 _ => panic!("Unexepected event"),
2995         }
2996         match events[1] {
2997                 Event::PaymentPathFailed { ref payment_hash, .. } => {
2998                         assert_eq!(*payment_hash, fourth_payment_hash);
2999                 },
3000                 _ => panic!("Unexpected event"),
3001         }
3002         if !deliver_bs_raa {
3003                 match events[2] {
3004                         Event::PendingHTLCsForwardable { .. } => { },
3005                         _ => panic!("Unexpected event"),
3006                 };
3007         }
3008         nodes[1].node.process_pending_htlc_forwards();
3009         check_added_monitors!(nodes[1], 1);
3010
3011         let events = nodes[1].node.get_and_clear_pending_msg_events();
3012         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3013         match events[if deliver_bs_raa { 1 } else { 0 }] {
3014                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3015                 _ => panic!("Unexpected event"),
3016         }
3017         match events[if deliver_bs_raa { 2 } else { 1 }] {
3018                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3019                         assert_eq!(channel_id, chan_2.2);
3020                         assert_eq!(data.as_str(), "Commitment or closing transaction was confirmed on chain.");
3021                 },
3022                 _ => panic!("Unexpected event"),
3023         }
3024         if deliver_bs_raa {
3025                 match events[0] {
3026                         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, .. } } => {
3027                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3028                                 assert_eq!(update_add_htlcs.len(), 1);
3029                                 assert!(update_fulfill_htlcs.is_empty());
3030                                 assert!(update_fail_htlcs.is_empty());
3031                                 assert!(update_fail_malformed_htlcs.is_empty());
3032                         },
3033                         _ => panic!("Unexpected event"),
3034                 }
3035         }
3036         match events[if deliver_bs_raa { 3 } else { 2 }] {
3037                 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, .. } } => {
3038                         assert!(update_add_htlcs.is_empty());
3039                         assert_eq!(update_fail_htlcs.len(), 3);
3040                         assert!(update_fulfill_htlcs.is_empty());
3041                         assert!(update_fail_malformed_htlcs.is_empty());
3042                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3043
3044                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3045                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3046                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3047
3048                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3049
3050                         let events = nodes[0].node.get_and_clear_pending_events();
3051                         assert_eq!(events.len(), 3);
3052                         match events[0] {
3053                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3054                                         assert!(failed_htlcs.insert(payment_hash.0));
3055                                         // If we delivered B's RAA we got an unknown preimage error, not something
3056                                         // that we should update our routing table for.
3057                                         if !deliver_bs_raa {
3058                                                 assert!(network_update.is_some());
3059                                         }
3060                                 },
3061                                 _ => panic!("Unexpected event"),
3062                         }
3063                         match events[1] {
3064                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3065                                         assert!(failed_htlcs.insert(payment_hash.0));
3066                                         assert!(network_update.is_some());
3067                                 },
3068                                 _ => panic!("Unexpected event"),
3069                         }
3070                         match events[2] {
3071                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3072                                         assert!(failed_htlcs.insert(payment_hash.0));
3073                                         assert!(network_update.is_some());
3074                                 },
3075                                 _ => panic!("Unexpected event"),
3076                         }
3077                 },
3078                 _ => panic!("Unexpected event"),
3079         }
3080
3081         assert!(failed_htlcs.contains(&first_payment_hash.0));
3082         assert!(failed_htlcs.contains(&second_payment_hash.0));
3083         assert!(failed_htlcs.contains(&third_payment_hash.0));
3084 }
3085
3086 #[test]
3087 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3088         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3089         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3090         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3091         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3092 }
3093
3094 #[test]
3095 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3096         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3097         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3098         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3099         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3100 }
3101
3102 #[test]
3103 fn fail_backward_pending_htlc_upon_channel_failure() {
3104         let chanmon_cfgs = create_chanmon_cfgs(2);
3105         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3106         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3107         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3108         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3109
3110         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3111         {
3112                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3113                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3114                 check_added_monitors!(nodes[0], 1);
3115
3116                 let payment_event = {
3117                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3118                         assert_eq!(events.len(), 1);
3119                         SendEvent::from_event(events.remove(0))
3120                 };
3121                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3122                 assert_eq!(payment_event.msgs.len(), 1);
3123         }
3124
3125         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3126         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3127         {
3128                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3129                 check_added_monitors!(nodes[0], 0);
3130
3131                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3132         }
3133
3134         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3135         {
3136                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3137
3138                 let secp_ctx = Secp256k1::new();
3139                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3140                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3141                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3142                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3143                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3144
3145                 // Send a 0-msat update_add_htlc to fail the channel.
3146                 let update_add_htlc = msgs::UpdateAddHTLC {
3147                         channel_id: chan.2,
3148                         htlc_id: 0,
3149                         amount_msat: 0,
3150                         payment_hash,
3151                         cltv_expiry,
3152                         onion_routing_packet,
3153                 };
3154                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3155         }
3156         let events = nodes[0].node.get_and_clear_pending_events();
3157         assert_eq!(events.len(), 2);
3158         // Check that Alice fails backward the pending HTLC from the second payment.
3159         match events[0] {
3160                 Event::PaymentPathFailed { payment_hash, .. } => {
3161                         assert_eq!(payment_hash, failed_payment_hash);
3162                 },
3163                 _ => panic!("Unexpected event"),
3164         }
3165         match events[1] {
3166                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3167                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3168                 },
3169                 _ => panic!("Unexpected event {:?}", events[1]),
3170         }
3171         check_closed_broadcast!(nodes[0], true);
3172         check_added_monitors!(nodes[0], 1);
3173 }
3174
3175 #[test]
3176 fn test_htlc_ignore_latest_remote_commitment() {
3177         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3178         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3179         let chanmon_cfgs = create_chanmon_cfgs(2);
3180         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3181         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3182         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3183         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3184
3185         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3186         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3187         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3188         check_closed_broadcast!(nodes[0], true);
3189         check_added_monitors!(nodes[0], 1);
3190         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3191
3192         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3193         assert_eq!(node_txn.len(), 3);
3194         assert_eq!(node_txn[0], node_txn[1]);
3195
3196         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3197         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3198         check_closed_broadcast!(nodes[1], true);
3199         check_added_monitors!(nodes[1], 1);
3200         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3201
3202         // Duplicate the connect_block call since this may happen due to other listeners
3203         // registering new transactions
3204         header.prev_blockhash = header.block_hash();
3205         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3206 }
3207
3208 #[test]
3209 fn test_force_close_fail_back() {
3210         // Check which HTLCs are failed-backwards on channel force-closure
3211         let chanmon_cfgs = create_chanmon_cfgs(3);
3212         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3213         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3214         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3215         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3216         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3217
3218         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3219
3220         let mut payment_event = {
3221                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3222                 check_added_monitors!(nodes[0], 1);
3223
3224                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3225                 assert_eq!(events.len(), 1);
3226                 SendEvent::from_event(events.remove(0))
3227         };
3228
3229         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3230         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3231
3232         expect_pending_htlcs_forwardable!(nodes[1]);
3233
3234         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3235         assert_eq!(events_2.len(), 1);
3236         payment_event = SendEvent::from_event(events_2.remove(0));
3237         assert_eq!(payment_event.msgs.len(), 1);
3238
3239         check_added_monitors!(nodes[1], 1);
3240         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3241         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3242         check_added_monitors!(nodes[2], 1);
3243         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3244
3245         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3246         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3247         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3248
3249         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3250         check_closed_broadcast!(nodes[2], true);
3251         check_added_monitors!(nodes[2], 1);
3252         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3253         let tx = {
3254                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3255                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3256                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3257                 // back to nodes[1] upon timeout otherwise.
3258                 assert_eq!(node_txn.len(), 1);
3259                 node_txn.remove(0)
3260         };
3261
3262         mine_transaction(&nodes[1], &tx);
3263
3264         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3265         check_closed_broadcast!(nodes[1], true);
3266         check_added_monitors!(nodes[1], 1);
3267         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3268
3269         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3270         {
3271                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3272                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3273         }
3274         mine_transaction(&nodes[2], &tx);
3275         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3276         assert_eq!(node_txn.len(), 1);
3277         assert_eq!(node_txn[0].input.len(), 1);
3278         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3279         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3280         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3281
3282         check_spends!(node_txn[0], tx);
3283 }
3284
3285 #[test]
3286 fn test_dup_events_on_peer_disconnect() {
3287         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3288         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3289         // as we used to generate the event immediately upon receipt of the payment preimage in the
3290         // update_fulfill_htlc message.
3291
3292         let chanmon_cfgs = create_chanmon_cfgs(2);
3293         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3294         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3295         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3296         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3297
3298         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3299
3300         assert!(nodes[1].node.claim_funds(payment_preimage));
3301         check_added_monitors!(nodes[1], 1);
3302         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3303         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3304         expect_payment_sent!(nodes[0], payment_preimage);
3305
3306         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3307         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3308
3309         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3310         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3311 }
3312
3313 #[test]
3314 fn test_simple_peer_disconnect() {
3315         // Test that we can reconnect when there are no lost messages
3316         let chanmon_cfgs = create_chanmon_cfgs(3);
3317         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3318         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3319         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3320         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3321         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3322
3323         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3324         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3325         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3326
3327         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3328         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3329         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3330         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3331
3332         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3333         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3334         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3335
3336         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3337         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3338         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3339         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3340
3341         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3342         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3343
3344         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3345         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3346
3347         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3348         {
3349                 let events = nodes[0].node.get_and_clear_pending_events();
3350                 assert_eq!(events.len(), 2);
3351                 match events[0] {
3352                         Event::PaymentSent { payment_preimage, payment_hash } => {
3353                                 assert_eq!(payment_preimage, payment_preimage_3);
3354                                 assert_eq!(payment_hash, payment_hash_3);
3355                         },
3356                         _ => panic!("Unexpected event"),
3357                 }
3358                 match events[1] {
3359                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3360                                 assert_eq!(payment_hash, payment_hash_5);
3361                                 assert!(rejected_by_dest);
3362                         },
3363                         _ => panic!("Unexpected event"),
3364                 }
3365         }
3366
3367         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3368         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3369 }
3370
3371 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3372         // Test that we can reconnect when in-flight HTLC updates get dropped
3373         let chanmon_cfgs = create_chanmon_cfgs(2);
3374         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3375         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3376         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3377
3378         let mut as_funding_locked = None;
3379         if messages_delivered == 0 {
3380                 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3381                 as_funding_locked = Some(funding_locked);
3382                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3383                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3384                 // it before the channel_reestablish message.
3385         } else {
3386                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3387         }
3388
3389         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3390
3391         let payment_event = {
3392                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3393                 check_added_monitors!(nodes[0], 1);
3394
3395                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3396                 assert_eq!(events.len(), 1);
3397                 SendEvent::from_event(events.remove(0))
3398         };
3399         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3400
3401         if messages_delivered < 2 {
3402                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3403         } else {
3404                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3405                 if messages_delivered >= 3 {
3406                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3407                         check_added_monitors!(nodes[1], 1);
3408                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3409
3410                         if messages_delivered >= 4 {
3411                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3412                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3413                                 check_added_monitors!(nodes[0], 1);
3414
3415                                 if messages_delivered >= 5 {
3416                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3417                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3418                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3419                                         check_added_monitors!(nodes[0], 1);
3420
3421                                         if messages_delivered >= 6 {
3422                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3423                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3424                                                 check_added_monitors!(nodes[1], 1);
3425                                         }
3426                                 }
3427                         }
3428                 }
3429         }
3430
3431         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3432         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3433         if messages_delivered < 3 {
3434                 if simulate_broken_lnd {
3435                         // lnd has a long-standing bug where they send a funding_locked prior to a
3436                         // channel_reestablish if you reconnect prior to funding_locked time.
3437                         //
3438                         // Here we simulate that behavior, delivering a funding_locked immediately on
3439                         // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3440                         // in `reconnect_nodes` but we currently don't fail based on that.
3441                         //
3442                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3443                         nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3444                 }
3445                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3446                 // received on either side, both sides will need to resend them.
3447                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3448         } else if messages_delivered == 3 {
3449                 // nodes[0] still wants its RAA + commitment_signed
3450                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3451         } else if messages_delivered == 4 {
3452                 // nodes[0] still wants its commitment_signed
3453                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3454         } else if messages_delivered == 5 {
3455                 // nodes[1] still wants its final RAA
3456                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3457         } else if messages_delivered == 6 {
3458                 // Everything was delivered...
3459                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3460         }
3461
3462         let events_1 = nodes[1].node.get_and_clear_pending_events();
3463         assert_eq!(events_1.len(), 1);
3464         match events_1[0] {
3465                 Event::PendingHTLCsForwardable { .. } => { },
3466                 _ => panic!("Unexpected event"),
3467         };
3468
3469         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3470         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3471         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3472
3473         nodes[1].node.process_pending_htlc_forwards();
3474
3475         let events_2 = nodes[1].node.get_and_clear_pending_events();
3476         assert_eq!(events_2.len(), 1);
3477         match events_2[0] {
3478                 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3479                         assert_eq!(payment_hash_1, *payment_hash);
3480                         assert_eq!(amt, 1000000);
3481                         match &purpose {
3482                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3483                                         assert!(payment_preimage.is_none());
3484                                         assert_eq!(payment_secret_1, *payment_secret);
3485                                 },
3486                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3487                         }
3488                 },
3489                 _ => panic!("Unexpected event"),
3490         }
3491
3492         nodes[1].node.claim_funds(payment_preimage_1);
3493         check_added_monitors!(nodes[1], 1);
3494
3495         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3496         assert_eq!(events_3.len(), 1);
3497         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3498                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3499                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3500                         assert!(updates.update_add_htlcs.is_empty());
3501                         assert!(updates.update_fail_htlcs.is_empty());
3502                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3503                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3504                         assert!(updates.update_fee.is_none());
3505                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3506                 },
3507                 _ => panic!("Unexpected event"),
3508         };
3509
3510         if messages_delivered >= 1 {
3511                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3512
3513                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3514                 assert_eq!(events_4.len(), 1);
3515                 match events_4[0] {
3516                         Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
3517                                 assert_eq!(payment_preimage_1, *payment_preimage);
3518                                 assert_eq!(payment_hash_1, *payment_hash);
3519                         },
3520                         _ => panic!("Unexpected event"),
3521                 }
3522
3523                 if messages_delivered >= 2 {
3524                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3525                         check_added_monitors!(nodes[0], 1);
3526                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3527
3528                         if messages_delivered >= 3 {
3529                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3530                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3531                                 check_added_monitors!(nodes[1], 1);
3532
3533                                 if messages_delivered >= 4 {
3534                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3535                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3536                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3537                                         check_added_monitors!(nodes[1], 1);
3538
3539                                         if messages_delivered >= 5 {
3540                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3541                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3542                                                 check_added_monitors!(nodes[0], 1);
3543                                         }
3544                                 }
3545                         }
3546                 }
3547         }
3548
3549         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3550         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3551         if messages_delivered < 2 {
3552                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3553                 if messages_delivered < 1 {
3554                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3555                         assert_eq!(events_4.len(), 1);
3556                         match events_4[0] {
3557                                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
3558                                         assert_eq!(payment_preimage_1, *payment_preimage);
3559                                         assert_eq!(payment_hash_1, *payment_hash);
3560                                 },
3561                                 _ => panic!("Unexpected event"),
3562                         }
3563                 } else {
3564                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3565                 }
3566         } else if messages_delivered == 2 {
3567                 // nodes[0] still wants its RAA + commitment_signed
3568                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3569         } else if messages_delivered == 3 {
3570                 // nodes[0] still wants its commitment_signed
3571                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3572         } else if messages_delivered == 4 {
3573                 // nodes[1] still wants its final RAA
3574                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3575         } else if messages_delivered == 5 {
3576                 // Everything was delivered...
3577                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3578         }
3579
3580         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3581         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3582         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3583
3584         // Channel should still work fine...
3585         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3586         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3587         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3588 }
3589
3590 #[test]
3591 fn test_drop_messages_peer_disconnect_a() {
3592         do_test_drop_messages_peer_disconnect(0, true);
3593         do_test_drop_messages_peer_disconnect(0, false);
3594         do_test_drop_messages_peer_disconnect(1, false);
3595         do_test_drop_messages_peer_disconnect(2, false);
3596 }
3597
3598 #[test]
3599 fn test_drop_messages_peer_disconnect_b() {
3600         do_test_drop_messages_peer_disconnect(3, false);
3601         do_test_drop_messages_peer_disconnect(4, false);
3602         do_test_drop_messages_peer_disconnect(5, false);
3603         do_test_drop_messages_peer_disconnect(6, false);
3604 }
3605
3606 #[test]
3607 fn test_funding_peer_disconnect() {
3608         // Test that we can lock in our funding tx while disconnected
3609         let chanmon_cfgs = create_chanmon_cfgs(2);
3610         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3611         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3612         let persister: test_utils::TestPersister;
3613         let new_chain_monitor: test_utils::TestChainMonitor;
3614         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3615         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3616         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3617
3618         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3619         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3620
3621         confirm_transaction(&nodes[0], &tx);
3622         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3623         let chan_id;
3624         assert_eq!(events_1.len(), 1);
3625         match events_1[0] {
3626                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3627                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3628                         chan_id = msg.channel_id;
3629                 },
3630                 _ => panic!("Unexpected event"),
3631         }
3632
3633         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3634
3635         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3636         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3637
3638         confirm_transaction(&nodes[1], &tx);
3639         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3640         assert_eq!(events_2.len(), 2);
3641         let funding_locked = match events_2[0] {
3642                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3643                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3644                         msg.clone()
3645                 },
3646                 _ => panic!("Unexpected event"),
3647         };
3648         let bs_announcement_sigs = match events_2[1] {
3649                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3650                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3651                         msg.clone()
3652                 },
3653                 _ => panic!("Unexpected event"),
3654         };
3655
3656         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3657
3658         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3659         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3660         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3661         assert_eq!(events_3.len(), 2);
3662         let as_announcement_sigs = match events_3[0] {
3663                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3664                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3665                         msg.clone()
3666                 },
3667                 _ => panic!("Unexpected event"),
3668         };
3669         let (as_announcement, as_update) = match events_3[1] {
3670                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3671                         (msg.clone(), update_msg.clone())
3672                 },
3673                 _ => panic!("Unexpected event"),
3674         };
3675
3676         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3677         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3678         assert_eq!(events_4.len(), 1);
3679         let (_, bs_update) = match events_4[0] {
3680                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3681                         (msg.clone(), update_msg.clone())
3682                 },
3683                 _ => panic!("Unexpected event"),
3684         };
3685
3686         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3687         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3688         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3689
3690         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3691         let (payment_preimage, _, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3692         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3693
3694         // Check that after deserialization and reconnection we can still generate an identical
3695         // channel_announcement from the cached signatures.
3696         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3697
3698         let nodes_0_serialized = nodes[0].node.encode();
3699         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3700         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3701
3702         persister = test_utils::TestPersister::new();
3703         let keys_manager = &chanmon_cfgs[0].keys_manager;
3704         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);
3705         nodes[0].chain_monitor = &new_chain_monitor;
3706         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3707         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3708                 &mut chan_0_monitor_read, keys_manager).unwrap();
3709         assert!(chan_0_monitor_read.is_empty());
3710
3711         let mut nodes_0_read = &nodes_0_serialized[..];
3712         let (_, nodes_0_deserialized_tmp) = {
3713                 let mut channel_monitors = HashMap::new();
3714                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3715                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3716                         default_config: UserConfig::default(),
3717                         keys_manager,
3718                         fee_estimator: node_cfgs[0].fee_estimator,
3719                         chain_monitor: nodes[0].chain_monitor,
3720                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3721                         logger: nodes[0].logger,
3722                         channel_monitors,
3723                 }).unwrap()
3724         };
3725         nodes_0_deserialized = nodes_0_deserialized_tmp;
3726         assert!(nodes_0_read.is_empty());
3727
3728         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3729         nodes[0].node = &nodes_0_deserialized;
3730         check_added_monitors!(nodes[0], 1);
3731
3732         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3733
3734         // as_announcement should be re-generated exactly by broadcast_node_announcement.
3735         nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3736         let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3737         let mut found_announcement = false;
3738         for event in msgs.iter() {
3739                 match event {
3740                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3741                                 if *msg == as_announcement { found_announcement = true; }
3742                         },
3743                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3744                         _ => panic!("Unexpected event"),
3745                 }
3746         }
3747         assert!(found_announcement);
3748 }
3749
3750 #[test]
3751 fn test_drop_messages_peer_disconnect_dual_htlc() {
3752         // Test that we can handle reconnecting when both sides of a channel have pending
3753         // commitment_updates when we disconnect.
3754         let chanmon_cfgs = create_chanmon_cfgs(2);
3755         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3756         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3757         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3758         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3759
3760         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3761
3762         // Now try to send a second payment which will fail to send
3763         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3764         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
3765         check_added_monitors!(nodes[0], 1);
3766
3767         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3768         assert_eq!(events_1.len(), 1);
3769         match events_1[0] {
3770                 MessageSendEvent::UpdateHTLCs { .. } => {},
3771                 _ => panic!("Unexpected event"),
3772         }
3773
3774         assert!(nodes[1].node.claim_funds(payment_preimage_1));
3775         check_added_monitors!(nodes[1], 1);
3776
3777         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3778         assert_eq!(events_2.len(), 1);
3779         match events_2[0] {
3780                 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 } } => {
3781                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3782                         assert!(update_add_htlcs.is_empty());
3783                         assert_eq!(update_fulfill_htlcs.len(), 1);
3784                         assert!(update_fail_htlcs.is_empty());
3785                         assert!(update_fail_malformed_htlcs.is_empty());
3786                         assert!(update_fee.is_none());
3787
3788                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3789                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3790                         assert_eq!(events_3.len(), 1);
3791                         match events_3[0] {
3792                                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
3793                                         assert_eq!(*payment_preimage, payment_preimage_1);
3794                                         assert_eq!(*payment_hash, payment_hash_1);
3795                                 },
3796                                 _ => panic!("Unexpected event"),
3797                         }
3798
3799                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3800                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3801                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3802                         check_added_monitors!(nodes[0], 1);
3803                 },
3804                 _ => panic!("Unexpected event"),
3805         }
3806
3807         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3808         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3809
3810         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3811         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3812         assert_eq!(reestablish_1.len(), 1);
3813         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3814         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3815         assert_eq!(reestablish_2.len(), 1);
3816
3817         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3818         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3819         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3820         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3821
3822         assert!(as_resp.0.is_none());
3823         assert!(bs_resp.0.is_none());
3824
3825         assert!(bs_resp.1.is_none());
3826         assert!(bs_resp.2.is_none());
3827
3828         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3829
3830         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3831         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3832         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3833         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3834         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3835         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3836         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3837         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3838         // No commitment_signed so get_event_msg's assert(len == 1) passes
3839         check_added_monitors!(nodes[1], 1);
3840
3841         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3842         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3843         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3844         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3845         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3846         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3847         assert!(bs_second_commitment_signed.update_fee.is_none());
3848         check_added_monitors!(nodes[1], 1);
3849
3850         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3851         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3852         assert!(as_commitment_signed.update_add_htlcs.is_empty());
3853         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3854         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3855         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3856         assert!(as_commitment_signed.update_fee.is_none());
3857         check_added_monitors!(nodes[0], 1);
3858
3859         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3860         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3861         // No commitment_signed so get_event_msg's assert(len == 1) passes
3862         check_added_monitors!(nodes[0], 1);
3863
3864         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3865         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3866         // No commitment_signed so get_event_msg's assert(len == 1) passes
3867         check_added_monitors!(nodes[1], 1);
3868
3869         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3870         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3871         check_added_monitors!(nodes[1], 1);
3872
3873         expect_pending_htlcs_forwardable!(nodes[1]);
3874
3875         let events_5 = nodes[1].node.get_and_clear_pending_events();
3876         assert_eq!(events_5.len(), 1);
3877         match events_5[0] {
3878                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
3879                         assert_eq!(payment_hash_2, *payment_hash);
3880                         match &purpose {
3881                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3882                                         assert!(payment_preimage.is_none());
3883                                         assert_eq!(payment_secret_2, *payment_secret);
3884                                 },
3885                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3886                         }
3887                 },
3888                 _ => panic!("Unexpected event"),
3889         }
3890
3891         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3892         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3893         check_added_monitors!(nodes[0], 1);
3894
3895         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3896 }
3897
3898 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3899         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3900         // to avoid our counterparty failing the channel.
3901         let chanmon_cfgs = create_chanmon_cfgs(2);
3902         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3903         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3904         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3905
3906         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3907
3908         let our_payment_hash = if send_partial_mpp {
3909                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
3910                 // Use the utility function send_payment_along_path to send the payment with MPP data which
3911                 // indicates there are more HTLCs coming.
3912                 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.
3913                 let payment_id = PaymentId([42; 32]);
3914                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height, payment_id, &None).unwrap();
3915                 check_added_monitors!(nodes[0], 1);
3916                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3917                 assert_eq!(events.len(), 1);
3918                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3919                 // hop should *not* yet generate any PaymentReceived event(s).
3920                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
3921                 our_payment_hash
3922         } else {
3923                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3924         };
3925
3926         let mut block = Block {
3927                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3928                 txdata: vec![],
3929         };
3930         connect_block(&nodes[0], &block);
3931         connect_block(&nodes[1], &block);
3932         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
3933         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
3934                 block.header.prev_blockhash = block.block_hash();
3935                 connect_block(&nodes[0], &block);
3936                 connect_block(&nodes[1], &block);
3937         }
3938
3939         expect_pending_htlcs_forwardable!(nodes[1]);
3940
3941         check_added_monitors!(nodes[1], 1);
3942         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3943         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3944         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3945         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3946         assert!(htlc_timeout_updates.update_fee.is_none());
3947
3948         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3949         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3950         // 100_000 msat as u64, followed by the height at which we failed back above
3951         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
3952         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
3953         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
3954 }
3955
3956 #[test]
3957 fn test_htlc_timeout() {
3958         do_test_htlc_timeout(true);
3959         do_test_htlc_timeout(false);
3960 }
3961
3962 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
3963         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
3964         let chanmon_cfgs = create_chanmon_cfgs(3);
3965         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3966         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3967         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3968         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3969         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3970
3971         // Make sure all nodes are at the same starting height
3972         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
3973         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
3974         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
3975
3976         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
3977         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
3978         {
3979                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
3980         }
3981         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
3982         check_added_monitors!(nodes[1], 1);
3983
3984         // Now attempt to route a second payment, which should be placed in the holding cell
3985         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
3986         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
3987         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
3988         if forwarded_htlc {
3989                 check_added_monitors!(nodes[0], 1);
3990                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
3991                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3992                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3993                 expect_pending_htlcs_forwardable!(nodes[1]);
3994         }
3995         check_added_monitors!(nodes[1], 0);
3996
3997         connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
3998         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3999         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4000         connect_blocks(&nodes[1], 1);
4001
4002         if forwarded_htlc {
4003                 expect_pending_htlcs_forwardable!(nodes[1]);
4004                 check_added_monitors!(nodes[1], 1);
4005                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4006                 assert_eq!(fail_commit.len(), 1);
4007                 match fail_commit[0] {
4008                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4009                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4010                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4011                         },
4012                         _ => unreachable!(),
4013                 }
4014                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4015         } else {
4016                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4017         }
4018 }
4019
4020 #[test]
4021 fn test_holding_cell_htlc_add_timeouts() {
4022         do_test_holding_cell_htlc_add_timeouts(false);
4023         do_test_holding_cell_htlc_add_timeouts(true);
4024 }
4025
4026 #[test]
4027 fn test_no_txn_manager_serialize_deserialize() {
4028         let chanmon_cfgs = create_chanmon_cfgs(2);
4029         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4030         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4031         let logger: test_utils::TestLogger;
4032         let fee_estimator: test_utils::TestFeeEstimator;
4033         let persister: test_utils::TestPersister;
4034         let new_chain_monitor: test_utils::TestChainMonitor;
4035         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4036         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4037
4038         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4039
4040         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4041
4042         let nodes_0_serialized = nodes[0].node.encode();
4043         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4044         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4045                 .write(&mut chan_0_monitor_serialized).unwrap();
4046
4047         logger = test_utils::TestLogger::new();
4048         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4049         persister = test_utils::TestPersister::new();
4050         let keys_manager = &chanmon_cfgs[0].keys_manager;
4051         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4052         nodes[0].chain_monitor = &new_chain_monitor;
4053         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4054         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4055                 &mut chan_0_monitor_read, keys_manager).unwrap();
4056         assert!(chan_0_monitor_read.is_empty());
4057
4058         let mut nodes_0_read = &nodes_0_serialized[..];
4059         let config = UserConfig::default();
4060         let (_, nodes_0_deserialized_tmp) = {
4061                 let mut channel_monitors = HashMap::new();
4062                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4063                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4064                         default_config: config,
4065                         keys_manager,
4066                         fee_estimator: &fee_estimator,
4067                         chain_monitor: nodes[0].chain_monitor,
4068                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4069                         logger: &logger,
4070                         channel_monitors,
4071                 }).unwrap()
4072         };
4073         nodes_0_deserialized = nodes_0_deserialized_tmp;
4074         assert!(nodes_0_read.is_empty());
4075
4076         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4077         nodes[0].node = &nodes_0_deserialized;
4078         assert_eq!(nodes[0].node.list_channels().len(), 1);
4079         check_added_monitors!(nodes[0], 1);
4080
4081         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4082         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4083         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4084         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4085
4086         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4087         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4088         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4089         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4090
4091         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4092         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4093         for node in nodes.iter() {
4094                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4095                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4096                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4097         }
4098
4099         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4100 }
4101
4102 #[test]
4103 fn test_dup_htlc_onchain_fails_on_reload() {
4104         // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
4105         // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
4106         // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
4107         // the ChannelMonitor tells it to.
4108         //
4109         // If, due to an on-chain event, an HTLC is failed/claimed, and then we serialize the
4110         // ChannelManager, we generally expect there not to be a duplicate HTLC fail/claim (eg via a
4111         // PaymentPathFailed event appearing). However, because we may not serialize the relevant
4112         // ChannelMonitor at the same time, this isn't strictly guaranteed. In order to provide this
4113         // consistency, the ChannelManager explicitly tracks pending-onchain-resolution outbound HTLCs
4114         // and de-duplicates ChannelMonitor events.
4115         //
4116         // This tests that explicit tracking behavior.
4117         let chanmon_cfgs = create_chanmon_cfgs(2);
4118         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4119         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4120         let persister: test_utils::TestPersister;
4121         let new_chain_monitor: test_utils::TestChainMonitor;
4122         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4123         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4124
4125         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4126
4127         // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
4128         // nodes[0].
4129         let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 10000000);
4130         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
4131         check_closed_broadcast!(nodes[0], true);
4132         check_added_monitors!(nodes[0], 1);
4133         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4134
4135         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4136         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4137
4138         // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
4139         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
4140         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4141         assert_eq!(node_txn.len(), 3);
4142         assert_eq!(node_txn[0], node_txn[1]);
4143
4144         assert!(nodes[1].node.claim_funds(payment_preimage));
4145         check_added_monitors!(nodes[1], 1);
4146
4147         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4148         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4149         check_closed_broadcast!(nodes[1], true);
4150         check_added_monitors!(nodes[1], 1);
4151         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4152         let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4153
4154         header.prev_blockhash = nodes[0].best_block_hash();
4155         connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4156
4157         // Serialize out the ChannelMonitor before connecting the on-chain claim transactions. This is
4158         // fairly normal behavior as ChannelMonitor(s) are often not re-serialized when on-chain events
4159         // happen, unlike ChannelManager which tends to be re-serialized after any relevant event(s).
4160         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4161         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4162
4163         header.prev_blockhash = nodes[0].best_block_hash();
4164         let claim_block = Block { header, txdata: claim_txn};
4165         connect_block(&nodes[0], &claim_block);
4166         expect_payment_sent!(nodes[0], payment_preimage);
4167
4168         // ChannelManagers generally get re-serialized after any relevant event(s). Since we just
4169         // connected a highly-relevant block, it likely gets serialized out now.
4170         let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
4171         nodes[0].node.write(&mut chan_manager_serialized).unwrap();
4172
4173         // Now reload nodes[0]...
4174         persister = test_utils::TestPersister::new();
4175         let keys_manager = &chanmon_cfgs[0].keys_manager;
4176         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);
4177         nodes[0].chain_monitor = &new_chain_monitor;
4178         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4179         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4180                 &mut chan_0_monitor_read, keys_manager).unwrap();
4181         assert!(chan_0_monitor_read.is_empty());
4182
4183         let (_, nodes_0_deserialized_tmp) = {
4184                 let mut channel_monitors = HashMap::new();
4185                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4186                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
4187                         ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
4188                                 default_config: Default::default(),
4189                                 keys_manager,
4190                                 fee_estimator: node_cfgs[0].fee_estimator,
4191                                 chain_monitor: nodes[0].chain_monitor,
4192                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4193                                 logger: nodes[0].logger,
4194                                 channel_monitors,
4195                         }).unwrap()
4196         };
4197         nodes_0_deserialized = nodes_0_deserialized_tmp;
4198
4199         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4200         check_added_monitors!(nodes[0], 1);
4201         nodes[0].node = &nodes_0_deserialized;
4202
4203         // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
4204         // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
4205         // payment events should kick in, leaving us with no pending events here.
4206         let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
4207         nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
4208         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4209 }
4210
4211 #[test]
4212 fn test_manager_serialize_deserialize_events() {
4213         // This test makes sure the events field in ChannelManager survives de/serialization
4214         let chanmon_cfgs = create_chanmon_cfgs(2);
4215         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4216         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4217         let fee_estimator: test_utils::TestFeeEstimator;
4218         let persister: test_utils::TestPersister;
4219         let logger: test_utils::TestLogger;
4220         let new_chain_monitor: test_utils::TestChainMonitor;
4221         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4222         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4223
4224         // Start creating a channel, but stop right before broadcasting the funding transaction
4225         let channel_value = 100000;
4226         let push_msat = 10001;
4227         let a_flags = InitFeatures::known();
4228         let b_flags = InitFeatures::known();
4229         let node_a = nodes.remove(0);
4230         let node_b = nodes.remove(0);
4231         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4232         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()));
4233         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()));
4234
4235         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4236
4237         node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4238         check_added_monitors!(node_a, 0);
4239
4240         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()));
4241         {
4242                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4243                 assert_eq!(added_monitors.len(), 1);
4244                 assert_eq!(added_monitors[0].0, funding_output);
4245                 added_monitors.clear();
4246         }
4247
4248         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4249         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4250         {
4251                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4252                 assert_eq!(added_monitors.len(), 1);
4253                 assert_eq!(added_monitors[0].0, funding_output);
4254                 added_monitors.clear();
4255         }
4256         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4257
4258         nodes.push(node_a);
4259         nodes.push(node_b);
4260
4261         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4262         let nodes_0_serialized = nodes[0].node.encode();
4263         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4264         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4265
4266         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4267         logger = test_utils::TestLogger::new();
4268         persister = test_utils::TestPersister::new();
4269         let keys_manager = &chanmon_cfgs[0].keys_manager;
4270         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4271         nodes[0].chain_monitor = &new_chain_monitor;
4272         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4273         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4274                 &mut chan_0_monitor_read, keys_manager).unwrap();
4275         assert!(chan_0_monitor_read.is_empty());
4276
4277         let mut nodes_0_read = &nodes_0_serialized[..];
4278         let config = UserConfig::default();
4279         let (_, nodes_0_deserialized_tmp) = {
4280                 let mut channel_monitors = HashMap::new();
4281                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4282                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4283                         default_config: config,
4284                         keys_manager,
4285                         fee_estimator: &fee_estimator,
4286                         chain_monitor: nodes[0].chain_monitor,
4287                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4288                         logger: &logger,
4289                         channel_monitors,
4290                 }).unwrap()
4291         };
4292         nodes_0_deserialized = nodes_0_deserialized_tmp;
4293         assert!(nodes_0_read.is_empty());
4294
4295         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4296
4297         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4298         nodes[0].node = &nodes_0_deserialized;
4299
4300         // After deserializing, make sure the funding_transaction is still held by the channel manager
4301         let events_4 = nodes[0].node.get_and_clear_pending_events();
4302         assert_eq!(events_4.len(), 0);
4303         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4304         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4305
4306         // Make sure the channel is functioning as though the de/serialization never happened
4307         assert_eq!(nodes[0].node.list_channels().len(), 1);
4308         check_added_monitors!(nodes[0], 1);
4309
4310         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4311         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4312         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4313         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4314
4315         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4316         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4317         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4318         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4319
4320         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4321         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4322         for node in nodes.iter() {
4323                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4324                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4325                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4326         }
4327
4328         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4329 }
4330
4331 #[test]
4332 fn test_simple_manager_serialize_deserialize() {
4333         let chanmon_cfgs = create_chanmon_cfgs(2);
4334         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4335         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4336         let logger: test_utils::TestLogger;
4337         let fee_estimator: test_utils::TestFeeEstimator;
4338         let persister: test_utils::TestPersister;
4339         let new_chain_monitor: test_utils::TestChainMonitor;
4340         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4341         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4342         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4343
4344         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4345         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4346
4347         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4348
4349         let nodes_0_serialized = nodes[0].node.encode();
4350         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4351         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4352
4353         logger = test_utils::TestLogger::new();
4354         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4355         persister = test_utils::TestPersister::new();
4356         let keys_manager = &chanmon_cfgs[0].keys_manager;
4357         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4358         nodes[0].chain_monitor = &new_chain_monitor;
4359         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4360         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4361                 &mut chan_0_monitor_read, keys_manager).unwrap();
4362         assert!(chan_0_monitor_read.is_empty());
4363
4364         let mut nodes_0_read = &nodes_0_serialized[..];
4365         let (_, nodes_0_deserialized_tmp) = {
4366                 let mut channel_monitors = HashMap::new();
4367                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4368                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4369                         default_config: UserConfig::default(),
4370                         keys_manager,
4371                         fee_estimator: &fee_estimator,
4372                         chain_monitor: nodes[0].chain_monitor,
4373                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4374                         logger: &logger,
4375                         channel_monitors,
4376                 }).unwrap()
4377         };
4378         nodes_0_deserialized = nodes_0_deserialized_tmp;
4379         assert!(nodes_0_read.is_empty());
4380
4381         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4382         nodes[0].node = &nodes_0_deserialized;
4383         check_added_monitors!(nodes[0], 1);
4384
4385         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4386
4387         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4388         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4389 }
4390
4391 #[test]
4392 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4393         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4394         let chanmon_cfgs = create_chanmon_cfgs(4);
4395         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4396         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4397         let logger: test_utils::TestLogger;
4398         let fee_estimator: test_utils::TestFeeEstimator;
4399         let persister: test_utils::TestPersister;
4400         let new_chain_monitor: test_utils::TestChainMonitor;
4401         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4402         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4403         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4404         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4405         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4406
4407         let mut node_0_stale_monitors_serialized = Vec::new();
4408         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4409                 let mut writer = test_utils::TestVecWriter(Vec::new());
4410                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4411                 node_0_stale_monitors_serialized.push(writer.0);
4412         }
4413
4414         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4415
4416         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4417         let nodes_0_serialized = nodes[0].node.encode();
4418
4419         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4420         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4421         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4422         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4423
4424         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4425         // nodes[3])
4426         let mut node_0_monitors_serialized = Vec::new();
4427         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4428                 let mut writer = test_utils::TestVecWriter(Vec::new());
4429                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4430                 node_0_monitors_serialized.push(writer.0);
4431         }
4432
4433         logger = test_utils::TestLogger::new();
4434         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4435         persister = test_utils::TestPersister::new();
4436         let keys_manager = &chanmon_cfgs[0].keys_manager;
4437         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4438         nodes[0].chain_monitor = &new_chain_monitor;
4439
4440
4441         let mut node_0_stale_monitors = Vec::new();
4442         for serialized in node_0_stale_monitors_serialized.iter() {
4443                 let mut read = &serialized[..];
4444                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4445                 assert!(read.is_empty());
4446                 node_0_stale_monitors.push(monitor);
4447         }
4448
4449         let mut node_0_monitors = Vec::new();
4450         for serialized in node_0_monitors_serialized.iter() {
4451                 let mut read = &serialized[..];
4452                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4453                 assert!(read.is_empty());
4454                 node_0_monitors.push(monitor);
4455         }
4456
4457         let mut nodes_0_read = &nodes_0_serialized[..];
4458         if let Err(msgs::DecodeError::InvalidValue) =
4459                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4460                 default_config: UserConfig::default(),
4461                 keys_manager,
4462                 fee_estimator: &fee_estimator,
4463                 chain_monitor: nodes[0].chain_monitor,
4464                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4465                 logger: &logger,
4466                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4467         }) { } else {
4468                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4469         };
4470
4471         let mut nodes_0_read = &nodes_0_serialized[..];
4472         let (_, nodes_0_deserialized_tmp) =
4473                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4474                 default_config: UserConfig::default(),
4475                 keys_manager,
4476                 fee_estimator: &fee_estimator,
4477                 chain_monitor: nodes[0].chain_monitor,
4478                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4479                 logger: &logger,
4480                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4481         }).unwrap();
4482         nodes_0_deserialized = nodes_0_deserialized_tmp;
4483         assert!(nodes_0_read.is_empty());
4484
4485         { // Channel close should result in a commitment tx
4486                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4487                 assert_eq!(txn.len(), 1);
4488                 check_spends!(txn[0], funding_tx);
4489                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4490         }
4491
4492         for monitor in node_0_monitors.drain(..) {
4493                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4494                 check_added_monitors!(nodes[0], 1);
4495         }
4496         nodes[0].node = &nodes_0_deserialized;
4497         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4498
4499         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4500         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4501         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4502         //... and we can even still claim the payment!
4503         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4504
4505         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4506         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4507         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4508         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4509         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4510         assert_eq!(msg_events.len(), 1);
4511         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4512                 match action {
4513                         &ErrorAction::SendErrorMessage { ref msg } => {
4514                                 assert_eq!(msg.channel_id, channel_id);
4515                         },
4516                         _ => panic!("Unexpected event!"),
4517                 }
4518         }
4519 }
4520
4521 macro_rules! check_spendable_outputs {
4522         ($node: expr, $keysinterface: expr) => {
4523                 {
4524                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4525                         let mut txn = Vec::new();
4526                         let mut all_outputs = Vec::new();
4527                         let secp_ctx = Secp256k1::new();
4528                         for event in events.drain(..) {
4529                                 match event {
4530                                         Event::SpendableOutputs { mut outputs } => {
4531                                                 for outp in outputs.drain(..) {
4532                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4533                                                         all_outputs.push(outp);
4534                                                 }
4535                                         },
4536                                         _ => panic!("Unexpected event"),
4537                                 };
4538                         }
4539                         if all_outputs.len() > 1 {
4540                                 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) {
4541                                         txn.push(tx);
4542                                 }
4543                         }
4544                         txn
4545                 }
4546         }
4547 }
4548
4549 #[test]
4550 fn test_claim_sizeable_push_msat() {
4551         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4552         let chanmon_cfgs = create_chanmon_cfgs(2);
4553         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4554         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4555         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4556
4557         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4558         nodes[1].node.force_close_channel(&chan.2).unwrap();
4559         check_closed_broadcast!(nodes[1], true);
4560         check_added_monitors!(nodes[1], 1);
4561         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4562         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4563         assert_eq!(node_txn.len(), 1);
4564         check_spends!(node_txn[0], chan.3);
4565         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
4566
4567         mine_transaction(&nodes[1], &node_txn[0]);
4568         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4569
4570         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4571         assert_eq!(spend_txn.len(), 1);
4572         assert_eq!(spend_txn[0].input.len(), 1);
4573         check_spends!(spend_txn[0], node_txn[0]);
4574         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4575 }
4576
4577 #[test]
4578 fn test_claim_on_remote_sizeable_push_msat() {
4579         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4580         // to_remote output is encumbered by a P2WPKH
4581         let chanmon_cfgs = create_chanmon_cfgs(2);
4582         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4583         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4584         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4585
4586         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4587         nodes[0].node.force_close_channel(&chan.2).unwrap();
4588         check_closed_broadcast!(nodes[0], true);
4589         check_added_monitors!(nodes[0], 1);
4590         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4591
4592         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4593         assert_eq!(node_txn.len(), 1);
4594         check_spends!(node_txn[0], chan.3);
4595         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
4596
4597         mine_transaction(&nodes[1], &node_txn[0]);
4598         check_closed_broadcast!(nodes[1], true);
4599         check_added_monitors!(nodes[1], 1);
4600         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4601         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4602
4603         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4604         assert_eq!(spend_txn.len(), 1);
4605         check_spends!(spend_txn[0], node_txn[0]);
4606 }
4607
4608 #[test]
4609 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4610         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4611         // to_remote output is encumbered by a P2WPKH
4612
4613         let chanmon_cfgs = create_chanmon_cfgs(2);
4614         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4615         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4616         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4617
4618         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4619         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4620         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4621         assert_eq!(revoked_local_txn[0].input.len(), 1);
4622         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4623
4624         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4625         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4626         check_closed_broadcast!(nodes[1], true);
4627         check_added_monitors!(nodes[1], 1);
4628         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4629
4630         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4631         mine_transaction(&nodes[1], &node_txn[0]);
4632         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4633
4634         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4635         assert_eq!(spend_txn.len(), 3);
4636         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4637         check_spends!(spend_txn[1], node_txn[0]);
4638         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4639 }
4640
4641 #[test]
4642 fn test_static_spendable_outputs_preimage_tx() {
4643         let chanmon_cfgs = create_chanmon_cfgs(2);
4644         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4645         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4646         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4647
4648         // Create some initial channels
4649         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4650
4651         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4652
4653         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4654         assert_eq!(commitment_tx[0].input.len(), 1);
4655         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4656
4657         // Settle A's commitment tx on B's chain
4658         assert!(nodes[1].node.claim_funds(payment_preimage));
4659         check_added_monitors!(nodes[1], 1);
4660         mine_transaction(&nodes[1], &commitment_tx[0]);
4661         check_added_monitors!(nodes[1], 1);
4662         let events = nodes[1].node.get_and_clear_pending_msg_events();
4663         match events[0] {
4664                 MessageSendEvent::UpdateHTLCs { .. } => {},
4665                 _ => panic!("Unexpected event"),
4666         }
4667         match events[1] {
4668                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4669                 _ => panic!("Unexepected event"),
4670         }
4671
4672         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4673         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4674         assert_eq!(node_txn.len(), 3);
4675         check_spends!(node_txn[0], commitment_tx[0]);
4676         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4677         check_spends!(node_txn[1], chan_1.3);
4678         check_spends!(node_txn[2], node_txn[1]);
4679
4680         mine_transaction(&nodes[1], &node_txn[0]);
4681         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4682         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4683
4684         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4685         assert_eq!(spend_txn.len(), 1);
4686         check_spends!(spend_txn[0], node_txn[0]);
4687 }
4688
4689 #[test]
4690 fn test_static_spendable_outputs_timeout_tx() {
4691         let chanmon_cfgs = create_chanmon_cfgs(2);
4692         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4693         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4694         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4695
4696         // Create some initial channels
4697         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4698
4699         // Rebalance the network a bit by relaying one payment through all the channels ...
4700         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4701
4702         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4703
4704         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4705         assert_eq!(commitment_tx[0].input.len(), 1);
4706         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4707
4708         // Settle A's commitment tx on B' chain
4709         mine_transaction(&nodes[1], &commitment_tx[0]);
4710         check_added_monitors!(nodes[1], 1);
4711         let events = nodes[1].node.get_and_clear_pending_msg_events();
4712         match events[0] {
4713                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4714                 _ => panic!("Unexpected event"),
4715         }
4716         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4717
4718         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4719         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4720         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4721         check_spends!(node_txn[0], chan_1.3.clone());
4722         check_spends!(node_txn[1],  commitment_tx[0].clone());
4723         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4724
4725         mine_transaction(&nodes[1], &node_txn[1]);
4726         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4727         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4728         expect_payment_failed!(nodes[1], our_payment_hash, true);
4729
4730         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4731         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4732         check_spends!(spend_txn[0], commitment_tx[0]);
4733         check_spends!(spend_txn[1], node_txn[1]);
4734         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4735 }
4736
4737 #[test]
4738 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4739         let chanmon_cfgs = create_chanmon_cfgs(2);
4740         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4741         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4742         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4743
4744         // Create some initial channels
4745         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4746
4747         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4748         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4749         assert_eq!(revoked_local_txn[0].input.len(), 1);
4750         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4751
4752         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4753
4754         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4755         check_closed_broadcast!(nodes[1], true);
4756         check_added_monitors!(nodes[1], 1);
4757         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4758
4759         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4760         assert_eq!(node_txn.len(), 2);
4761         assert_eq!(node_txn[0].input.len(), 2);
4762         check_spends!(node_txn[0], revoked_local_txn[0]);
4763
4764         mine_transaction(&nodes[1], &node_txn[0]);
4765         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4766
4767         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4768         assert_eq!(spend_txn.len(), 1);
4769         check_spends!(spend_txn[0], node_txn[0]);
4770 }
4771
4772 #[test]
4773 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4774         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4775         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4776         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4777         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4778         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4779
4780         // Create some initial channels
4781         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4782
4783         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4784         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4785         assert_eq!(revoked_local_txn[0].input.len(), 1);
4786         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4787
4788         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4789
4790         // A will generate HTLC-Timeout from revoked commitment tx
4791         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4792         check_closed_broadcast!(nodes[0], true);
4793         check_added_monitors!(nodes[0], 1);
4794         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4795         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4796
4797         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4798         assert_eq!(revoked_htlc_txn.len(), 2);
4799         check_spends!(revoked_htlc_txn[0], chan_1.3);
4800         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4801         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4802         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4803         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4804
4805         // B will generate justice tx from A's revoked commitment/HTLC tx
4806         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4807         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4808         check_closed_broadcast!(nodes[1], true);
4809         check_added_monitors!(nodes[1], 1);
4810         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4811
4812         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4813         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4814         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4815         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4816         // transactions next...
4817         assert_eq!(node_txn[0].input.len(), 3);
4818         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4819
4820         assert_eq!(node_txn[1].input.len(), 2);
4821         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4822         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4823                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4824         } else {
4825                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4826                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4827         }
4828
4829         assert_eq!(node_txn[2].input.len(), 1);
4830         check_spends!(node_txn[2], chan_1.3);
4831
4832         mine_transaction(&nodes[1], &node_txn[1]);
4833         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4834
4835         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4836         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4837         assert_eq!(spend_txn.len(), 1);
4838         assert_eq!(spend_txn[0].input.len(), 1);
4839         check_spends!(spend_txn[0], node_txn[1]);
4840 }
4841
4842 #[test]
4843 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4844         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4845         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4846         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4847         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4848         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4849
4850         // Create some initial channels
4851         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4852
4853         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4854         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4855         assert_eq!(revoked_local_txn[0].input.len(), 1);
4856         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4857
4858         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4859         assert_eq!(revoked_local_txn[0].output.len(), 2);
4860
4861         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4862
4863         // B will generate HTLC-Success from revoked commitment tx
4864         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4865         check_closed_broadcast!(nodes[1], true);
4866         check_added_monitors!(nodes[1], 1);
4867         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4868         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4869
4870         assert_eq!(revoked_htlc_txn.len(), 2);
4871         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4872         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4873         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4874
4875         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4876         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4877         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4878
4879         // A will generate justice tx from B's revoked commitment/HTLC tx
4880         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4881         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4882         check_closed_broadcast!(nodes[0], true);
4883         check_added_monitors!(nodes[0], 1);
4884         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4885
4886         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4887         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4888
4889         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4890         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4891         // transactions next...
4892         assert_eq!(node_txn[0].input.len(), 2);
4893         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4894         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4895                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4896         } else {
4897                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4898                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4899         }
4900
4901         assert_eq!(node_txn[1].input.len(), 1);
4902         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4903
4904         check_spends!(node_txn[2], chan_1.3);
4905
4906         mine_transaction(&nodes[0], &node_txn[1]);
4907         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4908
4909         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4910         // didn't try to generate any new transactions.
4911
4912         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4913         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4914         assert_eq!(spend_txn.len(), 3);
4915         assert_eq!(spend_txn[0].input.len(), 1);
4916         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4917         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4918         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4919         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4920 }
4921
4922 #[test]
4923 fn test_onchain_to_onchain_claim() {
4924         // Test that in case of channel closure, we detect the state of output and claim HTLC
4925         // on downstream peer's remote commitment tx.
4926         // First, have C claim an HTLC against its own latest commitment transaction.
4927         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4928         // channel.
4929         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4930         // gets broadcast.
4931
4932         let chanmon_cfgs = create_chanmon_cfgs(3);
4933         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4934         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4935         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4936
4937         // Create some initial channels
4938         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4939         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4940
4941         // Ensure all nodes are at the same height
4942         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4943         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4944         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4945         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4946
4947         // Rebalance the network a bit by relaying one payment through all the channels ...
4948         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4949         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4950
4951         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4952         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4953         check_spends!(commitment_tx[0], chan_2.3);
4954         nodes[2].node.claim_funds(payment_preimage);
4955         check_added_monitors!(nodes[2], 1);
4956         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4957         assert!(updates.update_add_htlcs.is_empty());
4958         assert!(updates.update_fail_htlcs.is_empty());
4959         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4960         assert!(updates.update_fail_malformed_htlcs.is_empty());
4961
4962         mine_transaction(&nodes[2], &commitment_tx[0]);
4963         check_closed_broadcast!(nodes[2], true);
4964         check_added_monitors!(nodes[2], 1);
4965         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4966
4967         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4968         assert_eq!(c_txn.len(), 3);
4969         assert_eq!(c_txn[0], c_txn[2]);
4970         assert_eq!(commitment_tx[0], c_txn[1]);
4971         check_spends!(c_txn[1], chan_2.3);
4972         check_spends!(c_txn[2], c_txn[1]);
4973         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4974         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4975         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4976         assert_eq!(c_txn[0].lock_time, 0); // Success tx
4977
4978         // 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
4979         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4980         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
4981         check_added_monitors!(nodes[1], 1);
4982         let events = nodes[1].node.get_and_clear_pending_events();
4983         assert_eq!(events.len(), 2);
4984         match events[0] {
4985                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4986                 _ => panic!("Unexpected event"),
4987         }
4988         match events[1] {
4989                 Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
4990                         assert_eq!(fee_earned_msat, Some(1000));
4991                         assert_eq!(claim_from_onchain_tx, true);
4992                 },
4993                 _ => panic!("Unexpected event"),
4994         }
4995         {
4996                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4997                 // ChannelMonitor: claim tx
4998                 assert_eq!(b_txn.len(), 1);
4999                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5000                 b_txn.clear();
5001         }
5002         check_added_monitors!(nodes[1], 1);
5003         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5004         assert_eq!(msg_events.len(), 3);
5005         match msg_events[0] {
5006                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5007                 _ => panic!("Unexpected event"),
5008         }
5009         match msg_events[1] {
5010                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5011                 _ => panic!("Unexpected event"),
5012         }
5013         match msg_events[2] {
5014                 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, .. } } => {
5015                         assert!(update_add_htlcs.is_empty());
5016                         assert!(update_fail_htlcs.is_empty());
5017                         assert_eq!(update_fulfill_htlcs.len(), 1);
5018                         assert!(update_fail_malformed_htlcs.is_empty());
5019                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5020                 },
5021                 _ => panic!("Unexpected event"),
5022         };
5023         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5024         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5025         mine_transaction(&nodes[1], &commitment_tx[0]);
5026         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5027         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5028         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5029         assert_eq!(b_txn.len(), 3);
5030         check_spends!(b_txn[1], chan_1.3);
5031         check_spends!(b_txn[2], b_txn[1]);
5032         check_spends!(b_txn[0], commitment_tx[0]);
5033         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5034         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5035         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5036
5037         check_closed_broadcast!(nodes[1], true);
5038         check_added_monitors!(nodes[1], 1);
5039 }
5040
5041 #[test]
5042 fn test_duplicate_payment_hash_one_failure_one_success() {
5043         // Topology : A --> B --> C --> D
5044         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5045         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5046         // we forward one of the payments onwards to D.
5047         let chanmon_cfgs = create_chanmon_cfgs(4);
5048         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5049         // When this test was written, the default base fee floated based on the HTLC count.
5050         // It is now fixed, so we simply set the fee to the expected value here.
5051         let mut config = test_default_channel_config();
5052         config.channel_options.forwarding_fee_base_msat = 196;
5053         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5054                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5055         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5056
5057         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5058         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5059         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5060
5061         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5062         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5063         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5064         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5065         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5066
5067         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5068
5069         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, 0).unwrap();
5070         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5071         // script push size limit so that the below script length checks match
5072         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5073         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], vec![], 900000, TEST_FINAL_CLTV - 40);
5074         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5075
5076         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5077         assert_eq!(commitment_txn[0].input.len(), 1);
5078         check_spends!(commitment_txn[0], chan_2.3);
5079
5080         mine_transaction(&nodes[1], &commitment_txn[0]);
5081         check_closed_broadcast!(nodes[1], true);
5082         check_added_monitors!(nodes[1], 1);
5083         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5084         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5085
5086         let htlc_timeout_tx;
5087         { // Extract one of the two HTLC-Timeout transaction
5088                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5089                 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5090                 assert_eq!(node_txn.len(), 4);
5091                 check_spends!(node_txn[0], chan_2.3);
5092
5093                 check_spends!(node_txn[1], commitment_txn[0]);
5094                 assert_eq!(node_txn[1].input.len(), 1);
5095                 check_spends!(node_txn[2], commitment_txn[0]);
5096                 assert_eq!(node_txn[2].input.len(), 1);
5097                 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5098                 check_spends!(node_txn[3], commitment_txn[0]);
5099                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5100
5101                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5102                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5103                 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5104                 htlc_timeout_tx = node_txn[1].clone();
5105         }
5106
5107         nodes[2].node.claim_funds(our_payment_preimage);
5108         mine_transaction(&nodes[2], &commitment_txn[0]);
5109         check_added_monitors!(nodes[2], 2);
5110         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5111         let events = nodes[2].node.get_and_clear_pending_msg_events();
5112         match events[0] {
5113                 MessageSendEvent::UpdateHTLCs { .. } => {},
5114                 _ => panic!("Unexpected event"),
5115         }
5116         match events[1] {
5117                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5118                 _ => panic!("Unexepected event"),
5119         }
5120         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5121         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)
5122         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5123         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5124         assert_eq!(htlc_success_txn[0].input.len(), 1);
5125         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5126         assert_eq!(htlc_success_txn[1].input.len(), 1);
5127         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5128         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5129         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5130         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5131         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5132         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5133
5134         mine_transaction(&nodes[1], &htlc_timeout_tx);
5135         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5136         expect_pending_htlcs_forwardable!(nodes[1]);
5137         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5138         assert!(htlc_updates.update_add_htlcs.is_empty());
5139         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5140         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5141         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5142         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5143         check_added_monitors!(nodes[1], 1);
5144
5145         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5146         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5147         {
5148                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5149         }
5150         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5151
5152         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5153         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5154         // and nodes[2] fee) is rounded down and then claimed in full.
5155         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5156         expect_payment_forwarded!(nodes[1], Some(196*2), true);
5157         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5158         assert!(updates.update_add_htlcs.is_empty());
5159         assert!(updates.update_fail_htlcs.is_empty());
5160         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5161         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5162         assert!(updates.update_fail_malformed_htlcs.is_empty());
5163         check_added_monitors!(nodes[1], 1);
5164
5165         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5166         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5167
5168         let events = nodes[0].node.get_and_clear_pending_events();
5169         match events[0] {
5170                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
5171                         assert_eq!(*payment_preimage, our_payment_preimage);
5172                         assert_eq!(*payment_hash, duplicate_payment_hash);
5173                 }
5174                 _ => panic!("Unexpected event"),
5175         }
5176 }
5177
5178 #[test]
5179 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5180         let chanmon_cfgs = create_chanmon_cfgs(2);
5181         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5182         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5183         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5184
5185         // Create some initial channels
5186         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5187
5188         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5189         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5190         assert_eq!(local_txn.len(), 1);
5191         assert_eq!(local_txn[0].input.len(), 1);
5192         check_spends!(local_txn[0], chan_1.3);
5193
5194         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5195         nodes[1].node.claim_funds(payment_preimage);
5196         check_added_monitors!(nodes[1], 1);
5197         mine_transaction(&nodes[1], &local_txn[0]);
5198         check_added_monitors!(nodes[1], 1);
5199         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5200         let events = nodes[1].node.get_and_clear_pending_msg_events();
5201         match events[0] {
5202                 MessageSendEvent::UpdateHTLCs { .. } => {},
5203                 _ => panic!("Unexpected event"),
5204         }
5205         match events[1] {
5206                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5207                 _ => panic!("Unexepected event"),
5208         }
5209         let node_tx = {
5210                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5211                 assert_eq!(node_txn.len(), 3);
5212                 assert_eq!(node_txn[0], node_txn[2]);
5213                 assert_eq!(node_txn[1], local_txn[0]);
5214                 assert_eq!(node_txn[0].input.len(), 1);
5215                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5216                 check_spends!(node_txn[0], local_txn[0]);
5217                 node_txn[0].clone()
5218         };
5219
5220         mine_transaction(&nodes[1], &node_tx);
5221         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5222
5223         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5224         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5225         assert_eq!(spend_txn.len(), 1);
5226         assert_eq!(spend_txn[0].input.len(), 1);
5227         check_spends!(spend_txn[0], node_tx);
5228         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5229 }
5230
5231 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5232         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5233         // unrevoked commitment transaction.
5234         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5235         // a remote RAA before they could be failed backwards (and combinations thereof).
5236         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5237         // use the same payment hashes.
5238         // Thus, we use a six-node network:
5239         //
5240         // A \         / E
5241         //    - C - D -
5242         // B /         \ F
5243         // And test where C fails back to A/B when D announces its latest commitment transaction
5244         let chanmon_cfgs = create_chanmon_cfgs(6);
5245         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5246         // When this test was written, the default base fee floated based on the HTLC count.
5247         // It is now fixed, so we simply set the fee to the expected value here.
5248         let mut config = test_default_channel_config();
5249         config.channel_options.forwarding_fee_base_msat = 196;
5250         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5251                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5252         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5253
5254         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5255         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5256         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5257         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5258         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5259
5260         // Rebalance and check output sanity...
5261         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5262         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5263         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5264
5265         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5266         // 0th HTLC:
5267         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
5268         // 1st HTLC:
5269         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
5270         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5271         // 2nd HTLC:
5272         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
5273         // 3rd HTLC:
5274         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
5275         // 4th HTLC:
5276         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5277         // 5th HTLC:
5278         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5279         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5280         // 6th HTLC:
5281         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());
5282         // 7th HTLC:
5283         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());
5284
5285         // 8th HTLC:
5286         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5287         // 9th HTLC:
5288         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5289         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
5290
5291         // 10th HTLC:
5292         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
5293         // 11th HTLC:
5294         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5295         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());
5296
5297         // Double-check that six of the new HTLC were added
5298         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5299         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5300         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5301         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5302
5303         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5304         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5305         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5306         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5307         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5308         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5309         check_added_monitors!(nodes[4], 0);
5310         expect_pending_htlcs_forwardable!(nodes[4]);
5311         check_added_monitors!(nodes[4], 1);
5312
5313         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5314         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5315         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5316         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5317         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5318         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5319
5320         // Fail 3rd below-dust and 7th above-dust HTLCs
5321         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5322         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5323         check_added_monitors!(nodes[5], 0);
5324         expect_pending_htlcs_forwardable!(nodes[5]);
5325         check_added_monitors!(nodes[5], 1);
5326
5327         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5328         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5329         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5330         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5331
5332         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5333
5334         expect_pending_htlcs_forwardable!(nodes[3]);
5335         check_added_monitors!(nodes[3], 1);
5336         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5337         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5338         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5339         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5340         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5341         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5342         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5343         if deliver_last_raa {
5344                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5345         } else {
5346                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5347         }
5348
5349         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5350         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5351         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5352         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5353         //
5354         // We now broadcast the latest commitment transaction, which *should* result in failures for
5355         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5356         // the non-broadcast above-dust HTLCs.
5357         //
5358         // Alternatively, we may broadcast the previous commitment transaction, which should only
5359         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5360         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5361
5362         if announce_latest {
5363                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5364         } else {
5365                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5366         }
5367         let events = nodes[2].node.get_and_clear_pending_events();
5368         let close_event = if deliver_last_raa {
5369                 assert_eq!(events.len(), 2);
5370                 events[1].clone()
5371         } else {
5372                 assert_eq!(events.len(), 1);
5373                 events[0].clone()
5374         };
5375         match close_event {
5376                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5377                 _ => panic!("Unexpected event"),
5378         }
5379
5380         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5381         check_closed_broadcast!(nodes[2], true);
5382         if deliver_last_raa {
5383                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5384         } else {
5385                 expect_pending_htlcs_forwardable!(nodes[2]);
5386         }
5387         check_added_monitors!(nodes[2], 3);
5388
5389         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5390         assert_eq!(cs_msgs.len(), 2);
5391         let mut a_done = false;
5392         for msg in cs_msgs {
5393                 match msg {
5394                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5395                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5396                                 // should be failed-backwards here.
5397                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5398                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5399                                         for htlc in &updates.update_fail_htlcs {
5400                                                 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 });
5401                                         }
5402                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5403                                         assert!(!a_done);
5404                                         a_done = true;
5405                                         &nodes[0]
5406                                 } else {
5407                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5408                                         for htlc in &updates.update_fail_htlcs {
5409                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5410                                         }
5411                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5412                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5413                                         &nodes[1]
5414                                 };
5415                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5416                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5417                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5418                                 if announce_latest {
5419                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5420                                         if *node_id == nodes[0].node.get_our_node_id() {
5421                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5422                                         }
5423                                 }
5424                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5425                         },
5426                         _ => panic!("Unexpected event"),
5427                 }
5428         }
5429
5430         let as_events = nodes[0].node.get_and_clear_pending_events();
5431         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5432         let mut as_failds = HashSet::new();
5433         let mut as_updates = 0;
5434         for event in as_events.iter() {
5435                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5436                         assert!(as_failds.insert(*payment_hash));
5437                         if *payment_hash != payment_hash_2 {
5438                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5439                         } else {
5440                                 assert!(!rejected_by_dest);
5441                         }
5442                         if network_update.is_some() {
5443                                 as_updates += 1;
5444                         }
5445                 } else { panic!("Unexpected event"); }
5446         }
5447         assert!(as_failds.contains(&payment_hash_1));
5448         assert!(as_failds.contains(&payment_hash_2));
5449         if announce_latest {
5450                 assert!(as_failds.contains(&payment_hash_3));
5451                 assert!(as_failds.contains(&payment_hash_5));
5452         }
5453         assert!(as_failds.contains(&payment_hash_6));
5454
5455         let bs_events = nodes[1].node.get_and_clear_pending_events();
5456         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5457         let mut bs_failds = HashSet::new();
5458         let mut bs_updates = 0;
5459         for event in bs_events.iter() {
5460                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5461                         assert!(bs_failds.insert(*payment_hash));
5462                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5463                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5464                         } else {
5465                                 assert!(!rejected_by_dest);
5466                         }
5467                         if network_update.is_some() {
5468                                 bs_updates += 1;
5469                         }
5470                 } else { panic!("Unexpected event"); }
5471         }
5472         assert!(bs_failds.contains(&payment_hash_1));
5473         assert!(bs_failds.contains(&payment_hash_2));
5474         if announce_latest {
5475                 assert!(bs_failds.contains(&payment_hash_4));
5476         }
5477         assert!(bs_failds.contains(&payment_hash_5));
5478
5479         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5480         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5481         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5482         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5483         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5484         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5485 }
5486
5487 #[test]
5488 fn test_fail_backwards_latest_remote_announce_a() {
5489         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5490 }
5491
5492 #[test]
5493 fn test_fail_backwards_latest_remote_announce_b() {
5494         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5495 }
5496
5497 #[test]
5498 fn test_fail_backwards_previous_remote_announce() {
5499         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5500         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5501         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5502 }
5503
5504 #[test]
5505 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5506         let chanmon_cfgs = create_chanmon_cfgs(2);
5507         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5508         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5509         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5510
5511         // Create some initial channels
5512         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5513
5514         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5515         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5516         assert_eq!(local_txn[0].input.len(), 1);
5517         check_spends!(local_txn[0], chan_1.3);
5518
5519         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5520         mine_transaction(&nodes[0], &local_txn[0]);
5521         check_closed_broadcast!(nodes[0], true);
5522         check_added_monitors!(nodes[0], 1);
5523         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5524         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5525
5526         let htlc_timeout = {
5527                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5528                 assert_eq!(node_txn.len(), 2);
5529                 check_spends!(node_txn[0], chan_1.3);
5530                 assert_eq!(node_txn[1].input.len(), 1);
5531                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5532                 check_spends!(node_txn[1], local_txn[0]);
5533                 node_txn[1].clone()
5534         };
5535
5536         mine_transaction(&nodes[0], &htlc_timeout);
5537         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5538         expect_payment_failed!(nodes[0], our_payment_hash, true);
5539
5540         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5541         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5542         assert_eq!(spend_txn.len(), 3);
5543         check_spends!(spend_txn[0], local_txn[0]);
5544         assert_eq!(spend_txn[1].input.len(), 1);
5545         check_spends!(spend_txn[1], htlc_timeout);
5546         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5547         assert_eq!(spend_txn[2].input.len(), 2);
5548         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5549         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5550                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5551 }
5552
5553 #[test]
5554 fn test_key_derivation_params() {
5555         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5556         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5557         // let us re-derive the channel key set to then derive a delayed_payment_key.
5558
5559         let chanmon_cfgs = create_chanmon_cfgs(3);
5560
5561         // We manually create the node configuration to backup the seed.
5562         let seed = [42; 32];
5563         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5564         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);
5565         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() };
5566         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5567         node_cfgs.remove(0);
5568         node_cfgs.insert(0, node);
5569
5570         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5571         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5572
5573         // Create some initial channels
5574         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5575         // for node 0
5576         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5577         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5578         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5579
5580         // Ensure all nodes are at the same height
5581         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5582         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5583         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5584         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5585
5586         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5587         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5588         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5589         assert_eq!(local_txn_1[0].input.len(), 1);
5590         check_spends!(local_txn_1[0], chan_1.3);
5591
5592         // We check funding pubkey are unique
5593         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]));
5594         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]));
5595         if from_0_funding_key_0 == from_1_funding_key_0
5596             || from_0_funding_key_0 == from_1_funding_key_1
5597             || from_0_funding_key_1 == from_1_funding_key_0
5598             || from_0_funding_key_1 == from_1_funding_key_1 {
5599                 panic!("Funding pubkeys aren't unique");
5600         }
5601
5602         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5603         mine_transaction(&nodes[0], &local_txn_1[0]);
5604         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5605         check_closed_broadcast!(nodes[0], true);
5606         check_added_monitors!(nodes[0], 1);
5607         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5608
5609         let htlc_timeout = {
5610                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5611                 assert_eq!(node_txn[1].input.len(), 1);
5612                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5613                 check_spends!(node_txn[1], local_txn_1[0]);
5614                 node_txn[1].clone()
5615         };
5616
5617         mine_transaction(&nodes[0], &htlc_timeout);
5618         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5619         expect_payment_failed!(nodes[0], our_payment_hash, true);
5620
5621         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5622         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5623         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5624         assert_eq!(spend_txn.len(), 3);
5625         check_spends!(spend_txn[0], local_txn_1[0]);
5626         assert_eq!(spend_txn[1].input.len(), 1);
5627         check_spends!(spend_txn[1], htlc_timeout);
5628         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5629         assert_eq!(spend_txn[2].input.len(), 2);
5630         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5631         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5632                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5633 }
5634
5635 #[test]
5636 fn test_static_output_closing_tx() {
5637         let chanmon_cfgs = create_chanmon_cfgs(2);
5638         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5639         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5640         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5641
5642         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5643
5644         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5645         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5646
5647         mine_transaction(&nodes[0], &closing_tx);
5648         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5649         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5650
5651         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5652         assert_eq!(spend_txn.len(), 1);
5653         check_spends!(spend_txn[0], closing_tx);
5654
5655         mine_transaction(&nodes[1], &closing_tx);
5656         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5657         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5658
5659         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5660         assert_eq!(spend_txn.len(), 1);
5661         check_spends!(spend_txn[0], closing_tx);
5662 }
5663
5664 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5665         let chanmon_cfgs = create_chanmon_cfgs(2);
5666         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5667         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5668         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5669         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5670
5671         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5672
5673         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5674         // present in B's local commitment transaction, but none of A's commitment transactions.
5675         assert!(nodes[1].node.claim_funds(our_payment_preimage));
5676         check_added_monitors!(nodes[1], 1);
5677
5678         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5679         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5680         let events = nodes[0].node.get_and_clear_pending_events();
5681         assert_eq!(events.len(), 1);
5682         match events[0] {
5683                 Event::PaymentSent { payment_preimage, payment_hash } => {
5684                         assert_eq!(payment_preimage, our_payment_preimage);
5685                         assert_eq!(payment_hash, our_payment_hash);
5686                 },
5687                 _ => panic!("Unexpected event"),
5688         }
5689
5690         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5691         check_added_monitors!(nodes[0], 1);
5692         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5693         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5694         check_added_monitors!(nodes[1], 1);
5695
5696         let starting_block = nodes[1].best_block_info();
5697         let mut block = Block {
5698                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5699                 txdata: vec![],
5700         };
5701         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5702                 connect_block(&nodes[1], &block);
5703                 block.header.prev_blockhash = block.block_hash();
5704         }
5705         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5706         check_closed_broadcast!(nodes[1], true);
5707         check_added_monitors!(nodes[1], 1);
5708         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5709 }
5710
5711 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5712         let chanmon_cfgs = create_chanmon_cfgs(2);
5713         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5714         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5715         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5716         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5717
5718         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5719         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5720         check_added_monitors!(nodes[0], 1);
5721
5722         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5723
5724         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5725         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5726         // to "time out" the HTLC.
5727
5728         let starting_block = nodes[1].best_block_info();
5729         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5730
5731         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5732                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5733                 header.prev_blockhash = header.block_hash();
5734         }
5735         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5736         check_closed_broadcast!(nodes[0], true);
5737         check_added_monitors!(nodes[0], 1);
5738         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5739 }
5740
5741 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5742         let chanmon_cfgs = create_chanmon_cfgs(3);
5743         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5744         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5745         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5746         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5747
5748         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5749         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5750         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5751         // actually revoked.
5752         let htlc_value = if use_dust { 50000 } else { 3000000 };
5753         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5754         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5755         expect_pending_htlcs_forwardable!(nodes[1]);
5756         check_added_monitors!(nodes[1], 1);
5757
5758         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5759         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5760         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5761         check_added_monitors!(nodes[0], 1);
5762         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5763         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5764         check_added_monitors!(nodes[1], 1);
5765         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5766         check_added_monitors!(nodes[1], 1);
5767         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5768
5769         if check_revoke_no_close {
5770                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5771                 check_added_monitors!(nodes[0], 1);
5772         }
5773
5774         let starting_block = nodes[1].best_block_info();
5775         let mut block = Block {
5776                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5777                 txdata: vec![],
5778         };
5779         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5780                 connect_block(&nodes[0], &block);
5781                 block.header.prev_blockhash = block.block_hash();
5782         }
5783         if !check_revoke_no_close {
5784                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5785                 check_closed_broadcast!(nodes[0], true);
5786                 check_added_monitors!(nodes[0], 1);
5787                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5788         } else {
5789                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5790         }
5791 }
5792
5793 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5794 // There are only a few cases to test here:
5795 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5796 //    broadcastable commitment transactions result in channel closure,
5797 //  * its included in an unrevoked-but-previous remote commitment transaction,
5798 //  * its included in the latest remote or local commitment transactions.
5799 // We test each of the three possible commitment transactions individually and use both dust and
5800 // non-dust HTLCs.
5801 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5802 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5803 // tested for at least one of the cases in other tests.
5804 #[test]
5805 fn htlc_claim_single_commitment_only_a() {
5806         do_htlc_claim_local_commitment_only(true);
5807         do_htlc_claim_local_commitment_only(false);
5808
5809         do_htlc_claim_current_remote_commitment_only(true);
5810         do_htlc_claim_current_remote_commitment_only(false);
5811 }
5812
5813 #[test]
5814 fn htlc_claim_single_commitment_only_b() {
5815         do_htlc_claim_previous_remote_commitment_only(true, false);
5816         do_htlc_claim_previous_remote_commitment_only(false, false);
5817         do_htlc_claim_previous_remote_commitment_only(true, true);
5818         do_htlc_claim_previous_remote_commitment_only(false, true);
5819 }
5820
5821 #[test]
5822 #[should_panic]
5823 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5824         let chanmon_cfgs = create_chanmon_cfgs(2);
5825         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5826         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5827         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5828         //Force duplicate channel ids
5829         for node in nodes.iter() {
5830                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5831         }
5832
5833         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5834         let channel_value_satoshis=10000;
5835         let push_msat=10001;
5836         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5837         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5838         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5839
5840         //Create a second channel with a channel_id collision
5841         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5842 }
5843
5844 #[test]
5845 fn bolt2_open_channel_sending_node_checks_part2() {
5846         let chanmon_cfgs = create_chanmon_cfgs(2);
5847         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5848         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5849         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5850
5851         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5852         let channel_value_satoshis=2^24;
5853         let push_msat=10001;
5854         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5855
5856         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5857         let channel_value_satoshis=10000;
5858         // Test when push_msat is equal to 1000 * funding_satoshis.
5859         let push_msat=1000*channel_value_satoshis+1;
5860         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5861
5862         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5863         let channel_value_satoshis=10000;
5864         let push_msat=10001;
5865         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
5866         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5867         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5868
5869         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5870         // 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
5871         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5872
5873         // 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.
5874         assert!(BREAKDOWN_TIMEOUT>0);
5875         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5876
5877         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5878         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5879         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5880
5881         // 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.
5882         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5883         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5884         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5885         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5886         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5887 }
5888
5889 #[test]
5890 fn bolt2_open_channel_sane_dust_limit() {
5891         let chanmon_cfgs = create_chanmon_cfgs(2);
5892         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5893         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5894         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5895
5896         let channel_value_satoshis=1000000;
5897         let push_msat=10001;
5898         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5899         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5900         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5901         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5902
5903         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5904         let events = nodes[1].node.get_and_clear_pending_msg_events();
5905         let err_msg = match events[0] {
5906                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5907                         msg.clone()
5908                 },
5909                 _ => panic!("Unexpected event"),
5910         };
5911         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5912 }
5913
5914 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5915 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5916 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5917 // is no longer affordable once it's freed.
5918 #[test]
5919 fn test_fail_holding_cell_htlc_upon_free() {
5920         let chanmon_cfgs = create_chanmon_cfgs(2);
5921         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5922         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5923         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5924         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5925
5926         // First nodes[0] generates an update_fee, setting the channel's
5927         // pending_update_fee.
5928         {
5929                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5930                 *feerate_lock += 20;
5931         }
5932         nodes[0].node.timer_tick_occurred();
5933         check_added_monitors!(nodes[0], 1);
5934
5935         let events = nodes[0].node.get_and_clear_pending_msg_events();
5936         assert_eq!(events.len(), 1);
5937         let (update_msg, commitment_signed) = match events[0] {
5938                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5939                         (update_fee.as_ref(), commitment_signed)
5940                 },
5941                 _ => panic!("Unexpected event"),
5942         };
5943
5944         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5945
5946         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5947         let channel_reserve = chan_stat.channel_reserve_msat;
5948         let feerate = get_feerate!(nodes[0], chan.2);
5949
5950         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5951         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5952         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5953
5954         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5955         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
5956         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5957         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5958
5959         // Flush the pending fee update.
5960         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5961         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5962         check_added_monitors!(nodes[1], 1);
5963         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5964         check_added_monitors!(nodes[0], 1);
5965
5966         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5967         // HTLC, but now that the fee has been raised the payment will now fail, causing
5968         // us to surface its failure to the user.
5969         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5970         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5971         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);
5972         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 {}",
5973                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5974         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5975
5976         // Check that the payment failed to be sent out.
5977         let events = nodes[0].node.get_and_clear_pending_events();
5978         assert_eq!(events.len(), 1);
5979         match &events[0] {
5980                 &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 } => {
5981                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5982                         assert_eq!(*rejected_by_dest, false);
5983                         assert_eq!(*all_paths_failed, true);
5984                         assert_eq!(*network_update, None);
5985                         assert_eq!(*short_channel_id, None);
5986                         assert_eq!(*error_code, None);
5987                         assert_eq!(*error_data, None);
5988                 },
5989                 _ => panic!("Unexpected event"),
5990         }
5991 }
5992
5993 // Test that if multiple HTLCs are released from the holding cell and one is
5994 // valid but the other is no longer valid upon release, the valid HTLC can be
5995 // successfully completed while the other one fails as expected.
5996 #[test]
5997 fn test_free_and_fail_holding_cell_htlcs() {
5998         let chanmon_cfgs = create_chanmon_cfgs(2);
5999         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6000         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6001         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6002         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6003
6004         // First nodes[0] generates an update_fee, setting the channel's
6005         // pending_update_fee.
6006         {
6007                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6008                 *feerate_lock += 200;
6009         }
6010         nodes[0].node.timer_tick_occurred();
6011         check_added_monitors!(nodes[0], 1);
6012
6013         let events = nodes[0].node.get_and_clear_pending_msg_events();
6014         assert_eq!(events.len(), 1);
6015         let (update_msg, commitment_signed) = match events[0] {
6016                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6017                         (update_fee.as_ref(), commitment_signed)
6018                 },
6019                 _ => panic!("Unexpected event"),
6020         };
6021
6022         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6023
6024         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6025         let channel_reserve = chan_stat.channel_reserve_msat;
6026         let feerate = get_feerate!(nodes[0], chan.2);
6027
6028         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6029         let amt_1 = 20000;
6030         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6031         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6032         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6033
6034         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6035         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6036         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6037         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6038         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6039         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6040         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6041
6042         // Flush the pending fee update.
6043         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6044         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6045         check_added_monitors!(nodes[1], 1);
6046         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6047         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6048         check_added_monitors!(nodes[0], 2);
6049
6050         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6051         // but now that the fee has been raised the second payment will now fail, causing us
6052         // to surface its failure to the user. The first payment should succeed.
6053         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6054         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6055         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);
6056         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 {}",
6057                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6058         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6059
6060         // Check that the second payment failed to be sent out.
6061         let events = nodes[0].node.get_and_clear_pending_events();
6062         assert_eq!(events.len(), 1);
6063         match &events[0] {
6064                 &Event::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 } => {
6065                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6066                         assert_eq!(*rejected_by_dest, false);
6067                         assert_eq!(*all_paths_failed, true);
6068                         assert_eq!(*network_update, None);
6069                         assert_eq!(*short_channel_id, None);
6070                         assert_eq!(*error_code, None);
6071                         assert_eq!(*error_data, None);
6072                 },
6073                 _ => panic!("Unexpected event"),
6074         }
6075
6076         // Complete the first payment and the RAA from the fee update.
6077         let (payment_event, send_raa_event) = {
6078                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6079                 assert_eq!(msgs.len(), 2);
6080                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6081         };
6082         let raa = match send_raa_event {
6083                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6084                 _ => panic!("Unexpected event"),
6085         };
6086         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6087         check_added_monitors!(nodes[1], 1);
6088         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6089         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6090         let events = nodes[1].node.get_and_clear_pending_events();
6091         assert_eq!(events.len(), 1);
6092         match events[0] {
6093                 Event::PendingHTLCsForwardable { .. } => {},
6094                 _ => panic!("Unexpected event"),
6095         }
6096         nodes[1].node.process_pending_htlc_forwards();
6097         let events = nodes[1].node.get_and_clear_pending_events();
6098         assert_eq!(events.len(), 1);
6099         match events[0] {
6100                 Event::PaymentReceived { .. } => {},
6101                 _ => panic!("Unexpected event"),
6102         }
6103         nodes[1].node.claim_funds(payment_preimage_1);
6104         check_added_monitors!(nodes[1], 1);
6105         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6106         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6107         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6108         let events = nodes[0].node.get_and_clear_pending_events();
6109         assert_eq!(events.len(), 1);
6110         match events[0] {
6111                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
6112                         assert_eq!(*payment_preimage, payment_preimage_1);
6113                         assert_eq!(*payment_hash, payment_hash_1);
6114                 }
6115                 _ => panic!("Unexpected event"),
6116         }
6117 }
6118
6119 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6120 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6121 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6122 // once it's freed.
6123 #[test]
6124 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6125         let chanmon_cfgs = create_chanmon_cfgs(3);
6126         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6127         // When this test was written, the default base fee floated based on the HTLC count.
6128         // It is now fixed, so we simply set the fee to the expected value here.
6129         let mut config = test_default_channel_config();
6130         config.channel_options.forwarding_fee_base_msat = 196;
6131         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6132         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6133         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6134         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6135
6136         // First nodes[1] generates an update_fee, setting the channel's
6137         // pending_update_fee.
6138         {
6139                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6140                 *feerate_lock += 20;
6141         }
6142         nodes[1].node.timer_tick_occurred();
6143         check_added_monitors!(nodes[1], 1);
6144
6145         let events = nodes[1].node.get_and_clear_pending_msg_events();
6146         assert_eq!(events.len(), 1);
6147         let (update_msg, commitment_signed) = match events[0] {
6148                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6149                         (update_fee.as_ref(), commitment_signed)
6150                 },
6151                 _ => panic!("Unexpected event"),
6152         };
6153
6154         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6155
6156         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6157         let channel_reserve = chan_stat.channel_reserve_msat;
6158         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6159
6160         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6161         let feemsat = 239;
6162         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6163         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6164         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6165         let payment_event = {
6166                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6167                 check_added_monitors!(nodes[0], 1);
6168
6169                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6170                 assert_eq!(events.len(), 1);
6171
6172                 SendEvent::from_event(events.remove(0))
6173         };
6174         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6175         check_added_monitors!(nodes[1], 0);
6176         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6177         expect_pending_htlcs_forwardable!(nodes[1]);
6178
6179         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6180         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6181
6182         // Flush the pending fee update.
6183         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6184         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6185         check_added_monitors!(nodes[2], 1);
6186         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6187         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6188         check_added_monitors!(nodes[1], 2);
6189
6190         // A final RAA message is generated to finalize the fee update.
6191         let events = nodes[1].node.get_and_clear_pending_msg_events();
6192         assert_eq!(events.len(), 1);
6193
6194         let raa_msg = match &events[0] {
6195                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6196                         msg.clone()
6197                 },
6198                 _ => panic!("Unexpected event"),
6199         };
6200
6201         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6202         check_added_monitors!(nodes[2], 1);
6203         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6204
6205         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6206         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6207         assert_eq!(process_htlc_forwards_event.len(), 1);
6208         match &process_htlc_forwards_event[0] {
6209                 &Event::PendingHTLCsForwardable { .. } => {},
6210                 _ => panic!("Unexpected event"),
6211         }
6212
6213         // In response, we call ChannelManager's process_pending_htlc_forwards
6214         nodes[1].node.process_pending_htlc_forwards();
6215         check_added_monitors!(nodes[1], 1);
6216
6217         // This causes the HTLC to be failed backwards.
6218         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6219         assert_eq!(fail_event.len(), 1);
6220         let (fail_msg, commitment_signed) = match &fail_event[0] {
6221                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6222                         assert_eq!(updates.update_add_htlcs.len(), 0);
6223                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6224                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6225                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6226                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6227                 },
6228                 _ => panic!("Unexpected event"),
6229         };
6230
6231         // Pass the failure messages back to nodes[0].
6232         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6233         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6234
6235         // Complete the HTLC failure+removal process.
6236         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6237         check_added_monitors!(nodes[0], 1);
6238         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6239         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6240         check_added_monitors!(nodes[1], 2);
6241         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6242         assert_eq!(final_raa_event.len(), 1);
6243         let raa = match &final_raa_event[0] {
6244                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6245                 _ => panic!("Unexpected event"),
6246         };
6247         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6248         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6249         check_added_monitors!(nodes[0], 1);
6250 }
6251
6252 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6253 // 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.
6254 //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.
6255
6256 #[test]
6257 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6258         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6259         let chanmon_cfgs = create_chanmon_cfgs(2);
6260         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6261         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6262         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6263         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6264
6265         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6266         route.paths[0][0].fee_msat = 100;
6267
6268         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6269                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6270         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6271         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6272 }
6273
6274 #[test]
6275 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6276         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6277         let chanmon_cfgs = create_chanmon_cfgs(2);
6278         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6279         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6280         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6281         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6282
6283         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6284         route.paths[0][0].fee_msat = 0;
6285         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6286                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6287
6288         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6289         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6290 }
6291
6292 #[test]
6293 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6294         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6295         let chanmon_cfgs = create_chanmon_cfgs(2);
6296         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6297         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6298         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6299         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6300
6301         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6302         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6303         check_added_monitors!(nodes[0], 1);
6304         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6305         updates.update_add_htlcs[0].amount_msat = 0;
6306
6307         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6308         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6309         check_closed_broadcast!(nodes[1], true).unwrap();
6310         check_added_monitors!(nodes[1], 1);
6311         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6312 }
6313
6314 #[test]
6315 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6316         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6317         //It is enforced when constructing a route.
6318         let chanmon_cfgs = create_chanmon_cfgs(2);
6319         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6320         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6321         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6322         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6323
6324         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], vec![], 100000000, 500000001);
6325         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6326                 assert_eq!(err, &"Channel CLTV overflowed?"));
6327 }
6328
6329 #[test]
6330 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6331         //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.
6332         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6333         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6334         let chanmon_cfgs = create_chanmon_cfgs(2);
6335         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6336         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6337         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6338         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6339         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6340
6341         for i in 0..max_accepted_htlcs {
6342                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6343                 let payment_event = {
6344                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6345                         check_added_monitors!(nodes[0], 1);
6346
6347                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6348                         assert_eq!(events.len(), 1);
6349                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6350                                 assert_eq!(htlcs[0].htlc_id, i);
6351                         } else {
6352                                 assert!(false);
6353                         }
6354                         SendEvent::from_event(events.remove(0))
6355                 };
6356                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6357                 check_added_monitors!(nodes[1], 0);
6358                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6359
6360                 expect_pending_htlcs_forwardable!(nodes[1]);
6361                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6362         }
6363         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6364         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6365                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6366
6367         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6368         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6369 }
6370
6371 #[test]
6372 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6373         //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.
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 channel_value = 100000;
6379         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6380         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6381
6382         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6383
6384         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6385         // Manually create a route over our max in flight (which our router normally automatically
6386         // limits us to.
6387         route.paths[0][0].fee_msat =  max_in_flight + 1;
6388         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6389                 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)));
6390
6391         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6392         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);
6393
6394         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6395 }
6396
6397 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6398 #[test]
6399 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6400         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6401         let chanmon_cfgs = create_chanmon_cfgs(2);
6402         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6403         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6404         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6405         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6406         let htlc_minimum_msat: u64;
6407         {
6408                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6409                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6410                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6411         }
6412
6413         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6414         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6415         check_added_monitors!(nodes[0], 1);
6416         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6417         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6418         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6419         assert!(nodes[1].node.list_channels().is_empty());
6420         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6421         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()));
6422         check_added_monitors!(nodes[1], 1);
6423         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6424 }
6425
6426 #[test]
6427 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6428         //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
6429         let chanmon_cfgs = create_chanmon_cfgs(2);
6430         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6431         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6432         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6433         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6434
6435         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6436         let channel_reserve = chan_stat.channel_reserve_msat;
6437         let feerate = get_feerate!(nodes[0], chan.2);
6438         // The 2* and +1 are for the fee spike reserve.
6439         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6440
6441         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6442         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6443         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6444         check_added_monitors!(nodes[0], 1);
6445         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6446
6447         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6448         // at this time channel-initiatee receivers are not required to enforce that senders
6449         // respect the fee_spike_reserve.
6450         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6451         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6452
6453         assert!(nodes[1].node.list_channels().is_empty());
6454         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6455         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6456         check_added_monitors!(nodes[1], 1);
6457         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6458 }
6459
6460 #[test]
6461 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6462         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6463         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6464         let chanmon_cfgs = create_chanmon_cfgs(2);
6465         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6466         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6467         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6468         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6469
6470         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6471         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6472         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6473         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6474         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6475         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6476
6477         let mut msg = msgs::UpdateAddHTLC {
6478                 channel_id: chan.2,
6479                 htlc_id: 0,
6480                 amount_msat: 1000,
6481                 payment_hash: our_payment_hash,
6482                 cltv_expiry: htlc_cltv,
6483                 onion_routing_packet: onion_packet.clone(),
6484         };
6485
6486         for i in 0..super::channel::OUR_MAX_HTLCS {
6487                 msg.htlc_id = i as u64;
6488                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6489         }
6490         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6491         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6492
6493         assert!(nodes[1].node.list_channels().is_empty());
6494         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6495         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6496         check_added_monitors!(nodes[1], 1);
6497         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6498 }
6499
6500 #[test]
6501 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6502         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6503         let chanmon_cfgs = create_chanmon_cfgs(2);
6504         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6505         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6506         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6507         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6508
6509         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6510         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6511         check_added_monitors!(nodes[0], 1);
6512         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6513         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6514         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6515
6516         assert!(nodes[1].node.list_channels().is_empty());
6517         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6518         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6519         check_added_monitors!(nodes[1], 1);
6520         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6521 }
6522
6523 #[test]
6524 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6525         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6526         let chanmon_cfgs = create_chanmon_cfgs(2);
6527         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6528         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6529         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6530
6531         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6532         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6533         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6534         check_added_monitors!(nodes[0], 1);
6535         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6536         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6537         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6538
6539         assert!(nodes[1].node.list_channels().is_empty());
6540         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6541         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6542         check_added_monitors!(nodes[1], 1);
6543         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6544 }
6545
6546 #[test]
6547 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6548         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6549         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6550         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6551         let chanmon_cfgs = create_chanmon_cfgs(2);
6552         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6553         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6554         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6555
6556         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6557         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6558         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6559         check_added_monitors!(nodes[0], 1);
6560         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6561         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6562
6563         //Disconnect and Reconnect
6564         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6565         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6566         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6567         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6568         assert_eq!(reestablish_1.len(), 1);
6569         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6570         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6571         assert_eq!(reestablish_2.len(), 1);
6572         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6573         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6574         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6575         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6576
6577         //Resend HTLC
6578         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6579         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6580         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6581         check_added_monitors!(nodes[1], 1);
6582         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6583
6584         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6585
6586         assert!(nodes[1].node.list_channels().is_empty());
6587         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6588         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6589         check_added_monitors!(nodes[1], 1);
6590         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6591 }
6592
6593 #[test]
6594 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6595         //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.
6596
6597         let chanmon_cfgs = create_chanmon_cfgs(2);
6598         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6599         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6600         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6601         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6602         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6603         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6604
6605         check_added_monitors!(nodes[0], 1);
6606         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6607         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6608
6609         let update_msg = msgs::UpdateFulfillHTLC{
6610                 channel_id: chan.2,
6611                 htlc_id: 0,
6612                 payment_preimage: our_payment_preimage,
6613         };
6614
6615         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6616
6617         assert!(nodes[0].node.list_channels().is_empty());
6618         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6619         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()));
6620         check_added_monitors!(nodes[0], 1);
6621         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6622 }
6623
6624 #[test]
6625 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6626         //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.
6627
6628         let chanmon_cfgs = create_chanmon_cfgs(2);
6629         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6630         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6631         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6632         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6633
6634         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6635         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6636         check_added_monitors!(nodes[0], 1);
6637         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6638         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6639
6640         let update_msg = msgs::UpdateFailHTLC{
6641                 channel_id: chan.2,
6642                 htlc_id: 0,
6643                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6644         };
6645
6646         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6647
6648         assert!(nodes[0].node.list_channels().is_empty());
6649         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6650         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()));
6651         check_added_monitors!(nodes[0], 1);
6652         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6653 }
6654
6655 #[test]
6656 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6657         //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.
6658
6659         let chanmon_cfgs = create_chanmon_cfgs(2);
6660         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6661         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6662         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6663         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6664
6665         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6666         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6667         check_added_monitors!(nodes[0], 1);
6668         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6669         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6670         let update_msg = msgs::UpdateFailMalformedHTLC{
6671                 channel_id: chan.2,
6672                 htlc_id: 0,
6673                 sha256_of_onion: [1; 32],
6674                 failure_code: 0x8000,
6675         };
6676
6677         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6678
6679         assert!(nodes[0].node.list_channels().is_empty());
6680         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6681         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()));
6682         check_added_monitors!(nodes[0], 1);
6683         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6684 }
6685
6686 #[test]
6687 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6688         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6689
6690         let chanmon_cfgs = create_chanmon_cfgs(2);
6691         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6692         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6693         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6694         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6695
6696         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6697
6698         nodes[1].node.claim_funds(our_payment_preimage);
6699         check_added_monitors!(nodes[1], 1);
6700
6701         let events = nodes[1].node.get_and_clear_pending_msg_events();
6702         assert_eq!(events.len(), 1);
6703         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6704                 match events[0] {
6705                         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, .. } } => {
6706                                 assert!(update_add_htlcs.is_empty());
6707                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6708                                 assert!(update_fail_htlcs.is_empty());
6709                                 assert!(update_fail_malformed_htlcs.is_empty());
6710                                 assert!(update_fee.is_none());
6711                                 update_fulfill_htlcs[0].clone()
6712                         },
6713                         _ => panic!("Unexpected event"),
6714                 }
6715         };
6716
6717         update_fulfill_msg.htlc_id = 1;
6718
6719         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6720
6721         assert!(nodes[0].node.list_channels().is_empty());
6722         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6723         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6724         check_added_monitors!(nodes[0], 1);
6725         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6726 }
6727
6728 #[test]
6729 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6730         //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.
6731
6732         let chanmon_cfgs = create_chanmon_cfgs(2);
6733         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6734         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6735         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6736         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6737
6738         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6739
6740         nodes[1].node.claim_funds(our_payment_preimage);
6741         check_added_monitors!(nodes[1], 1);
6742
6743         let events = nodes[1].node.get_and_clear_pending_msg_events();
6744         assert_eq!(events.len(), 1);
6745         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6746                 match events[0] {
6747                         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, .. } } => {
6748                                 assert!(update_add_htlcs.is_empty());
6749                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6750                                 assert!(update_fail_htlcs.is_empty());
6751                                 assert!(update_fail_malformed_htlcs.is_empty());
6752                                 assert!(update_fee.is_none());
6753                                 update_fulfill_htlcs[0].clone()
6754                         },
6755                         _ => panic!("Unexpected event"),
6756                 }
6757         };
6758
6759         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6760
6761         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6762
6763         assert!(nodes[0].node.list_channels().is_empty());
6764         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6765         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6766         check_added_monitors!(nodes[0], 1);
6767         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6768 }
6769
6770 #[test]
6771 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6772         //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.
6773
6774         let chanmon_cfgs = create_chanmon_cfgs(2);
6775         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6776         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6777         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6778         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6779
6780         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6781         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6782         check_added_monitors!(nodes[0], 1);
6783
6784         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6785         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6786
6787         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6788         check_added_monitors!(nodes[1], 0);
6789         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6790
6791         let events = nodes[1].node.get_and_clear_pending_msg_events();
6792
6793         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6794                 match events[0] {
6795                         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, .. } } => {
6796                                 assert!(update_add_htlcs.is_empty());
6797                                 assert!(update_fulfill_htlcs.is_empty());
6798                                 assert!(update_fail_htlcs.is_empty());
6799                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6800                                 assert!(update_fee.is_none());
6801                                 update_fail_malformed_htlcs[0].clone()
6802                         },
6803                         _ => panic!("Unexpected event"),
6804                 }
6805         };
6806         update_msg.failure_code &= !0x8000;
6807         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6808
6809         assert!(nodes[0].node.list_channels().is_empty());
6810         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6811         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6812         check_added_monitors!(nodes[0], 1);
6813         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6814 }
6815
6816 #[test]
6817 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6818         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6819         //    * 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.
6820
6821         let chanmon_cfgs = create_chanmon_cfgs(3);
6822         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6823         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6824         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6825         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6826         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6827
6828         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6829
6830         //First hop
6831         let mut payment_event = {
6832                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6833                 check_added_monitors!(nodes[0], 1);
6834                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6835                 assert_eq!(events.len(), 1);
6836                 SendEvent::from_event(events.remove(0))
6837         };
6838         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6839         check_added_monitors!(nodes[1], 0);
6840         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6841         expect_pending_htlcs_forwardable!(nodes[1]);
6842         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6843         assert_eq!(events_2.len(), 1);
6844         check_added_monitors!(nodes[1], 1);
6845         payment_event = SendEvent::from_event(events_2.remove(0));
6846         assert_eq!(payment_event.msgs.len(), 1);
6847
6848         //Second Hop
6849         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6850         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6851         check_added_monitors!(nodes[2], 0);
6852         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6853
6854         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6855         assert_eq!(events_3.len(), 1);
6856         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6857                 match events_3[0] {
6858                         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 } } => {
6859                                 assert!(update_add_htlcs.is_empty());
6860                                 assert!(update_fulfill_htlcs.is_empty());
6861                                 assert!(update_fail_htlcs.is_empty());
6862                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6863                                 assert!(update_fee.is_none());
6864                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6865                         },
6866                         _ => panic!("Unexpected event"),
6867                 }
6868         };
6869
6870         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6871
6872         check_added_monitors!(nodes[1], 0);
6873         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6874         expect_pending_htlcs_forwardable!(nodes[1]);
6875         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6876         assert_eq!(events_4.len(), 1);
6877
6878         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6879         match events_4[0] {
6880                 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, .. } } => {
6881                         assert!(update_add_htlcs.is_empty());
6882                         assert!(update_fulfill_htlcs.is_empty());
6883                         assert_eq!(update_fail_htlcs.len(), 1);
6884                         assert!(update_fail_malformed_htlcs.is_empty());
6885                         assert!(update_fee.is_none());
6886                 },
6887                 _ => panic!("Unexpected event"),
6888         };
6889
6890         check_added_monitors!(nodes[1], 1);
6891 }
6892
6893 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6894         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6895         // 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
6896         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6897
6898         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6899         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6900         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6901         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6902         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6903         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6904
6905         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6906
6907         // We route 2 dust-HTLCs between A and B
6908         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6909         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6910         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6911
6912         // Cache one local commitment tx as previous
6913         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6914
6915         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6916         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
6917         check_added_monitors!(nodes[1], 0);
6918         expect_pending_htlcs_forwardable!(nodes[1]);
6919         check_added_monitors!(nodes[1], 1);
6920
6921         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6922         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6923         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6924         check_added_monitors!(nodes[0], 1);
6925
6926         // Cache one local commitment tx as lastest
6927         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6928
6929         let events = nodes[0].node.get_and_clear_pending_msg_events();
6930         match events[0] {
6931                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6932                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6933                 },
6934                 _ => panic!("Unexpected event"),
6935         }
6936         match events[1] {
6937                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6938                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6939                 },
6940                 _ => panic!("Unexpected event"),
6941         }
6942
6943         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6944         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6945         if announce_latest {
6946                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6947         } else {
6948                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6949         }
6950
6951         check_closed_broadcast!(nodes[0], true);
6952         check_added_monitors!(nodes[0], 1);
6953         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6954
6955         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6956         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6957         let events = nodes[0].node.get_and_clear_pending_events();
6958         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6959         assert_eq!(events.len(), 2);
6960         let mut first_failed = false;
6961         for event in events {
6962                 match event {
6963                         Event::PaymentPathFailed { payment_hash, .. } => {
6964                                 if payment_hash == payment_hash_1 {
6965                                         assert!(!first_failed);
6966                                         first_failed = true;
6967                                 } else {
6968                                         assert_eq!(payment_hash, payment_hash_2);
6969                                 }
6970                         }
6971                         _ => panic!("Unexpected event"),
6972                 }
6973         }
6974 }
6975
6976 #[test]
6977 fn test_failure_delay_dust_htlc_local_commitment() {
6978         do_test_failure_delay_dust_htlc_local_commitment(true);
6979         do_test_failure_delay_dust_htlc_local_commitment(false);
6980 }
6981
6982 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6983         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6984         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6985         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6986         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6987         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6988         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6989
6990         let chanmon_cfgs = create_chanmon_cfgs(3);
6991         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6992         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6993         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6994         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6995
6996         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6997
6998         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6999         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7000
7001         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7002         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7003
7004         // We revoked bs_commitment_tx
7005         if revoked {
7006                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7007                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7008         }
7009
7010         let mut timeout_tx = Vec::new();
7011         if local {
7012                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7013                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7014                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7015                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7016                 expect_payment_failed!(nodes[0], dust_hash, true);
7017
7018                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7019                 check_closed_broadcast!(nodes[0], true);
7020                 check_added_monitors!(nodes[0], 1);
7021                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7022                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7023                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7024                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7025                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7026                 mine_transaction(&nodes[0], &timeout_tx[0]);
7027                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7028                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7029         } else {
7030                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7031                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7032                 check_closed_broadcast!(nodes[0], true);
7033                 check_added_monitors!(nodes[0], 1);
7034                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7035                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7036                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7037                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7038                 if !revoked {
7039                         expect_payment_failed!(nodes[0], dust_hash, true);
7040                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7041                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7042                         mine_transaction(&nodes[0], &timeout_tx[0]);
7043                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7044                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7045                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7046                 } else {
7047                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7048                         // commitment tx
7049                         let events = nodes[0].node.get_and_clear_pending_events();
7050                         assert_eq!(events.len(), 2);
7051                         let first;
7052                         match events[0] {
7053                                 Event::PaymentPathFailed { payment_hash, .. } => {
7054                                         if payment_hash == dust_hash { first = true; }
7055                                         else { first = false; }
7056                                 },
7057                                 _ => panic!("Unexpected event"),
7058                         }
7059                         match events[1] {
7060                                 Event::PaymentPathFailed { payment_hash, .. } => {
7061                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7062                                         else { assert_eq!(payment_hash, dust_hash); }
7063                                 },
7064                                 _ => panic!("Unexpected event"),
7065                         }
7066                 }
7067         }
7068 }
7069
7070 #[test]
7071 fn test_sweep_outbound_htlc_failure_update() {
7072         do_test_sweep_outbound_htlc_failure_update(false, true);
7073         do_test_sweep_outbound_htlc_failure_update(false, false);
7074         do_test_sweep_outbound_htlc_failure_update(true, false);
7075 }
7076
7077 #[test]
7078 fn test_user_configurable_csv_delay() {
7079         // We test our channel constructors yield errors when we pass them absurd csv delay
7080
7081         let mut low_our_to_self_config = UserConfig::default();
7082         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7083         let mut high_their_to_self_config = UserConfig::default();
7084         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7085         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7086         let chanmon_cfgs = create_chanmon_cfgs(2);
7087         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7088         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7089         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7090
7091         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7092         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) {
7093                 match error {
7094                         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())); },
7095                         _ => panic!("Unexpected event"),
7096                 }
7097         } else { assert!(false) }
7098
7099         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7100         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7101         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7102         open_channel.to_self_delay = 200;
7103         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) {
7104                 match error {
7105                         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()));  },
7106                         _ => panic!("Unexpected event"),
7107                 }
7108         } else { assert!(false); }
7109
7110         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7111         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7112         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()));
7113         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7114         accept_channel.to_self_delay = 200;
7115         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7116         let reason_msg;
7117         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7118                 match action {
7119                         &ErrorAction::SendErrorMessage { ref msg } => {
7120                                 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()));
7121                                 reason_msg = msg.data.clone();
7122                         },
7123                         _ => { panic!(); }
7124                 }
7125         } else { panic!(); }
7126         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7127
7128         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7129         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7130         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7131         open_channel.to_self_delay = 200;
7132         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) {
7133                 match error {
7134                         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())); },
7135                         _ => panic!("Unexpected event"),
7136                 }
7137         } else { assert!(false); }
7138 }
7139
7140 #[test]
7141 fn test_data_loss_protect() {
7142         // We want to be sure that :
7143         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7144         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7145         // * we close channel in case of detecting other being fallen behind
7146         // * we are able to claim our own outputs thanks to to_remote being static
7147         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7148         let persister;
7149         let logger;
7150         let fee_estimator;
7151         let tx_broadcaster;
7152         let chain_source;
7153         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7154         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7155         // during signing due to revoked tx
7156         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7157         let keys_manager = &chanmon_cfgs[0].keys_manager;
7158         let monitor;
7159         let node_state_0;
7160         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7161         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7162         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7163
7164         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7165
7166         // Cache node A state before any channel update
7167         let previous_node_state = nodes[0].node.encode();
7168         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7169         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7170
7171         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7172         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7173
7174         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7175         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7176
7177         // Restore node A from previous state
7178         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7179         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7180         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7181         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7182         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7183         persister = test_utils::TestPersister::new();
7184         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7185         node_state_0 = {
7186                 let mut channel_monitors = HashMap::new();
7187                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7188                 <(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 {
7189                         keys_manager: keys_manager,
7190                         fee_estimator: &fee_estimator,
7191                         chain_monitor: &monitor,
7192                         logger: &logger,
7193                         tx_broadcaster: &tx_broadcaster,
7194                         default_config: UserConfig::default(),
7195                         channel_monitors,
7196                 }).unwrap().1
7197         };
7198         nodes[0].node = &node_state_0;
7199         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7200         nodes[0].chain_monitor = &monitor;
7201         nodes[0].chain_source = &chain_source;
7202
7203         check_added_monitors!(nodes[0], 1);
7204
7205         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7206         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7207
7208         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7209
7210         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7211         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7212         check_added_monitors!(nodes[0], 1);
7213
7214         {
7215                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7216                 assert_eq!(node_txn.len(), 0);
7217         }
7218
7219         let mut reestablish_1 = Vec::with_capacity(1);
7220         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7221                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7222                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7223                         reestablish_1.push(msg.clone());
7224                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7225                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7226                         match action {
7227                                 &ErrorAction::SendErrorMessage { ref msg } => {
7228                                         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");
7229                                 },
7230                                 _ => panic!("Unexpected event!"),
7231                         }
7232                 } else {
7233                         panic!("Unexpected event")
7234                 }
7235         }
7236
7237         // Check we close channel detecting A is fallen-behind
7238         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7239         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7240         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7241         check_added_monitors!(nodes[1], 1);
7242
7243         // Check A is able to claim to_remote output
7244         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7245         assert_eq!(node_txn.len(), 1);
7246         check_spends!(node_txn[0], chan.3);
7247         assert_eq!(node_txn[0].output.len(), 2);
7248         mine_transaction(&nodes[0], &node_txn[0]);
7249         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7250         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() });
7251         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7252         assert_eq!(spend_txn.len(), 1);
7253         check_spends!(spend_txn[0], node_txn[0]);
7254 }
7255
7256 #[test]
7257 fn test_check_htlc_underpaying() {
7258         // Send payment through A -> B but A is maliciously
7259         // sending a probe payment (i.e less than expected value0
7260         // to B, B should refuse payment.
7261
7262         let chanmon_cfgs = create_chanmon_cfgs(2);
7263         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7264         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7265         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7266
7267         // Create some initial channels
7268         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7269
7270         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).unwrap();
7271         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7272         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, 0).unwrap();
7273         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7274         check_added_monitors!(nodes[0], 1);
7275
7276         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7277         assert_eq!(events.len(), 1);
7278         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7279         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7280         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7281
7282         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7283         // and then will wait a second random delay before failing the HTLC back:
7284         expect_pending_htlcs_forwardable!(nodes[1]);
7285         expect_pending_htlcs_forwardable!(nodes[1]);
7286
7287         // Node 3 is expecting payment of 100_000 but received 10_000,
7288         // it should fail htlc like we didn't know the preimage.
7289         nodes[1].node.process_pending_htlc_forwards();
7290
7291         let events = nodes[1].node.get_and_clear_pending_msg_events();
7292         assert_eq!(events.len(), 1);
7293         let (update_fail_htlc, commitment_signed) = match events[0] {
7294                 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 } } => {
7295                         assert!(update_add_htlcs.is_empty());
7296                         assert!(update_fulfill_htlcs.is_empty());
7297                         assert_eq!(update_fail_htlcs.len(), 1);
7298                         assert!(update_fail_malformed_htlcs.is_empty());
7299                         assert!(update_fee.is_none());
7300                         (update_fail_htlcs[0].clone(), commitment_signed)
7301                 },
7302                 _ => panic!("Unexpected event"),
7303         };
7304         check_added_monitors!(nodes[1], 1);
7305
7306         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7307         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7308
7309         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7310         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7311         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7312         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7313 }
7314
7315 #[test]
7316 fn test_announce_disable_channels() {
7317         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7318         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7319
7320         let chanmon_cfgs = create_chanmon_cfgs(2);
7321         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7322         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7323         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7324
7325         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7326         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7327         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7328
7329         // Disconnect peers
7330         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7331         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7332
7333         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7334         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7335         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7336         assert_eq!(msg_events.len(), 3);
7337         let mut chans_disabled: HashSet<u64> = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7338         for e in msg_events {
7339                 match e {
7340                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7341                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7342                                 // Check that each channel gets updated exactly once
7343                                 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7344                                         panic!("Generated ChannelUpdate for wrong chan!");
7345                                 }
7346                         },
7347                         _ => panic!("Unexpected event"),
7348                 }
7349         }
7350         // Reconnect peers
7351         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7352         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7353         assert_eq!(reestablish_1.len(), 3);
7354         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7355         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7356         assert_eq!(reestablish_2.len(), 3);
7357
7358         // Reestablish chan_1
7359         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7360         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7361         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7362         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7363         // Reestablish chan_2
7364         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7365         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7366         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7367         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7368         // Reestablish chan_3
7369         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7370         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7371         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7372         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7373
7374         nodes[0].node.timer_tick_occurred();
7375         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7376         nodes[0].node.timer_tick_occurred();
7377         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7378         assert_eq!(msg_events.len(), 3);
7379         chans_disabled = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7380         for e in msg_events {
7381                 match e {
7382                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7383                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7384                                 // Check that each channel gets updated exactly once
7385                                 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7386                                         panic!("Generated ChannelUpdate for wrong chan!");
7387                                 }
7388                         },
7389                         _ => panic!("Unexpected event"),
7390                 }
7391         }
7392 }
7393
7394 #[test]
7395 fn test_priv_forwarding_rejection() {
7396         // If we have a private channel with outbound liquidity, and
7397         // UserConfig::accept_forwards_to_priv_channels is set to false, we should reject any attempts
7398         // to forward through that channel.
7399         let chanmon_cfgs = create_chanmon_cfgs(3);
7400         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7401         let mut no_announce_cfg = test_default_channel_config();
7402         no_announce_cfg.channel_options.announced_channel = false;
7403         no_announce_cfg.accept_forwards_to_priv_channels = false;
7404         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]);
7405         let persister: test_utils::TestPersister;
7406         let new_chain_monitor: test_utils::TestChainMonitor;
7407         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
7408         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7409
7410         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;
7411
7412         // Note that the create_*_chan functions in utils requires announcement_signatures, which we do
7413         // not send for private channels.
7414         nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
7415         let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[2].node.get_our_node_id());
7416         nodes[2].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
7417         let accept_channel = get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
7418         nodes[1].node.handle_accept_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7419
7420         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[1], 1_000_000, 42);
7421         nodes[1].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
7422         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()));
7423         check_added_monitors!(nodes[2], 1);
7424
7425         let cs_funding_signed = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[1].node.get_our_node_id());
7426         nodes[1].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &cs_funding_signed);
7427         check_added_monitors!(nodes[1], 1);
7428
7429         let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[2].best_block_info().1 + 1);
7430         confirm_transaction_at(&nodes[1], &tx, conf_height);
7431         connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
7432         confirm_transaction_at(&nodes[2], &tx, conf_height);
7433         connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
7434         let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[2].node.get_our_node_id());
7435         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()));
7436         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7437         nodes[2].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
7438         get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7439
7440         assert!(nodes[0].node.list_usable_channels()[0].is_public);
7441         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
7442         assert!(!nodes[2].node.list_usable_channels()[0].is_public);
7443
7444         // We should always be able to forward through nodes[1] as long as its out through a public
7445         // channel:
7446         send_payment(&nodes[2], &[&nodes[1], &nodes[0]], 10_000);
7447
7448         // ... however, if we send to nodes[2], we will have to pass the private channel from nodes[1]
7449         // to nodes[2], which should be rejected:
7450         let route_hint = RouteHint(vec![RouteHintHop {
7451                 src_node_id: nodes[1].node.get_our_node_id(),
7452                 short_channel_id: nodes[2].node.list_channels()[0].short_channel_id.unwrap(),
7453                 fees: RoutingFees { base_msat: 1000, proportional_millionths: 0 },
7454                 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
7455                 htlc_minimum_msat: None,
7456                 htlc_maximum_msat: None,
7457         }]);
7458         let last_hops = vec![&route_hint];
7459         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);
7460
7461         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7462         check_added_monitors!(nodes[0], 1);
7463         let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7464         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7465         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
7466
7467         let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7468         assert!(htlc_fail_updates.update_add_htlcs.is_empty());
7469         assert_eq!(htlc_fail_updates.update_fail_htlcs.len(), 1);
7470         assert!(htlc_fail_updates.update_fail_malformed_htlcs.is_empty());
7471         assert!(htlc_fail_updates.update_fee.is_none());
7472
7473         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
7474         commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, true, true);
7475         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, nodes[2].node.list_channels()[0].short_channel_id.unwrap(), true);
7476
7477         // Now disconnect nodes[1] from its peers and restart with accept_forwards_to_priv_channels set
7478         // to true. Sadly there is currently no way to change it at runtime.
7479
7480         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7481         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7482
7483         let nodes_1_serialized = nodes[1].node.encode();
7484         let mut monitor_a_serialized = test_utils::TestVecWriter(Vec::new());
7485         let mut monitor_b_serialized = test_utils::TestVecWriter(Vec::new());
7486         get_monitor!(nodes[1], chan_id_1).write(&mut monitor_a_serialized).unwrap();
7487         get_monitor!(nodes[1], cs_funding_signed.channel_id).write(&mut monitor_b_serialized).unwrap();
7488
7489         persister = test_utils::TestPersister::new();
7490         let keys_manager = &chanmon_cfgs[1].keys_manager;
7491         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);
7492         nodes[1].chain_monitor = &new_chain_monitor;
7493
7494         let mut monitor_a_read = &monitor_a_serialized.0[..];
7495         let mut monitor_b_read = &monitor_b_serialized.0[..];
7496         let (_, mut monitor_a) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_a_read, keys_manager).unwrap();
7497         let (_, mut monitor_b) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_b_read, keys_manager).unwrap();
7498         assert!(monitor_a_read.is_empty());
7499         assert!(monitor_b_read.is_empty());
7500
7501         no_announce_cfg.accept_forwards_to_priv_channels = true;
7502
7503         let mut nodes_1_read = &nodes_1_serialized[..];
7504         let (_, nodes_1_deserialized_tmp) = {
7505                 let mut channel_monitors = HashMap::new();
7506                 channel_monitors.insert(monitor_a.get_funding_txo().0, &mut monitor_a);
7507                 channel_monitors.insert(monitor_b.get_funding_txo().0, &mut monitor_b);
7508                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
7509                         default_config: no_announce_cfg,
7510                         keys_manager,
7511                         fee_estimator: node_cfgs[1].fee_estimator,
7512                         chain_monitor: nodes[1].chain_monitor,
7513                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
7514                         logger: nodes[1].logger,
7515                         channel_monitors,
7516                 }).unwrap()
7517         };
7518         assert!(nodes_1_read.is_empty());
7519         nodes_1_deserialized = nodes_1_deserialized_tmp;
7520
7521         assert!(nodes[1].chain_monitor.watch_channel(monitor_a.get_funding_txo().0, monitor_a).is_ok());
7522         assert!(nodes[1].chain_monitor.watch_channel(monitor_b.get_funding_txo().0, monitor_b).is_ok());
7523         check_added_monitors!(nodes[1], 2);
7524         nodes[1].node = &nodes_1_deserialized;
7525
7526         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7527         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7528         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7529         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
7530         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
7531         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7532         get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7533         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
7534
7535         nodes[1].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7536         nodes[2].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7537         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[2].node.get_our_node_id());
7538         let cs_reestablish = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7539         nodes[2].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7540         nodes[1].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &cs_reestablish);
7541         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7542         get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7543
7544         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7545         check_added_monitors!(nodes[0], 1);
7546         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 10_000, our_payment_hash, our_payment_secret);
7547         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage);
7548 }
7549
7550 #[test]
7551 fn test_bump_penalty_txn_on_revoked_commitment() {
7552         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7553         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7554
7555         let chanmon_cfgs = create_chanmon_cfgs(2);
7556         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7557         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7558         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7559
7560         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7561
7562         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7563         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], vec![], 3000000, 30);
7564         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7565
7566         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7567         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7568         assert_eq!(revoked_txn[0].output.len(), 4);
7569         assert_eq!(revoked_txn[0].input.len(), 1);
7570         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7571         let revoked_txid = revoked_txn[0].txid();
7572
7573         let mut penalty_sum = 0;
7574         for outp in revoked_txn[0].output.iter() {
7575                 if outp.script_pubkey.is_v0_p2wsh() {
7576                         penalty_sum += outp.value;
7577                 }
7578         }
7579
7580         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7581         let header_114 = connect_blocks(&nodes[1], 14);
7582
7583         // Actually revoke tx by claiming a HTLC
7584         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7585         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7586         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7587         check_added_monitors!(nodes[1], 1);
7588
7589         // One or more justice tx should have been broadcast, check it
7590         let penalty_1;
7591         let feerate_1;
7592         {
7593                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7594                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7595                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7596                 assert_eq!(node_txn[0].output.len(), 1);
7597                 check_spends!(node_txn[0], revoked_txn[0]);
7598                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7599                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7600                 penalty_1 = node_txn[0].txid();
7601                 node_txn.clear();
7602         };
7603
7604         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7605         connect_blocks(&nodes[1], 15);
7606         let mut penalty_2 = penalty_1;
7607         let mut feerate_2 = 0;
7608         {
7609                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7610                 assert_eq!(node_txn.len(), 1);
7611                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7612                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7613                         assert_eq!(node_txn[0].output.len(), 1);
7614                         check_spends!(node_txn[0], revoked_txn[0]);
7615                         penalty_2 = node_txn[0].txid();
7616                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7617                         assert_ne!(penalty_2, penalty_1);
7618                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7619                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7620                         // Verify 25% bump heuristic
7621                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7622                         node_txn.clear();
7623                 }
7624         }
7625         assert_ne!(feerate_2, 0);
7626
7627         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7628         connect_blocks(&nodes[1], 1);
7629         let penalty_3;
7630         let mut feerate_3 = 0;
7631         {
7632                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7633                 assert_eq!(node_txn.len(), 1);
7634                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7635                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7636                         assert_eq!(node_txn[0].output.len(), 1);
7637                         check_spends!(node_txn[0], revoked_txn[0]);
7638                         penalty_3 = node_txn[0].txid();
7639                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7640                         assert_ne!(penalty_3, penalty_2);
7641                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7642                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7643                         // Verify 25% bump heuristic
7644                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7645                         node_txn.clear();
7646                 }
7647         }
7648         assert_ne!(feerate_3, 0);
7649
7650         nodes[1].node.get_and_clear_pending_events();
7651         nodes[1].node.get_and_clear_pending_msg_events();
7652 }
7653
7654 #[test]
7655 fn test_bump_penalty_txn_on_revoked_htlcs() {
7656         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7657         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7658
7659         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7660         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7661         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7662         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7663         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7664
7665         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7666         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7667         let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph,
7668                 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
7669         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7670         let route = get_route(&nodes[1].node.get_our_node_id(), &nodes[1].net_graph_msg_handler.network_graph,
7671                 &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
7672         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7673
7674         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7675         assert_eq!(revoked_local_txn[0].input.len(), 1);
7676         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7677
7678         // Revoke local commitment tx
7679         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7680
7681         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7682         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7683         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7684         check_closed_broadcast!(nodes[1], true);
7685         check_added_monitors!(nodes[1], 1);
7686         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7687         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7688
7689         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7690         assert_eq!(revoked_htlc_txn.len(), 3);
7691         check_spends!(revoked_htlc_txn[1], chan.3);
7692
7693         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7694         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7695         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7696
7697         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7698         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7699         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7700         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7701
7702         // Broadcast set of revoked txn on A
7703         let hash_128 = connect_blocks(&nodes[0], 40);
7704         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7705         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7706         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7707         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7708         let events = nodes[0].node.get_and_clear_pending_events();
7709         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7710         match events[1] {
7711                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7712                 _ => panic!("Unexpected event"),
7713         }
7714         let first;
7715         let feerate_1;
7716         let penalty_txn;
7717         {
7718                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7719                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7720                 // Verify claim tx are spending revoked HTLC txn
7721
7722                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7723                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7724                 // which are included in the same block (they are broadcasted because we scan the
7725                 // transactions linearly and generate claims as we go, they likely should be removed in the
7726                 // future).
7727                 assert_eq!(node_txn[0].input.len(), 1);
7728                 check_spends!(node_txn[0], revoked_local_txn[0]);
7729                 assert_eq!(node_txn[1].input.len(), 1);
7730                 check_spends!(node_txn[1], revoked_local_txn[0]);
7731                 assert_eq!(node_txn[2].input.len(), 1);
7732                 check_spends!(node_txn[2], revoked_local_txn[0]);
7733
7734                 // Each of the three justice transactions claim a separate (single) output of the three
7735                 // available, which we check here:
7736                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7737                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7738                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7739
7740                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7741                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7742
7743                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7744                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7745                 // a remote commitment tx has already been confirmed).
7746                 check_spends!(node_txn[3], chan.3);
7747
7748                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7749                 // output, checked above).
7750                 assert_eq!(node_txn[4].input.len(), 2);
7751                 assert_eq!(node_txn[4].output.len(), 1);
7752                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7753
7754                 first = node_txn[4].txid();
7755                 // Store both feerates for later comparison
7756                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7757                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7758                 penalty_txn = vec![node_txn[2].clone()];
7759                 node_txn.clear();
7760         }
7761
7762         // Connect one more block to see if bumped penalty are issued for HTLC txn
7763         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7764         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7765         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7766         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7767         {
7768                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7769                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7770
7771                 check_spends!(node_txn[0], revoked_local_txn[0]);
7772                 check_spends!(node_txn[1], revoked_local_txn[0]);
7773                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7774                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7775                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7776                 } else {
7777                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7778                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7779                 }
7780
7781                 node_txn.clear();
7782         };
7783
7784         // Few more blocks to confirm penalty txn
7785         connect_blocks(&nodes[0], 4);
7786         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7787         let header_144 = connect_blocks(&nodes[0], 9);
7788         let node_txn = {
7789                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7790                 assert_eq!(node_txn.len(), 1);
7791
7792                 assert_eq!(node_txn[0].input.len(), 2);
7793                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7794                 // Verify bumped tx is different and 25% bump heuristic
7795                 assert_ne!(first, node_txn[0].txid());
7796                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7797                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7798                 assert!(feerate_2 * 100 > feerate_1 * 125);
7799                 let txn = vec![node_txn[0].clone()];
7800                 node_txn.clear();
7801                 txn
7802         };
7803         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7804         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7805         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7806         connect_blocks(&nodes[0], 20);
7807         {
7808                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7809                 // We verify than no new transaction has been broadcast because previously
7810                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7811                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7812                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7813                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7814                 // up bumped justice generation.
7815                 assert_eq!(node_txn.len(), 0);
7816                 node_txn.clear();
7817         }
7818         check_closed_broadcast!(nodes[0], true);
7819         check_added_monitors!(nodes[0], 1);
7820 }
7821
7822 #[test]
7823 fn test_bump_penalty_txn_on_remote_commitment() {
7824         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7825         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7826
7827         // Create 2 HTLCs
7828         // Provide preimage for one
7829         // Check aggregation
7830
7831         let chanmon_cfgs = create_chanmon_cfgs(2);
7832         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7833         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7834         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7835
7836         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7837         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7838         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7839
7840         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7841         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7842         assert_eq!(remote_txn[0].output.len(), 4);
7843         assert_eq!(remote_txn[0].input.len(), 1);
7844         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7845
7846         // Claim a HTLC without revocation (provide B monitor with preimage)
7847         nodes[1].node.claim_funds(payment_preimage);
7848         mine_transaction(&nodes[1], &remote_txn[0]);
7849         check_added_monitors!(nodes[1], 2);
7850         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7851
7852         // One or more claim tx should have been broadcast, check it
7853         let timeout;
7854         let preimage;
7855         let preimage_bump;
7856         let feerate_timeout;
7857         let feerate_preimage;
7858         {
7859                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7860                 // 9 transactions including:
7861                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7862                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7863                 // 2 * HTLC-Success (one RBF bump we'll check later)
7864                 // 1 * HTLC-Timeout
7865                 assert_eq!(node_txn.len(), 8);
7866                 assert_eq!(node_txn[0].input.len(), 1);
7867                 assert_eq!(node_txn[6].input.len(), 1);
7868                 check_spends!(node_txn[0], remote_txn[0]);
7869                 check_spends!(node_txn[6], remote_txn[0]);
7870                 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7871                 preimage_bump = node_txn[3].clone();
7872
7873                 check_spends!(node_txn[1], chan.3);
7874                 check_spends!(node_txn[2], node_txn[1]);
7875                 assert_eq!(node_txn[1], node_txn[4]);
7876                 assert_eq!(node_txn[2], node_txn[5]);
7877
7878                 timeout = node_txn[6].txid();
7879                 let index = node_txn[6].input[0].previous_output.vout;
7880                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
7881                 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
7882
7883                 preimage = node_txn[0].txid();
7884                 let index = node_txn[0].input[0].previous_output.vout;
7885                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7886                 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7887
7888                 node_txn.clear();
7889         };
7890         assert_ne!(feerate_timeout, 0);
7891         assert_ne!(feerate_preimage, 0);
7892
7893         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7894         connect_blocks(&nodes[1], 15);
7895         {
7896                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7897                 assert_eq!(node_txn.len(), 1);
7898                 assert_eq!(node_txn[0].input.len(), 1);
7899                 assert_eq!(preimage_bump.input.len(), 1);
7900                 check_spends!(node_txn[0], remote_txn[0]);
7901                 check_spends!(preimage_bump, remote_txn[0]);
7902
7903                 let index = preimage_bump.input[0].previous_output.vout;
7904                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7905                 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
7906                 assert!(new_feerate * 100 > feerate_timeout * 125);
7907                 assert_ne!(timeout, preimage_bump.txid());
7908
7909                 let index = node_txn[0].input[0].previous_output.vout;
7910                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7911                 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7912                 assert!(new_feerate * 100 > feerate_preimage * 125);
7913                 assert_ne!(preimage, node_txn[0].txid());
7914
7915                 node_txn.clear();
7916         }
7917
7918         nodes[1].node.get_and_clear_pending_events();
7919         nodes[1].node.get_and_clear_pending_msg_events();
7920 }
7921
7922 #[test]
7923 fn test_counterparty_raa_skip_no_crash() {
7924         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7925         // commitment transaction, we would have happily carried on and provided them the next
7926         // commitment transaction based on one RAA forward. This would probably eventually have led to
7927         // channel closure, but it would not have resulted in funds loss. Still, our
7928         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7929         // check simply that the channel is closed in response to such an RAA, but don't check whether
7930         // we decide to punish our counterparty for revoking their funds (as we don't currently
7931         // implement that).
7932         let chanmon_cfgs = create_chanmon_cfgs(2);
7933         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7934         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7935         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7936         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7937
7938         let mut guard = nodes[0].node.channel_state.lock().unwrap();
7939         let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7940
7941         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7942
7943         // Make signer believe we got a counterparty signature, so that it allows the revocation
7944         keys.get_enforcement_state().last_holder_commitment -= 1;
7945         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7946
7947         // Must revoke without gaps
7948         keys.get_enforcement_state().last_holder_commitment -= 1;
7949         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7950
7951         keys.get_enforcement_state().last_holder_commitment -= 1;
7952         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7953                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7954
7955         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7956                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7957         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7958         check_added_monitors!(nodes[1], 1);
7959         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7960 }
7961
7962 #[test]
7963 fn test_bump_txn_sanitize_tracking_maps() {
7964         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7965         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7966
7967         let chanmon_cfgs = create_chanmon_cfgs(2);
7968         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7969         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7970         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7971
7972         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7973         // Lock HTLC in both directions
7974         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7975         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7976
7977         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7978         assert_eq!(revoked_local_txn[0].input.len(), 1);
7979         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7980
7981         // Revoke local commitment tx
7982         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7983
7984         // Broadcast set of revoked txn on A
7985         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7986         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7987         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7988
7989         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7990         check_closed_broadcast!(nodes[0], true);
7991         check_added_monitors!(nodes[0], 1);
7992         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7993         let penalty_txn = {
7994                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7995                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7996                 check_spends!(node_txn[0], revoked_local_txn[0]);
7997                 check_spends!(node_txn[1], revoked_local_txn[0]);
7998                 check_spends!(node_txn[2], revoked_local_txn[0]);
7999                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8000                 node_txn.clear();
8001                 penalty_txn
8002         };
8003         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8004         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8005         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8006         {
8007                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8008                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8009                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8010         }
8011 }
8012
8013 #[test]
8014 fn test_override_channel_config() {
8015         let chanmon_cfgs = create_chanmon_cfgs(2);
8016         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8017         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8018         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8019
8020         // Node0 initiates a channel to node1 using the override config.
8021         let mut override_config = UserConfig::default();
8022         override_config.own_channel_config.our_to_self_delay = 200;
8023
8024         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8025
8026         // Assert the channel created by node0 is using the override config.
8027         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8028         assert_eq!(res.channel_flags, 0);
8029         assert_eq!(res.to_self_delay, 200);
8030 }
8031
8032 #[test]
8033 fn test_override_0msat_htlc_minimum() {
8034         let mut zero_config = UserConfig::default();
8035         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8036         let chanmon_cfgs = create_chanmon_cfgs(2);
8037         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8038         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8039         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8040
8041         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8042         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8043         assert_eq!(res.htlc_minimum_msat, 1);
8044
8045         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8046         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8047         assert_eq!(res.htlc_minimum_msat, 1);
8048 }
8049
8050 #[test]
8051 fn test_simple_mpp() {
8052         // Simple test of sending a multi-path payment.
8053         let chanmon_cfgs = create_chanmon_cfgs(4);
8054         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8055         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8056         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8057
8058         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8059         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8060         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8061         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8062
8063         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8064         let path = route.paths[0].clone();
8065         route.paths.push(path);
8066         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8067         route.paths[0][0].short_channel_id = chan_1_id;
8068         route.paths[0][1].short_channel_id = chan_3_id;
8069         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8070         route.paths[1][0].short_channel_id = chan_2_id;
8071         route.paths[1][1].short_channel_id = chan_4_id;
8072         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8073         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8074 }
8075
8076 #[test]
8077 fn test_preimage_storage() {
8078         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8079         let chanmon_cfgs = create_chanmon_cfgs(2);
8080         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8081         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8082         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8083
8084         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8085
8086         {
8087                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, 42);
8088                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8089                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8090                 check_added_monitors!(nodes[0], 1);
8091                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8092                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8093                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8094                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8095         }
8096         // Note that after leaving the above scope we have no knowledge of any arguments or return
8097         // values from previous calls.
8098         expect_pending_htlcs_forwardable!(nodes[1]);
8099         let events = nodes[1].node.get_and_clear_pending_events();
8100         assert_eq!(events.len(), 1);
8101         match events[0] {
8102                 Event::PaymentReceived { ref purpose, .. } => {
8103                         match &purpose {
8104                                 PaymentPurpose::InvoicePayment { payment_preimage, user_payment_id, .. } => {
8105                                         assert_eq!(*user_payment_id, 42);
8106                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8107                                 },
8108                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8109                         }
8110                 },
8111                 _ => panic!("Unexpected event"),
8112         }
8113 }
8114
8115 #[test]
8116 fn test_secret_timeout() {
8117         // Simple test of payment secret storage time outs
8118         let chanmon_cfgs = create_chanmon_cfgs(2);
8119         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8120         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8121         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8122
8123         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8124
8125         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8126
8127         // We should fail to register the same payment hash twice, at least until we've connected a
8128         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8129         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8130                 assert_eq!(err, "Duplicate payment hash");
8131         } else { panic!(); }
8132         let mut block = {
8133                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8134                 Block {
8135                         header: BlockHeader {
8136                                 version: 0x2000000,
8137                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8138                                 merkle_root: Default::default(),
8139                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8140                         txdata: vec![],
8141                 }
8142         };
8143         connect_block(&nodes[1], &block);
8144         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8145                 assert_eq!(err, "Duplicate payment hash");
8146         } else { panic!(); }
8147
8148         // If we then connect the second block, we should be able to register the same payment hash
8149         // again with a different user_payment_id (this time getting a new payment secret).
8150         block.header.prev_blockhash = block.header.block_hash();
8151         block.header.time += 1;
8152         connect_block(&nodes[1], &block);
8153         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 42).unwrap();
8154         assert_ne!(payment_secret_1, our_payment_secret);
8155
8156         {
8157                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8158                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8159                 check_added_monitors!(nodes[0], 1);
8160                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8161                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8162                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8163                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8164         }
8165         // Note that after leaving the above scope we have no knowledge of any arguments or return
8166         // values from previous calls.
8167         expect_pending_htlcs_forwardable!(nodes[1]);
8168         let events = nodes[1].node.get_and_clear_pending_events();
8169         assert_eq!(events.len(), 1);
8170         match events[0] {
8171                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, user_payment_id }, .. } => {
8172                         assert!(payment_preimage.is_none());
8173                         assert_eq!(user_payment_id, 42);
8174                         assert_eq!(payment_secret, our_payment_secret);
8175                         // We don't actually have the payment preimage with which to claim this payment!
8176                 },
8177                 _ => panic!("Unexpected event"),
8178         }
8179 }
8180
8181 #[test]
8182 fn test_bad_secret_hash() {
8183         // Simple test of unregistered payment hash/invalid payment secret handling
8184         let chanmon_cfgs = create_chanmon_cfgs(2);
8185         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8186         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8187         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8188
8189         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8190
8191         let random_payment_hash = PaymentHash([42; 32]);
8192         let random_payment_secret = PaymentSecret([43; 32]);
8193         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8194         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8195
8196         // All the below cases should end up being handled exactly identically, so we macro the
8197         // resulting events.
8198         macro_rules! handle_unknown_invalid_payment_data {
8199                 () => {
8200                         check_added_monitors!(nodes[0], 1);
8201                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8202                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8203                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8204                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8205
8206                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8207                         // again to process the pending backwards-failure of the HTLC
8208                         expect_pending_htlcs_forwardable!(nodes[1]);
8209                         expect_pending_htlcs_forwardable!(nodes[1]);
8210                         check_added_monitors!(nodes[1], 1);
8211
8212                         // We should fail the payment back
8213                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8214                         match events.pop().unwrap() {
8215                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8216                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8217                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8218                                 },
8219                                 _ => panic!("Unexpected event"),
8220                         }
8221                 }
8222         }
8223
8224         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8225         // Error data is the HTLC value (100,000) and current block height
8226         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8227
8228         // Send a payment with the right payment hash but the wrong payment secret
8229         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8230         handle_unknown_invalid_payment_data!();
8231         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8232
8233         // Send a payment with a random payment hash, but the right payment secret
8234         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8235         handle_unknown_invalid_payment_data!();
8236         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8237
8238         // Send a payment with a random payment hash and random payment secret
8239         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8240         handle_unknown_invalid_payment_data!();
8241         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8242 }
8243
8244 #[test]
8245 fn test_update_err_monitor_lockdown() {
8246         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8247         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8248         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8249         //
8250         // This scenario may happen in a watchtower setup, where watchtower process a block height
8251         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8252         // commitment at same time.
8253
8254         let chanmon_cfgs = create_chanmon_cfgs(2);
8255         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8256         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8257         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8258
8259         // Create some initial channel
8260         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8261         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8262
8263         // Rebalance the network to generate htlc in the two directions
8264         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8265
8266         // Route a HTLC from node 0 to node 1 (but don't settle)
8267         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8268
8269         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8270         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8271         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8272         let persister = test_utils::TestPersister::new();
8273         let watchtower = {
8274                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8275                 let mut w = test_utils::TestVecWriter(Vec::new());
8276                 monitor.write(&mut w).unwrap();
8277                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8278                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8279                 assert!(new_monitor == *monitor);
8280                 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);
8281                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8282                 watchtower
8283         };
8284         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8285         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8286         // transaction lock time requirements here.
8287         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8288         watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8289
8290         // Try to update ChannelMonitor
8291         assert!(nodes[1].node.claim_funds(preimage));
8292         check_added_monitors!(nodes[1], 1);
8293         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8294         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8295         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8296         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8297                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8298                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8299                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8300                 } else { assert!(false); }
8301         } else { assert!(false); };
8302         // Our local monitor is in-sync and hasn't processed yet timeout
8303         check_added_monitors!(nodes[0], 1);
8304         let events = nodes[0].node.get_and_clear_pending_events();
8305         assert_eq!(events.len(), 1);
8306 }
8307
8308 #[test]
8309 fn test_concurrent_monitor_claim() {
8310         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8311         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8312         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8313         // state N+1 confirms. Alice claims output from state N+1.
8314
8315         let chanmon_cfgs = create_chanmon_cfgs(2);
8316         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8317         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8318         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8319
8320         // Create some initial channel
8321         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8322         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8323
8324         // Rebalance the network to generate htlc in the two directions
8325         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8326
8327         // Route a HTLC from node 0 to node 1 (but don't settle)
8328         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8329
8330         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8331         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8332         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8333         let persister = test_utils::TestPersister::new();
8334         let watchtower_alice = {
8335                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8336                 let mut w = test_utils::TestVecWriter(Vec::new());
8337                 monitor.write(&mut w).unwrap();
8338                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8339                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8340                 assert!(new_monitor == *monitor);
8341                 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);
8342                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8343                 watchtower
8344         };
8345         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8346         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8347         // transaction lock time requirements here.
8348         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8349         watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8350
8351         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8352         {
8353                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8354                 assert_eq!(txn.len(), 2);
8355                 txn.clear();
8356         }
8357
8358         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8359         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8360         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8361         let persister = test_utils::TestPersister::new();
8362         let watchtower_bob = {
8363                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8364                 let mut w = test_utils::TestVecWriter(Vec::new());
8365                 monitor.write(&mut w).unwrap();
8366                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8367                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8368                 assert!(new_monitor == *monitor);
8369                 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);
8370                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8371                 watchtower
8372         };
8373         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8374         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8375
8376         // Route another payment to generate another update with still previous HTLC pending
8377         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8378         {
8379                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8380         }
8381         check_added_monitors!(nodes[1], 1);
8382
8383         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8384         assert_eq!(updates.update_add_htlcs.len(), 1);
8385         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8386         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8387                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8388                         // Watchtower Alice should already have seen the block and reject the update
8389                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8390                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8391                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8392                 } else { assert!(false); }
8393         } else { assert!(false); };
8394         // Our local monitor is in-sync and hasn't processed yet timeout
8395         check_added_monitors!(nodes[0], 1);
8396
8397         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8398         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8399         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8400
8401         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8402         let bob_state_y;
8403         {
8404                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8405                 assert_eq!(txn.len(), 2);
8406                 bob_state_y = txn[0].clone();
8407                 txn.clear();
8408         };
8409
8410         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8411         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8412         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);
8413         {
8414                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8415                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8416                 // the onchain detection of the HTLC output
8417                 assert_eq!(htlc_txn.len(), 2);
8418                 check_spends!(htlc_txn[0], bob_state_y);
8419                 check_spends!(htlc_txn[1], bob_state_y);
8420         }
8421 }
8422
8423 #[test]
8424 fn test_pre_lockin_no_chan_closed_update() {
8425         // Test that if a peer closes a channel in response to a funding_created message we don't
8426         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8427         // message).
8428         //
8429         // Doing so would imply a channel monitor update before the initial channel monitor
8430         // registration, violating our API guarantees.
8431         //
8432         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8433         // then opening a second channel with the same funding output as the first (which is not
8434         // rejected because the first channel does not exist in the ChannelManager) and closing it
8435         // before receiving funding_signed.
8436         let chanmon_cfgs = create_chanmon_cfgs(2);
8437         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8438         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8439         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8440
8441         // Create an initial channel
8442         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8443         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8444         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8445         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8446         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8447
8448         // Move the first channel through the funding flow...
8449         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8450
8451         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8452         check_added_monitors!(nodes[0], 0);
8453
8454         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8455         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8456         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8457         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8458         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8459 }
8460
8461 #[test]
8462 fn test_htlc_no_detection() {
8463         // This test is a mutation to underscore the detection logic bug we had
8464         // before #653. HTLC value routed is above the remaining balance, thus
8465         // inverting HTLC and `to_remote` output. HTLC will come second and
8466         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8467         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8468         // outputs order detection for correct spending children filtring.
8469
8470         let chanmon_cfgs = create_chanmon_cfgs(2);
8471         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8472         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8473         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8474
8475         // Create some initial channels
8476         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8477
8478         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8479         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8480         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8481         assert_eq!(local_txn[0].input.len(), 1);
8482         assert_eq!(local_txn[0].output.len(), 3);
8483         check_spends!(local_txn[0], chan_1.3);
8484
8485         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8486         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8487         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8488         // We deliberately connect the local tx twice as this should provoke a failure calling
8489         // this test before #653 fix.
8490         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);
8491         check_closed_broadcast!(nodes[0], true);
8492         check_added_monitors!(nodes[0], 1);
8493         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8494         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8495
8496         let htlc_timeout = {
8497                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8498                 assert_eq!(node_txn[1].input.len(), 1);
8499                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8500                 check_spends!(node_txn[1], local_txn[0]);
8501                 node_txn[1].clone()
8502         };
8503
8504         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8505         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8506         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8507         expect_payment_failed!(nodes[0], our_payment_hash, true);
8508 }
8509
8510 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8511         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8512         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8513         // Carol, Alice would be the upstream node, and Carol the downstream.)
8514         //
8515         // Steps of the test:
8516         // 1) Alice sends a HTLC to Carol through Bob.
8517         // 2) Carol doesn't settle the HTLC.
8518         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8519         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8520         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8521         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8522         // 5) Carol release the preimage to Bob off-chain.
8523         // 6) Bob claims the offered output on the broadcasted commitment.
8524         let chanmon_cfgs = create_chanmon_cfgs(3);
8525         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8526         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8527         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8528
8529         // Create some initial channels
8530         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8531         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8532
8533         // Steps (1) and (2):
8534         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8535         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8536
8537         // Check that Alice's commitment transaction now contains an output for this HTLC.
8538         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8539         check_spends!(alice_txn[0], chan_ab.3);
8540         assert_eq!(alice_txn[0].output.len(), 2);
8541         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8542         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8543         assert_eq!(alice_txn.len(), 2);
8544
8545         // Steps (3) and (4):
8546         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8547         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8548         let mut force_closing_node = 0; // Alice force-closes
8549         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8550         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8551         check_closed_broadcast!(nodes[force_closing_node], true);
8552         check_added_monitors!(nodes[force_closing_node], 1);
8553         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8554         if go_onchain_before_fulfill {
8555                 let txn_to_broadcast = match broadcast_alice {
8556                         true => alice_txn.clone(),
8557                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8558                 };
8559                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8560                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8561                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8562                 if broadcast_alice {
8563                         check_closed_broadcast!(nodes[1], true);
8564                         check_added_monitors!(nodes[1], 1);
8565                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8566                 }
8567                 assert_eq!(bob_txn.len(), 1);
8568                 check_spends!(bob_txn[0], chan_ab.3);
8569         }
8570
8571         // Step (5):
8572         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8573         // process of removing the HTLC from their commitment transactions.
8574         assert!(nodes[2].node.claim_funds(payment_preimage));
8575         check_added_monitors!(nodes[2], 1);
8576         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8577         assert!(carol_updates.update_add_htlcs.is_empty());
8578         assert!(carol_updates.update_fail_htlcs.is_empty());
8579         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8580         assert!(carol_updates.update_fee.is_none());
8581         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8582
8583         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8584         expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8585         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8586         if !go_onchain_before_fulfill && broadcast_alice {
8587                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8588                 assert_eq!(events.len(), 1);
8589                 match events[0] {
8590                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8591                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8592                         },
8593                         _ => panic!("Unexpected event"),
8594                 };
8595         }
8596         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8597         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8598         // Carol<->Bob's updated commitment transaction info.
8599         check_added_monitors!(nodes[1], 2);
8600
8601         let events = nodes[1].node.get_and_clear_pending_msg_events();
8602         assert_eq!(events.len(), 2);
8603         let bob_revocation = match events[0] {
8604                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8605                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8606                         (*msg).clone()
8607                 },
8608                 _ => panic!("Unexpected event"),
8609         };
8610         let bob_updates = match events[1] {
8611                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8612                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8613                         (*updates).clone()
8614                 },
8615                 _ => panic!("Unexpected event"),
8616         };
8617
8618         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8619         check_added_monitors!(nodes[2], 1);
8620         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8621         check_added_monitors!(nodes[2], 1);
8622
8623         let events = nodes[2].node.get_and_clear_pending_msg_events();
8624         assert_eq!(events.len(), 1);
8625         let carol_revocation = match events[0] {
8626                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8627                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8628                         (*msg).clone()
8629                 },
8630                 _ => panic!("Unexpected event"),
8631         };
8632         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8633         check_added_monitors!(nodes[1], 1);
8634
8635         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8636         // here's where we put said channel's commitment tx on-chain.
8637         let mut txn_to_broadcast = alice_txn.clone();
8638         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8639         if !go_onchain_before_fulfill {
8640                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8641                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8642                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8643                 if broadcast_alice {
8644                         check_closed_broadcast!(nodes[1], true);
8645                         check_added_monitors!(nodes[1], 1);
8646                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8647                 }
8648                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8649                 if broadcast_alice {
8650                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8651                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8652                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8653                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8654                         // broadcasted.
8655                         assert_eq!(bob_txn.len(), 3);
8656                         check_spends!(bob_txn[1], chan_ab.3);
8657                 } else {
8658                         assert_eq!(bob_txn.len(), 2);
8659                         check_spends!(bob_txn[0], chan_ab.3);
8660                 }
8661         }
8662
8663         // Step (6):
8664         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8665         // broadcasted commitment transaction.
8666         {
8667                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8668                 if go_onchain_before_fulfill {
8669                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8670                         assert_eq!(bob_txn.len(), 2);
8671                 }
8672                 let script_weight = match broadcast_alice {
8673                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8674                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8675                 };
8676                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8677                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8678                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8679                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8680                 if broadcast_alice && !go_onchain_before_fulfill {
8681                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8682                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8683                 } else {
8684                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8685                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8686                 }
8687         }
8688 }
8689
8690 #[test]
8691 fn test_onchain_htlc_settlement_after_close() {
8692         do_test_onchain_htlc_settlement_after_close(true, true);
8693         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8694         do_test_onchain_htlc_settlement_after_close(true, false);
8695         do_test_onchain_htlc_settlement_after_close(false, false);
8696 }
8697
8698 #[test]
8699 fn test_duplicate_chan_id() {
8700         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8701         // already open we reject it and keep the old channel.
8702         //
8703         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8704         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8705         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8706         // updating logic for the existing channel.
8707         let chanmon_cfgs = create_chanmon_cfgs(2);
8708         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8709         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8710         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8711
8712         // Create an initial channel
8713         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8714         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8715         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8716         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()));
8717
8718         // Try to create a second channel with the same temporary_channel_id as the first and check
8719         // that it is rejected.
8720         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8721         {
8722                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8723                 assert_eq!(events.len(), 1);
8724                 match events[0] {
8725                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8726                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8727                                 // first (valid) and second (invalid) channels are closed, given they both have
8728                                 // the same non-temporary channel_id. However, currently we do not, so we just
8729                                 // move forward with it.
8730                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8731                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8732                         },
8733                         _ => panic!("Unexpected event"),
8734                 }
8735         }
8736
8737         // Move the first channel through the funding flow...
8738         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8739
8740         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8741         check_added_monitors!(nodes[0], 0);
8742
8743         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8744         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8745         {
8746                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8747                 assert_eq!(added_monitors.len(), 1);
8748                 assert_eq!(added_monitors[0].0, funding_output);
8749                 added_monitors.clear();
8750         }
8751         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8752
8753         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8754         let channel_id = funding_outpoint.to_channel_id();
8755
8756         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8757         // temporary one).
8758
8759         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8760         // Technically this is allowed by the spec, but we don't support it and there's little reason
8761         // to. Still, it shouldn't cause any other issues.
8762         open_chan_msg.temporary_channel_id = channel_id;
8763         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8764         {
8765                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8766                 assert_eq!(events.len(), 1);
8767                 match events[0] {
8768                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8769                                 // Technically, at this point, nodes[1] would be justified in thinking both
8770                                 // channels are closed, but currently we do not, so we just move forward with it.
8771                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8772                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8773                         },
8774                         _ => panic!("Unexpected event"),
8775                 }
8776         }
8777
8778         // Now try to create a second channel which has a duplicate funding output.
8779         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8780         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8781         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8782         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()));
8783         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8784
8785         let funding_created = {
8786                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8787                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8788                 let logger = test_utils::TestLogger::new();
8789                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8790         };
8791         check_added_monitors!(nodes[0], 0);
8792         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8793         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8794         // still needs to be cleared here.
8795         check_added_monitors!(nodes[1], 1);
8796
8797         // ...still, nodes[1] will reject the duplicate channel.
8798         {
8799                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8800                 assert_eq!(events.len(), 1);
8801                 match events[0] {
8802                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8803                                 // Technically, at this point, nodes[1] would be justified in thinking both
8804                                 // channels are closed, but currently we do not, so we just move forward with it.
8805                                 assert_eq!(msg.channel_id, channel_id);
8806                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8807                         },
8808                         _ => panic!("Unexpected event"),
8809                 }
8810         }
8811
8812         // finally, finish creating the original channel and send a payment over it to make sure
8813         // everything is functional.
8814         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8815         {
8816                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8817                 assert_eq!(added_monitors.len(), 1);
8818                 assert_eq!(added_monitors[0].0, funding_output);
8819                 added_monitors.clear();
8820         }
8821
8822         let events_4 = nodes[0].node.get_and_clear_pending_events();
8823         assert_eq!(events_4.len(), 0);
8824         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8825         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
8826
8827         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8828         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8829         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8830         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8831 }
8832
8833 #[test]
8834 fn test_error_chans_closed() {
8835         // Test that we properly handle error messages, closing appropriate channels.
8836         //
8837         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8838         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8839         // we can test various edge cases around it to ensure we don't regress.
8840         let chanmon_cfgs = create_chanmon_cfgs(3);
8841         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8842         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8843         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8844
8845         // Create some initial channels
8846         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8847         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8848         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8849
8850         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8851         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8852         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8853
8854         // Closing a channel from a different peer has no effect
8855         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8856         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8857
8858         // Closing one channel doesn't impact others
8859         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8860         check_added_monitors!(nodes[0], 1);
8861         check_closed_broadcast!(nodes[0], false);
8862         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8863         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8864         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8865         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);
8866         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);
8867
8868         // A null channel ID should close all channels
8869         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8870         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8871         check_added_monitors!(nodes[0], 2);
8872         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8873         let events = nodes[0].node.get_and_clear_pending_msg_events();
8874         assert_eq!(events.len(), 2);
8875         match events[0] {
8876                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8877                         assert_eq!(msg.contents.flags & 2, 2);
8878                 },
8879                 _ => panic!("Unexpected event"),
8880         }
8881         match events[1] {
8882                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8883                         assert_eq!(msg.contents.flags & 2, 2);
8884                 },
8885                 _ => panic!("Unexpected event"),
8886         }
8887         // Note that at this point users of a standard PeerHandler will end up calling
8888         // peer_disconnected with no_connection_possible set to false, duplicating the
8889         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8890         // users with their own peer handling logic. We duplicate the call here, however.
8891         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8892         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8893
8894         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8895         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8896         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8897 }
8898
8899 #[test]
8900 fn test_invalid_funding_tx() {
8901         // Test that we properly handle invalid funding transactions sent to us from a peer.
8902         //
8903         // Previously, all other major lightning implementations had failed to properly sanitize
8904         // funding transactions from their counterparties, leading to a multi-implementation critical
8905         // security vulnerability (though we always sanitized properly, we've previously had
8906         // un-released crashes in the sanitization process).
8907         let chanmon_cfgs = create_chanmon_cfgs(2);
8908         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8909         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8910         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8911
8912         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8913         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()));
8914         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()));
8915
8916         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
8917         for output in tx.output.iter_mut() {
8918                 // Make the confirmed funding transaction have a bogus script_pubkey
8919                 output.script_pubkey = bitcoin::Script::new();
8920         }
8921
8922         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
8923         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()));
8924         check_added_monitors!(nodes[1], 1);
8925
8926         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()));
8927         check_added_monitors!(nodes[0], 1);
8928
8929         let events_1 = nodes[0].node.get_and_clear_pending_events();
8930         assert_eq!(events_1.len(), 0);
8931
8932         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8933         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8934         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8935
8936         confirm_transaction_at(&nodes[1], &tx, 1);
8937         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8938         check_added_monitors!(nodes[1], 1);
8939         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8940         assert_eq!(events_2.len(), 1);
8941         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
8942                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8943                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
8944                         assert_eq!(msg.data, "funding tx had wrong script/value or output index");
8945                 } else { panic!(); }
8946         } else { panic!(); }
8947         assert_eq!(nodes[1].node.list_channels().len(), 0);
8948 }
8949
8950 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
8951         // In the first version of the chain::Confirm interface, after a refactor was made to not
8952         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
8953         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
8954         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
8955         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
8956         // spending transaction until height N+1 (or greater). This was due to the way
8957         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
8958         // spending transaction at the height the input transaction was confirmed at, not whether we
8959         // should broadcast a spending transaction at the current height.
8960         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
8961         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
8962         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
8963         // until we learned about an additional block.
8964         //
8965         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
8966         // aren't broadcasting transactions too early (ie not broadcasting them at all).
8967         let chanmon_cfgs = create_chanmon_cfgs(3);
8968         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8969         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8970         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8971         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
8972
8973         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8974         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8975         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
8976         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
8977         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8978
8979         nodes[1].node.force_close_channel(&channel_id).unwrap();
8980         check_closed_broadcast!(nodes[1], true);
8981         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8982         check_added_monitors!(nodes[1], 1);
8983         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8984         assert_eq!(node_txn.len(), 1);
8985
8986         let conf_height = nodes[1].best_block_info().1;
8987         if !test_height_before_timelock {
8988                 connect_blocks(&nodes[1], 24 * 6);
8989         }
8990         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8991                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
8992         if test_height_before_timelock {
8993                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
8994                 // generate any events or broadcast any transactions
8995                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
8996                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
8997         } else {
8998                 // We should broadcast an HTLC transaction spending our funding transaction first
8999                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9000                 assert_eq!(spending_txn.len(), 2);
9001                 assert_eq!(spending_txn[0], node_txn[0]);
9002                 check_spends!(spending_txn[1], node_txn[0]);
9003                 // We should also generate a SpendableOutputs event with the to_self output (as its
9004                 // timelock is up).
9005                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9006                 assert_eq!(descriptor_spend_txn.len(), 1);
9007
9008                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9009                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9010                 // additional block built on top of the current chain.
9011                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9012                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9013                 expect_pending_htlcs_forwardable!(nodes[1]);
9014                 check_added_monitors!(nodes[1], 1);
9015
9016                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9017                 assert!(updates.update_add_htlcs.is_empty());
9018                 assert!(updates.update_fulfill_htlcs.is_empty());
9019                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9020                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9021                 assert!(updates.update_fee.is_none());
9022                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9023                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9024                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9025         }
9026 }
9027
9028 #[test]
9029 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9030         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9031         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9032 }
9033
9034 #[test]
9035 fn test_forwardable_regen() {
9036         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9037         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9038         // HTLCs.
9039         // We test it for both payment receipt and payment forwarding.
9040
9041         let chanmon_cfgs = create_chanmon_cfgs(3);
9042         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9043         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9044         let persister: test_utils::TestPersister;
9045         let new_chain_monitor: test_utils::TestChainMonitor;
9046         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9047         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9048         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9049         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9050
9051         // First send a payment to nodes[1]
9052         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9053         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9054         check_added_monitors!(nodes[0], 1);
9055
9056         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9057         assert_eq!(events.len(), 1);
9058         let payment_event = SendEvent::from_event(events.pop().unwrap());
9059         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9060         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9061
9062         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9063
9064         // Next send a payment which is forwarded by nodes[1]
9065         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9066         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9067         check_added_monitors!(nodes[0], 1);
9068
9069         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9070         assert_eq!(events.len(), 1);
9071         let payment_event = SendEvent::from_event(events.pop().unwrap());
9072         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9073         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9074
9075         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9076         // generated
9077         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9078
9079         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9080         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9081         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9082
9083         let nodes_1_serialized = nodes[1].node.encode();
9084         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9085         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9086         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9087         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9088
9089         persister = test_utils::TestPersister::new();
9090         let keys_manager = &chanmon_cfgs[1].keys_manager;
9091         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);
9092         nodes[1].chain_monitor = &new_chain_monitor;
9093
9094         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9095         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9096                 &mut chan_0_monitor_read, keys_manager).unwrap();
9097         assert!(chan_0_monitor_read.is_empty());
9098         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9099         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9100                 &mut chan_1_monitor_read, keys_manager).unwrap();
9101         assert!(chan_1_monitor_read.is_empty());
9102
9103         let mut nodes_1_read = &nodes_1_serialized[..];
9104         let (_, nodes_1_deserialized_tmp) = {
9105                 let mut channel_monitors = HashMap::new();
9106                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9107                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9108                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9109                         default_config: UserConfig::default(),
9110                         keys_manager,
9111                         fee_estimator: node_cfgs[1].fee_estimator,
9112                         chain_monitor: nodes[1].chain_monitor,
9113                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9114                         logger: nodes[1].logger,
9115                         channel_monitors,
9116                 }).unwrap()
9117         };
9118         nodes_1_deserialized = nodes_1_deserialized_tmp;
9119         assert!(nodes_1_read.is_empty());
9120
9121         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9122         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9123         nodes[1].node = &nodes_1_deserialized;
9124         check_added_monitors!(nodes[1], 2);
9125
9126         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9127         // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9128         // the commitment state.
9129         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9130
9131         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9132
9133         expect_pending_htlcs_forwardable!(nodes[1]);
9134         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9135         check_added_monitors!(nodes[1], 1);
9136
9137         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9138         assert_eq!(events.len(), 1);
9139         let payment_event = SendEvent::from_event(events.pop().unwrap());
9140         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9141         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9142         expect_pending_htlcs_forwardable!(nodes[2]);
9143         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9144
9145         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9146         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9147 }
9148
9149 #[test]
9150 fn test_keysend_payments_to_public_node() {
9151         let chanmon_cfgs = create_chanmon_cfgs(2);
9152         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9153         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9154         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9155
9156         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9157         let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
9158         let payer_pubkey = nodes[0].node.get_our_node_id();
9159         let payee_pubkey = nodes[1].node.get_our_node_id();
9160         let route = get_keysend_route(
9161                 &payer_pubkey, &network_graph, &payee_pubkey, None, &vec![], 10000, 40, nodes[0].logger
9162         ).unwrap();
9163
9164         let test_preimage = PaymentPreimage([42; 32]);
9165         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9166         check_added_monitors!(nodes[0], 1);
9167         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9168         assert_eq!(events.len(), 1);
9169         let event = events.pop().unwrap();
9170         let path = vec![&nodes[1]];
9171         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9172         claim_payment(&nodes[0], &path, test_preimage);
9173 }
9174
9175 #[test]
9176 fn test_keysend_payments_to_private_node() {
9177         let chanmon_cfgs = create_chanmon_cfgs(2);
9178         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9179         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9180         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9181
9182         let payer_pubkey = nodes[0].node.get_our_node_id();
9183         let payee_pubkey = nodes[1].node.get_our_node_id();
9184         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known() });
9185         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known() });
9186
9187         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9188         let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
9189         let first_hops = nodes[0].node.list_usable_channels();
9190         let route = get_keysend_route(
9191                 &payer_pubkey, &network_graph, &payee_pubkey, Some(&first_hops.iter().collect::<Vec<_>>()),
9192                 &vec![], 10000, 40, nodes[0].logger
9193         ).unwrap();
9194
9195         let test_preimage = PaymentPreimage([42; 32]);
9196         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9197         check_added_monitors!(nodes[0], 1);
9198         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9199         assert_eq!(events.len(), 1);
9200         let event = events.pop().unwrap();
9201         let path = vec![&nodes[1]];
9202         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9203         claim_payment(&nodes[0], &path, test_preimage);
9204 }