Update test_dup_htlc_onchain_fails_on_reload for new persist API
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use chain;
15 use chain::{Confirm, Listen, Watch, ChannelMonitorUpdateErr};
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::BaseSign;
20 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
21 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA};
23 use ln::channel::{Channel, ChannelError};
24 use ln::{chan_utils, onion_utils};
25 use ln::chan_utils::HTLC_SUCCESS_TX_WEIGHT;
26 use routing::network_graph::{NetworkUpdate, RoutingFees};
27 use routing::router::{Route, RouteHop, RouteHint, RouteHintHop, get_route, get_keysend_route};
28 use 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 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool) {
4103         // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
4104         // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
4105         // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
4106         // the ChannelMonitor tells it to.
4107         //
4108         // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
4109         // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
4110         // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
4111         let chanmon_cfgs = create_chanmon_cfgs(2);
4112         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4113         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4114         let persister: test_utils::TestPersister;
4115         let new_chain_monitor: test_utils::TestChainMonitor;
4116         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4117         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4118
4119         let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4120
4121         // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
4122         // nodes[0].
4123         let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 10000000);
4124         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
4125         check_closed_broadcast!(nodes[0], true);
4126         check_added_monitors!(nodes[0], 1);
4127         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4128
4129         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4130         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4131
4132         // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
4133         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
4134         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4135         assert_eq!(node_txn.len(), 3);
4136         assert_eq!(node_txn[0], node_txn[1]);
4137         check_spends!(node_txn[1], funding_tx);
4138         check_spends!(node_txn[2], node_txn[1]);
4139
4140         assert!(nodes[1].node.claim_funds(payment_preimage));
4141         check_added_monitors!(nodes[1], 1);
4142
4143         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4144         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()]});
4145         check_closed_broadcast!(nodes[1], true);
4146         check_added_monitors!(nodes[1], 1);
4147         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4148         let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4149
4150         header.prev_blockhash = nodes[0].best_block_hash();
4151         connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()]});
4152
4153         // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
4154         // returning TemporaryFailure. This should cause the claim event to never make its way to the
4155         // ChannelManager.
4156         chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
4157         chanmon_cfgs[0].persister.set_update_ret(Err(ChannelMonitorUpdateErr::TemporaryFailure));
4158
4159         header.prev_blockhash = nodes[0].best_block_hash();
4160         let claim_block = Block { header, txdata: claim_txn };
4161         connect_block(&nodes[0], &claim_block);
4162
4163         let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
4164         let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
4165                 .get_mut(&funding_txo).unwrap().drain().collect();
4166         assert_eq!(mon_updates.len(), 1);
4167         assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
4168         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4169
4170         // If we persist the ChannelManager here, we should get the PaymentSent event after
4171         // deserialization.
4172         let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
4173         if !persist_manager_post_event {
4174                 nodes[0].node.write(&mut chan_manager_serialized).unwrap();
4175         }
4176
4177         // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
4178         // payment sent event.
4179         chanmon_cfgs[0].persister.set_update_ret(Ok(()));
4180         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4181         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4182         nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, mon_updates[0]).unwrap();
4183         expect_payment_sent!(nodes[0], payment_preimage);
4184
4185         // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
4186         // twice.
4187         if persist_manager_post_event {
4188                 nodes[0].node.write(&mut chan_manager_serialized).unwrap();
4189         }
4190
4191         // Now reload nodes[0]...
4192         persister = test_utils::TestPersister::new();
4193         let keys_manager = &chanmon_cfgs[0].keys_manager;
4194         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);
4195         nodes[0].chain_monitor = &new_chain_monitor;
4196         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4197         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4198                 &mut chan_0_monitor_read, keys_manager).unwrap();
4199         assert!(chan_0_monitor_read.is_empty());
4200
4201         let (_, nodes_0_deserialized_tmp) = {
4202                 let mut channel_monitors = HashMap::new();
4203                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4204                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
4205                         ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
4206                                 default_config: Default::default(),
4207                                 keys_manager,
4208                                 fee_estimator: node_cfgs[0].fee_estimator,
4209                                 chain_monitor: nodes[0].chain_monitor,
4210                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4211                                 logger: nodes[0].logger,
4212                                 channel_monitors,
4213                         }).unwrap()
4214         };
4215         nodes_0_deserialized = nodes_0_deserialized_tmp;
4216
4217         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4218         check_added_monitors!(nodes[0], 1);
4219         nodes[0].node = &nodes_0_deserialized;
4220
4221         if persist_manager_post_event {
4222                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4223         } else {
4224                 expect_payment_sent!(nodes[0], payment_preimage);
4225         }
4226
4227         // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
4228         // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
4229         // payment events should kick in, leaving us with no pending events here.
4230         let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
4231         nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
4232         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4233 }
4234
4235 #[test]
4236 fn test_dup_htlc_onchain_fails_on_reload() {
4237         do_test_dup_htlc_onchain_fails_on_reload(true);
4238         do_test_dup_htlc_onchain_fails_on_reload(false);
4239 }
4240
4241 #[test]
4242 fn test_manager_serialize_deserialize_events() {
4243         // This test makes sure the events field in ChannelManager survives de/serialization
4244         let chanmon_cfgs = create_chanmon_cfgs(2);
4245         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4246         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4247         let fee_estimator: test_utils::TestFeeEstimator;
4248         let persister: test_utils::TestPersister;
4249         let logger: test_utils::TestLogger;
4250         let new_chain_monitor: test_utils::TestChainMonitor;
4251         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4252         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4253
4254         // Start creating a channel, but stop right before broadcasting the funding transaction
4255         let channel_value = 100000;
4256         let push_msat = 10001;
4257         let a_flags = InitFeatures::known();
4258         let b_flags = InitFeatures::known();
4259         let node_a = nodes.remove(0);
4260         let node_b = nodes.remove(0);
4261         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4262         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()));
4263         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()));
4264
4265         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4266
4267         node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4268         check_added_monitors!(node_a, 0);
4269
4270         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()));
4271         {
4272                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4273                 assert_eq!(added_monitors.len(), 1);
4274                 assert_eq!(added_monitors[0].0, funding_output);
4275                 added_monitors.clear();
4276         }
4277
4278         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4279         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4280         {
4281                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4282                 assert_eq!(added_monitors.len(), 1);
4283                 assert_eq!(added_monitors[0].0, funding_output);
4284                 added_monitors.clear();
4285         }
4286         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4287
4288         nodes.push(node_a);
4289         nodes.push(node_b);
4290
4291         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4292         let nodes_0_serialized = nodes[0].node.encode();
4293         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4294         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4295
4296         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4297         logger = test_utils::TestLogger::new();
4298         persister = test_utils::TestPersister::new();
4299         let keys_manager = &chanmon_cfgs[0].keys_manager;
4300         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4301         nodes[0].chain_monitor = &new_chain_monitor;
4302         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4303         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4304                 &mut chan_0_monitor_read, keys_manager).unwrap();
4305         assert!(chan_0_monitor_read.is_empty());
4306
4307         let mut nodes_0_read = &nodes_0_serialized[..];
4308         let config = UserConfig::default();
4309         let (_, nodes_0_deserialized_tmp) = {
4310                 let mut channel_monitors = HashMap::new();
4311                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4312                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4313                         default_config: config,
4314                         keys_manager,
4315                         fee_estimator: &fee_estimator,
4316                         chain_monitor: nodes[0].chain_monitor,
4317                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4318                         logger: &logger,
4319                         channel_monitors,
4320                 }).unwrap()
4321         };
4322         nodes_0_deserialized = nodes_0_deserialized_tmp;
4323         assert!(nodes_0_read.is_empty());
4324
4325         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4326
4327         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4328         nodes[0].node = &nodes_0_deserialized;
4329
4330         // After deserializing, make sure the funding_transaction is still held by the channel manager
4331         let events_4 = nodes[0].node.get_and_clear_pending_events();
4332         assert_eq!(events_4.len(), 0);
4333         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4334         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4335
4336         // Make sure the channel is functioning as though the de/serialization never happened
4337         assert_eq!(nodes[0].node.list_channels().len(), 1);
4338         check_added_monitors!(nodes[0], 1);
4339
4340         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4341         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4342         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4343         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4344
4345         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4346         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4347         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4348         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4349
4350         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4351         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4352         for node in nodes.iter() {
4353                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4354                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4355                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4356         }
4357
4358         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4359 }
4360
4361 #[test]
4362 fn test_simple_manager_serialize_deserialize() {
4363         let chanmon_cfgs = create_chanmon_cfgs(2);
4364         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4365         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4366         let logger: test_utils::TestLogger;
4367         let fee_estimator: test_utils::TestFeeEstimator;
4368         let persister: test_utils::TestPersister;
4369         let new_chain_monitor: test_utils::TestChainMonitor;
4370         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4371         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4372         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4373
4374         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4375         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4376
4377         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4378
4379         let nodes_0_serialized = nodes[0].node.encode();
4380         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4381         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4382
4383         logger = test_utils::TestLogger::new();
4384         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4385         persister = test_utils::TestPersister::new();
4386         let keys_manager = &chanmon_cfgs[0].keys_manager;
4387         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4388         nodes[0].chain_monitor = &new_chain_monitor;
4389         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4390         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4391                 &mut chan_0_monitor_read, keys_manager).unwrap();
4392         assert!(chan_0_monitor_read.is_empty());
4393
4394         let mut nodes_0_read = &nodes_0_serialized[..];
4395         let (_, nodes_0_deserialized_tmp) = {
4396                 let mut channel_monitors = HashMap::new();
4397                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4398                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4399                         default_config: UserConfig::default(),
4400                         keys_manager,
4401                         fee_estimator: &fee_estimator,
4402                         chain_monitor: nodes[0].chain_monitor,
4403                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4404                         logger: &logger,
4405                         channel_monitors,
4406                 }).unwrap()
4407         };
4408         nodes_0_deserialized = nodes_0_deserialized_tmp;
4409         assert!(nodes_0_read.is_empty());
4410
4411         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4412         nodes[0].node = &nodes_0_deserialized;
4413         check_added_monitors!(nodes[0], 1);
4414
4415         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4416
4417         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4418         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4419 }
4420
4421 #[test]
4422 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4423         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4424         let chanmon_cfgs = create_chanmon_cfgs(4);
4425         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4426         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4427         let logger: test_utils::TestLogger;
4428         let fee_estimator: test_utils::TestFeeEstimator;
4429         let persister: test_utils::TestPersister;
4430         let new_chain_monitor: test_utils::TestChainMonitor;
4431         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4432         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4433         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4434         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4435         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4436
4437         let mut node_0_stale_monitors_serialized = Vec::new();
4438         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4439                 let mut writer = test_utils::TestVecWriter(Vec::new());
4440                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4441                 node_0_stale_monitors_serialized.push(writer.0);
4442         }
4443
4444         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4445
4446         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4447         let nodes_0_serialized = nodes[0].node.encode();
4448
4449         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4450         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4451         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4452         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4453
4454         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4455         // nodes[3])
4456         let mut node_0_monitors_serialized = Vec::new();
4457         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4458                 let mut writer = test_utils::TestVecWriter(Vec::new());
4459                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4460                 node_0_monitors_serialized.push(writer.0);
4461         }
4462
4463         logger = test_utils::TestLogger::new();
4464         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4465         persister = test_utils::TestPersister::new();
4466         let keys_manager = &chanmon_cfgs[0].keys_manager;
4467         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4468         nodes[0].chain_monitor = &new_chain_monitor;
4469
4470
4471         let mut node_0_stale_monitors = Vec::new();
4472         for serialized in node_0_stale_monitors_serialized.iter() {
4473                 let mut read = &serialized[..];
4474                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4475                 assert!(read.is_empty());
4476                 node_0_stale_monitors.push(monitor);
4477         }
4478
4479         let mut node_0_monitors = Vec::new();
4480         for serialized in node_0_monitors_serialized.iter() {
4481                 let mut read = &serialized[..];
4482                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4483                 assert!(read.is_empty());
4484                 node_0_monitors.push(monitor);
4485         }
4486
4487         let mut nodes_0_read = &nodes_0_serialized[..];
4488         if let Err(msgs::DecodeError::InvalidValue) =
4489                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4490                 default_config: UserConfig::default(),
4491                 keys_manager,
4492                 fee_estimator: &fee_estimator,
4493                 chain_monitor: nodes[0].chain_monitor,
4494                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4495                 logger: &logger,
4496                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4497         }) { } else {
4498                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4499         };
4500
4501         let mut nodes_0_read = &nodes_0_serialized[..];
4502         let (_, nodes_0_deserialized_tmp) =
4503                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4504                 default_config: UserConfig::default(),
4505                 keys_manager,
4506                 fee_estimator: &fee_estimator,
4507                 chain_monitor: nodes[0].chain_monitor,
4508                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4509                 logger: &logger,
4510                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4511         }).unwrap();
4512         nodes_0_deserialized = nodes_0_deserialized_tmp;
4513         assert!(nodes_0_read.is_empty());
4514
4515         { // Channel close should result in a commitment tx
4516                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4517                 assert_eq!(txn.len(), 1);
4518                 check_spends!(txn[0], funding_tx);
4519                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4520         }
4521
4522         for monitor in node_0_monitors.drain(..) {
4523                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4524                 check_added_monitors!(nodes[0], 1);
4525         }
4526         nodes[0].node = &nodes_0_deserialized;
4527         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4528
4529         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4530         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4531         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4532         //... and we can even still claim the payment!
4533         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4534
4535         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4536         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4537         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4538         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4539         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4540         assert_eq!(msg_events.len(), 1);
4541         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4542                 match action {
4543                         &ErrorAction::SendErrorMessage { ref msg } => {
4544                                 assert_eq!(msg.channel_id, channel_id);
4545                         },
4546                         _ => panic!("Unexpected event!"),
4547                 }
4548         }
4549 }
4550
4551 macro_rules! check_spendable_outputs {
4552         ($node: expr, $keysinterface: expr) => {
4553                 {
4554                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4555                         let mut txn = Vec::new();
4556                         let mut all_outputs = Vec::new();
4557                         let secp_ctx = Secp256k1::new();
4558                         for event in events.drain(..) {
4559                                 match event {
4560                                         Event::SpendableOutputs { mut outputs } => {
4561                                                 for outp in outputs.drain(..) {
4562                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4563                                                         all_outputs.push(outp);
4564                                                 }
4565                                         },
4566                                         _ => panic!("Unexpected event"),
4567                                 };
4568                         }
4569                         if all_outputs.len() > 1 {
4570                                 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) {
4571                                         txn.push(tx);
4572                                 }
4573                         }
4574                         txn
4575                 }
4576         }
4577 }
4578
4579 #[test]
4580 fn test_claim_sizeable_push_msat() {
4581         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4582         let chanmon_cfgs = create_chanmon_cfgs(2);
4583         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4584         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4585         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4586
4587         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4588         nodes[1].node.force_close_channel(&chan.2).unwrap();
4589         check_closed_broadcast!(nodes[1], true);
4590         check_added_monitors!(nodes[1], 1);
4591         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4592         let node_txn = nodes[1].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         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4599
4600         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4601         assert_eq!(spend_txn.len(), 1);
4602         assert_eq!(spend_txn[0].input.len(), 1);
4603         check_spends!(spend_txn[0], node_txn[0]);
4604         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4605 }
4606
4607 #[test]
4608 fn test_claim_on_remote_sizeable_push_msat() {
4609         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4610         // to_remote output is encumbered by a P2WPKH
4611         let chanmon_cfgs = create_chanmon_cfgs(2);
4612         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4613         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4614         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4615
4616         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4617         nodes[0].node.force_close_channel(&chan.2).unwrap();
4618         check_closed_broadcast!(nodes[0], true);
4619         check_added_monitors!(nodes[0], 1);
4620         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4621
4622         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4623         assert_eq!(node_txn.len(), 1);
4624         check_spends!(node_txn[0], chan.3);
4625         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
4626
4627         mine_transaction(&nodes[1], &node_txn[0]);
4628         check_closed_broadcast!(nodes[1], true);
4629         check_added_monitors!(nodes[1], 1);
4630         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4631         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4632
4633         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4634         assert_eq!(spend_txn.len(), 1);
4635         check_spends!(spend_txn[0], node_txn[0]);
4636 }
4637
4638 #[test]
4639 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4640         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4641         // to_remote output is encumbered by a P2WPKH
4642
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         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4649         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4650         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4651         assert_eq!(revoked_local_txn[0].input.len(), 1);
4652         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4653
4654         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4655         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4656         check_closed_broadcast!(nodes[1], true);
4657         check_added_monitors!(nodes[1], 1);
4658         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4659
4660         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4661         mine_transaction(&nodes[1], &node_txn[0]);
4662         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4663
4664         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4665         assert_eq!(spend_txn.len(), 3);
4666         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4667         check_spends!(spend_txn[1], node_txn[0]);
4668         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4669 }
4670
4671 #[test]
4672 fn test_static_spendable_outputs_preimage_tx() {
4673         let chanmon_cfgs = create_chanmon_cfgs(2);
4674         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4675         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4676         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4677
4678         // Create some initial channels
4679         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4680
4681         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4682
4683         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4684         assert_eq!(commitment_tx[0].input.len(), 1);
4685         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4686
4687         // Settle A's commitment tx on B's chain
4688         assert!(nodes[1].node.claim_funds(payment_preimage));
4689         check_added_monitors!(nodes[1], 1);
4690         mine_transaction(&nodes[1], &commitment_tx[0]);
4691         check_added_monitors!(nodes[1], 1);
4692         let events = nodes[1].node.get_and_clear_pending_msg_events();
4693         match events[0] {
4694                 MessageSendEvent::UpdateHTLCs { .. } => {},
4695                 _ => panic!("Unexpected event"),
4696         }
4697         match events[1] {
4698                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4699                 _ => panic!("Unexepected event"),
4700         }
4701
4702         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4703         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4704         assert_eq!(node_txn.len(), 3);
4705         check_spends!(node_txn[0], commitment_tx[0]);
4706         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4707         check_spends!(node_txn[1], chan_1.3);
4708         check_spends!(node_txn[2], node_txn[1]);
4709
4710         mine_transaction(&nodes[1], &node_txn[0]);
4711         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4712         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4713
4714         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4715         assert_eq!(spend_txn.len(), 1);
4716         check_spends!(spend_txn[0], node_txn[0]);
4717 }
4718
4719 #[test]
4720 fn test_static_spendable_outputs_timeout_tx() {
4721         let chanmon_cfgs = create_chanmon_cfgs(2);
4722         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4723         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4724         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4725
4726         // Create some initial channels
4727         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4728
4729         // Rebalance the network a bit by relaying one payment through all the channels ...
4730         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4731
4732         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4733
4734         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4735         assert_eq!(commitment_tx[0].input.len(), 1);
4736         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4737
4738         // Settle A's commitment tx on B' chain
4739         mine_transaction(&nodes[1], &commitment_tx[0]);
4740         check_added_monitors!(nodes[1], 1);
4741         let events = nodes[1].node.get_and_clear_pending_msg_events();
4742         match events[0] {
4743                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4744                 _ => panic!("Unexpected event"),
4745         }
4746         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4747
4748         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4749         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4750         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4751         check_spends!(node_txn[0], chan_1.3.clone());
4752         check_spends!(node_txn[1],  commitment_tx[0].clone());
4753         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4754
4755         mine_transaction(&nodes[1], &node_txn[1]);
4756         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4757         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4758         expect_payment_failed!(nodes[1], our_payment_hash, true);
4759
4760         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4761         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4762         check_spends!(spend_txn[0], commitment_tx[0]);
4763         check_spends!(spend_txn[1], node_txn[1]);
4764         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4765 }
4766
4767 #[test]
4768 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4769         let chanmon_cfgs = create_chanmon_cfgs(2);
4770         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4771         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4772         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4773
4774         // Create some initial channels
4775         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4776
4777         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4778         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4779         assert_eq!(revoked_local_txn[0].input.len(), 1);
4780         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4781
4782         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4783
4784         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4785         check_closed_broadcast!(nodes[1], true);
4786         check_added_monitors!(nodes[1], 1);
4787         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4788
4789         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4790         assert_eq!(node_txn.len(), 2);
4791         assert_eq!(node_txn[0].input.len(), 2);
4792         check_spends!(node_txn[0], revoked_local_txn[0]);
4793
4794         mine_transaction(&nodes[1], &node_txn[0]);
4795         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4796
4797         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4798         assert_eq!(spend_txn.len(), 1);
4799         check_spends!(spend_txn[0], node_txn[0]);
4800 }
4801
4802 #[test]
4803 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4804         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4805         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4806         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4807         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4808         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4809
4810         // Create some initial channels
4811         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4812
4813         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4814         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4815         assert_eq!(revoked_local_txn[0].input.len(), 1);
4816         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4817
4818         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4819
4820         // A will generate HTLC-Timeout from revoked commitment tx
4821         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4822         check_closed_broadcast!(nodes[0], true);
4823         check_added_monitors!(nodes[0], 1);
4824         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4825         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4826
4827         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4828         assert_eq!(revoked_htlc_txn.len(), 2);
4829         check_spends!(revoked_htlc_txn[0], chan_1.3);
4830         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4831         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4832         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4833         assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4834
4835         // B will generate justice tx from A's revoked commitment/HTLC tx
4836         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4837         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4838         check_closed_broadcast!(nodes[1], true);
4839         check_added_monitors!(nodes[1], 1);
4840         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4841
4842         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4843         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4844         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4845         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4846         // transactions next...
4847         assert_eq!(node_txn[0].input.len(), 3);
4848         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4849
4850         assert_eq!(node_txn[1].input.len(), 2);
4851         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4852         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4853                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4854         } else {
4855                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4856                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4857         }
4858
4859         assert_eq!(node_txn[2].input.len(), 1);
4860         check_spends!(node_txn[2], chan_1.3);
4861
4862         mine_transaction(&nodes[1], &node_txn[1]);
4863         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4864
4865         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4866         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4867         assert_eq!(spend_txn.len(), 1);
4868         assert_eq!(spend_txn[0].input.len(), 1);
4869         check_spends!(spend_txn[0], node_txn[1]);
4870 }
4871
4872 #[test]
4873 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4874         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4875         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4876         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4877         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4878         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4879
4880         // Create some initial channels
4881         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4882
4883         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4884         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4885         assert_eq!(revoked_local_txn[0].input.len(), 1);
4886         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4887
4888         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4889         assert_eq!(revoked_local_txn[0].output.len(), 2);
4890
4891         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4892
4893         // B will generate HTLC-Success from revoked commitment tx
4894         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4895         check_closed_broadcast!(nodes[1], true);
4896         check_added_monitors!(nodes[1], 1);
4897         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4898         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4899
4900         assert_eq!(revoked_htlc_txn.len(), 2);
4901         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4902         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4903         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4904
4905         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4906         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4907         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4908
4909         // A will generate justice tx from B's revoked commitment/HTLC tx
4910         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4911         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4912         check_closed_broadcast!(nodes[0], true);
4913         check_added_monitors!(nodes[0], 1);
4914         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4915
4916         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4917         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4918
4919         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4920         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4921         // transactions next...
4922         assert_eq!(node_txn[0].input.len(), 2);
4923         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4924         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4925                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4926         } else {
4927                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4928                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4929         }
4930
4931         assert_eq!(node_txn[1].input.len(), 1);
4932         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4933
4934         check_spends!(node_txn[2], chan_1.3);
4935
4936         mine_transaction(&nodes[0], &node_txn[1]);
4937         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4938
4939         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4940         // didn't try to generate any new transactions.
4941
4942         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4943         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4944         assert_eq!(spend_txn.len(), 3);
4945         assert_eq!(spend_txn[0].input.len(), 1);
4946         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4947         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4948         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4949         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4950 }
4951
4952 #[test]
4953 fn test_onchain_to_onchain_claim() {
4954         // Test that in case of channel closure, we detect the state of output and claim HTLC
4955         // on downstream peer's remote commitment tx.
4956         // First, have C claim an HTLC against its own latest commitment transaction.
4957         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4958         // channel.
4959         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4960         // gets broadcast.
4961
4962         let chanmon_cfgs = create_chanmon_cfgs(3);
4963         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4964         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4965         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4966
4967         // Create some initial channels
4968         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4969         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4970
4971         // Ensure all nodes are at the same height
4972         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4973         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4974         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4975         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4976
4977         // Rebalance the network a bit by relaying one payment through all the channels ...
4978         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4979         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4980
4981         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4982         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4983         check_spends!(commitment_tx[0], chan_2.3);
4984         nodes[2].node.claim_funds(payment_preimage);
4985         check_added_monitors!(nodes[2], 1);
4986         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4987         assert!(updates.update_add_htlcs.is_empty());
4988         assert!(updates.update_fail_htlcs.is_empty());
4989         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4990         assert!(updates.update_fail_malformed_htlcs.is_empty());
4991
4992         mine_transaction(&nodes[2], &commitment_tx[0]);
4993         check_closed_broadcast!(nodes[2], true);
4994         check_added_monitors!(nodes[2], 1);
4995         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4996
4997         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4998         assert_eq!(c_txn.len(), 3);
4999         assert_eq!(c_txn[0], c_txn[2]);
5000         assert_eq!(commitment_tx[0], c_txn[1]);
5001         check_spends!(c_txn[1], chan_2.3);
5002         check_spends!(c_txn[2], c_txn[1]);
5003         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5004         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5005         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5006         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5007
5008         // 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
5009         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5010         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5011         check_added_monitors!(nodes[1], 1);
5012         let events = nodes[1].node.get_and_clear_pending_events();
5013         assert_eq!(events.len(), 2);
5014         match events[0] {
5015                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5016                 _ => panic!("Unexpected event"),
5017         }
5018         match events[1] {
5019                 Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
5020                         assert_eq!(fee_earned_msat, Some(1000));
5021                         assert_eq!(claim_from_onchain_tx, true);
5022                 },
5023                 _ => panic!("Unexpected event"),
5024         }
5025         {
5026                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5027                 // ChannelMonitor: claim tx
5028                 assert_eq!(b_txn.len(), 1);
5029                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5030                 b_txn.clear();
5031         }
5032         check_added_monitors!(nodes[1], 1);
5033         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5034         assert_eq!(msg_events.len(), 3);
5035         match msg_events[0] {
5036                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5037                 _ => panic!("Unexpected event"),
5038         }
5039         match msg_events[1] {
5040                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5041                 _ => panic!("Unexpected event"),
5042         }
5043         match msg_events[2] {
5044                 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, .. } } => {
5045                         assert!(update_add_htlcs.is_empty());
5046                         assert!(update_fail_htlcs.is_empty());
5047                         assert_eq!(update_fulfill_htlcs.len(), 1);
5048                         assert!(update_fail_malformed_htlcs.is_empty());
5049                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5050                 },
5051                 _ => panic!("Unexpected event"),
5052         };
5053         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5054         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5055         mine_transaction(&nodes[1], &commitment_tx[0]);
5056         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5057         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5058         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5059         assert_eq!(b_txn.len(), 3);
5060         check_spends!(b_txn[1], chan_1.3);
5061         check_spends!(b_txn[2], b_txn[1]);
5062         check_spends!(b_txn[0], commitment_tx[0]);
5063         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5064         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5065         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5066
5067         check_closed_broadcast!(nodes[1], true);
5068         check_added_monitors!(nodes[1], 1);
5069 }
5070
5071 #[test]
5072 fn test_duplicate_payment_hash_one_failure_one_success() {
5073         // Topology : A --> B --> C --> D
5074         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5075         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5076         // we forward one of the payments onwards to D.
5077         let chanmon_cfgs = create_chanmon_cfgs(4);
5078         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5079         // When this test was written, the default base fee floated based on the HTLC count.
5080         // It is now fixed, so we simply set the fee to the expected value here.
5081         let mut config = test_default_channel_config();
5082         config.channel_options.forwarding_fee_base_msat = 196;
5083         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5084                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5085         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5086
5087         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5088         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5089         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5090
5091         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5092         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5093         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5094         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5095         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5096
5097         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5098
5099         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, 0).unwrap();
5100         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5101         // script push size limit so that the below script length checks match
5102         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5103         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], vec![], 900000, TEST_FINAL_CLTV - 40);
5104         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5105
5106         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5107         assert_eq!(commitment_txn[0].input.len(), 1);
5108         check_spends!(commitment_txn[0], chan_2.3);
5109
5110         mine_transaction(&nodes[1], &commitment_txn[0]);
5111         check_closed_broadcast!(nodes[1], true);
5112         check_added_monitors!(nodes[1], 1);
5113         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5114         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5115
5116         let htlc_timeout_tx;
5117         { // Extract one of the two HTLC-Timeout transaction
5118                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5119                 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5120                 assert_eq!(node_txn.len(), 4);
5121                 check_spends!(node_txn[0], chan_2.3);
5122
5123                 check_spends!(node_txn[1], commitment_txn[0]);
5124                 assert_eq!(node_txn[1].input.len(), 1);
5125                 check_spends!(node_txn[2], commitment_txn[0]);
5126                 assert_eq!(node_txn[2].input.len(), 1);
5127                 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5128                 check_spends!(node_txn[3], commitment_txn[0]);
5129                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5130
5131                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5132                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5133                 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5134                 htlc_timeout_tx = node_txn[1].clone();
5135         }
5136
5137         nodes[2].node.claim_funds(our_payment_preimage);
5138         mine_transaction(&nodes[2], &commitment_txn[0]);
5139         check_added_monitors!(nodes[2], 2);
5140         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5141         let events = nodes[2].node.get_and_clear_pending_msg_events();
5142         match events[0] {
5143                 MessageSendEvent::UpdateHTLCs { .. } => {},
5144                 _ => panic!("Unexpected event"),
5145         }
5146         match events[1] {
5147                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5148                 _ => panic!("Unexepected event"),
5149         }
5150         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5151         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)
5152         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5153         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5154         assert_eq!(htlc_success_txn[0].input.len(), 1);
5155         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5156         assert_eq!(htlc_success_txn[1].input.len(), 1);
5157         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5158         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5159         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5160         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5161         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5162         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5163
5164         mine_transaction(&nodes[1], &htlc_timeout_tx);
5165         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5166         expect_pending_htlcs_forwardable!(nodes[1]);
5167         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5168         assert!(htlc_updates.update_add_htlcs.is_empty());
5169         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5170         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5171         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5172         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5173         check_added_monitors!(nodes[1], 1);
5174
5175         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5176         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5177         {
5178                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5179         }
5180         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5181
5182         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5183         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5184         // and nodes[2] fee) is rounded down and then claimed in full.
5185         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5186         expect_payment_forwarded!(nodes[1], Some(196*2), true);
5187         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5188         assert!(updates.update_add_htlcs.is_empty());
5189         assert!(updates.update_fail_htlcs.is_empty());
5190         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5191         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5192         assert!(updates.update_fail_malformed_htlcs.is_empty());
5193         check_added_monitors!(nodes[1], 1);
5194
5195         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5196         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5197
5198         let events = nodes[0].node.get_and_clear_pending_events();
5199         match events[0] {
5200                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
5201                         assert_eq!(*payment_preimage, our_payment_preimage);
5202                         assert_eq!(*payment_hash, duplicate_payment_hash);
5203                 }
5204                 _ => panic!("Unexpected event"),
5205         }
5206 }
5207
5208 #[test]
5209 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5210         let chanmon_cfgs = create_chanmon_cfgs(2);
5211         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5212         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5213         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5214
5215         // Create some initial channels
5216         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5217
5218         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5219         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5220         assert_eq!(local_txn.len(), 1);
5221         assert_eq!(local_txn[0].input.len(), 1);
5222         check_spends!(local_txn[0], chan_1.3);
5223
5224         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5225         nodes[1].node.claim_funds(payment_preimage);
5226         check_added_monitors!(nodes[1], 1);
5227         mine_transaction(&nodes[1], &local_txn[0]);
5228         check_added_monitors!(nodes[1], 1);
5229         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5230         let events = nodes[1].node.get_and_clear_pending_msg_events();
5231         match events[0] {
5232                 MessageSendEvent::UpdateHTLCs { .. } => {},
5233                 _ => panic!("Unexpected event"),
5234         }
5235         match events[1] {
5236                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5237                 _ => panic!("Unexepected event"),
5238         }
5239         let node_tx = {
5240                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5241                 assert_eq!(node_txn.len(), 3);
5242                 assert_eq!(node_txn[0], node_txn[2]);
5243                 assert_eq!(node_txn[1], local_txn[0]);
5244                 assert_eq!(node_txn[0].input.len(), 1);
5245                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5246                 check_spends!(node_txn[0], local_txn[0]);
5247                 node_txn[0].clone()
5248         };
5249
5250         mine_transaction(&nodes[1], &node_tx);
5251         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5252
5253         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5254         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5255         assert_eq!(spend_txn.len(), 1);
5256         assert_eq!(spend_txn[0].input.len(), 1);
5257         check_spends!(spend_txn[0], node_tx);
5258         assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5259 }
5260
5261 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5262         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5263         // unrevoked commitment transaction.
5264         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5265         // a remote RAA before they could be failed backwards (and combinations thereof).
5266         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5267         // use the same payment hashes.
5268         // Thus, we use a six-node network:
5269         //
5270         // A \         / E
5271         //    - C - D -
5272         // B /         \ F
5273         // And test where C fails back to A/B when D announces its latest commitment transaction
5274         let chanmon_cfgs = create_chanmon_cfgs(6);
5275         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5276         // When this test was written, the default base fee floated based on the HTLC count.
5277         // It is now fixed, so we simply set the fee to the expected value here.
5278         let mut config = test_default_channel_config();
5279         config.channel_options.forwarding_fee_base_msat = 196;
5280         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5281                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5282         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5283
5284         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5285         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5286         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5287         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5288         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5289
5290         // Rebalance and check output sanity...
5291         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5292         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5293         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5294
5295         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5296         // 0th HTLC:
5297         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
5298         // 1st HTLC:
5299         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
5300         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5301         // 2nd HTLC:
5302         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
5303         // 3rd HTLC:
5304         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
5305         // 4th HTLC:
5306         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5307         // 5th HTLC:
5308         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5309         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5310         // 6th HTLC:
5311         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());
5312         // 7th HTLC:
5313         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());
5314
5315         // 8th HTLC:
5316         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5317         // 9th HTLC:
5318         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5319         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
5320
5321         // 10th HTLC:
5322         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
5323         // 11th HTLC:
5324         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5325         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());
5326
5327         // Double-check that six of the new HTLC were added
5328         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5329         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5330         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5331         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5332
5333         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5334         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5335         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5336         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5337         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5338         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5339         check_added_monitors!(nodes[4], 0);
5340         expect_pending_htlcs_forwardable!(nodes[4]);
5341         check_added_monitors!(nodes[4], 1);
5342
5343         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5344         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5345         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5346         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5347         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5348         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5349
5350         // Fail 3rd below-dust and 7th above-dust HTLCs
5351         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5352         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5353         check_added_monitors!(nodes[5], 0);
5354         expect_pending_htlcs_forwardable!(nodes[5]);
5355         check_added_monitors!(nodes[5], 1);
5356
5357         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5358         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5359         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5360         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5361
5362         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5363
5364         expect_pending_htlcs_forwardable!(nodes[3]);
5365         check_added_monitors!(nodes[3], 1);
5366         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5367         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5368         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5369         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5370         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5371         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5372         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5373         if deliver_last_raa {
5374                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5375         } else {
5376                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5377         }
5378
5379         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5380         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5381         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5382         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5383         //
5384         // We now broadcast the latest commitment transaction, which *should* result in failures for
5385         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5386         // the non-broadcast above-dust HTLCs.
5387         //
5388         // Alternatively, we may broadcast the previous commitment transaction, which should only
5389         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5390         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5391
5392         if announce_latest {
5393                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5394         } else {
5395                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5396         }
5397         let events = nodes[2].node.get_and_clear_pending_events();
5398         let close_event = if deliver_last_raa {
5399                 assert_eq!(events.len(), 2);
5400                 events[1].clone()
5401         } else {
5402                 assert_eq!(events.len(), 1);
5403                 events[0].clone()
5404         };
5405         match close_event {
5406                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5407                 _ => panic!("Unexpected event"),
5408         }
5409
5410         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5411         check_closed_broadcast!(nodes[2], true);
5412         if deliver_last_raa {
5413                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5414         } else {
5415                 expect_pending_htlcs_forwardable!(nodes[2]);
5416         }
5417         check_added_monitors!(nodes[2], 3);
5418
5419         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5420         assert_eq!(cs_msgs.len(), 2);
5421         let mut a_done = false;
5422         for msg in cs_msgs {
5423                 match msg {
5424                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5425                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5426                                 // should be failed-backwards here.
5427                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5428                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5429                                         for htlc in &updates.update_fail_htlcs {
5430                                                 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 });
5431                                         }
5432                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5433                                         assert!(!a_done);
5434                                         a_done = true;
5435                                         &nodes[0]
5436                                 } else {
5437                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5438                                         for htlc in &updates.update_fail_htlcs {
5439                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5440                                         }
5441                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5442                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5443                                         &nodes[1]
5444                                 };
5445                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5446                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5447                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5448                                 if announce_latest {
5449                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5450                                         if *node_id == nodes[0].node.get_our_node_id() {
5451                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5452                                         }
5453                                 }
5454                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5455                         },
5456                         _ => panic!("Unexpected event"),
5457                 }
5458         }
5459
5460         let as_events = nodes[0].node.get_and_clear_pending_events();
5461         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5462         let mut as_failds = HashSet::new();
5463         let mut as_updates = 0;
5464         for event in as_events.iter() {
5465                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5466                         assert!(as_failds.insert(*payment_hash));
5467                         if *payment_hash != payment_hash_2 {
5468                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5469                         } else {
5470                                 assert!(!rejected_by_dest);
5471                         }
5472                         if network_update.is_some() {
5473                                 as_updates += 1;
5474                         }
5475                 } else { panic!("Unexpected event"); }
5476         }
5477         assert!(as_failds.contains(&payment_hash_1));
5478         assert!(as_failds.contains(&payment_hash_2));
5479         if announce_latest {
5480                 assert!(as_failds.contains(&payment_hash_3));
5481                 assert!(as_failds.contains(&payment_hash_5));
5482         }
5483         assert!(as_failds.contains(&payment_hash_6));
5484
5485         let bs_events = nodes[1].node.get_and_clear_pending_events();
5486         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5487         let mut bs_failds = HashSet::new();
5488         let mut bs_updates = 0;
5489         for event in bs_events.iter() {
5490                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5491                         assert!(bs_failds.insert(*payment_hash));
5492                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5493                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5494                         } else {
5495                                 assert!(!rejected_by_dest);
5496                         }
5497                         if network_update.is_some() {
5498                                 bs_updates += 1;
5499                         }
5500                 } else { panic!("Unexpected event"); }
5501         }
5502         assert!(bs_failds.contains(&payment_hash_1));
5503         assert!(bs_failds.contains(&payment_hash_2));
5504         if announce_latest {
5505                 assert!(bs_failds.contains(&payment_hash_4));
5506         }
5507         assert!(bs_failds.contains(&payment_hash_5));
5508
5509         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5510         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5511         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5512         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5513         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5514         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5515 }
5516
5517 #[test]
5518 fn test_fail_backwards_latest_remote_announce_a() {
5519         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5520 }
5521
5522 #[test]
5523 fn test_fail_backwards_latest_remote_announce_b() {
5524         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5525 }
5526
5527 #[test]
5528 fn test_fail_backwards_previous_remote_announce() {
5529         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5530         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5531         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5532 }
5533
5534 #[test]
5535 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5536         let chanmon_cfgs = create_chanmon_cfgs(2);
5537         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5538         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5539         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5540
5541         // Create some initial channels
5542         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5543
5544         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5545         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5546         assert_eq!(local_txn[0].input.len(), 1);
5547         check_spends!(local_txn[0], chan_1.3);
5548
5549         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5550         mine_transaction(&nodes[0], &local_txn[0]);
5551         check_closed_broadcast!(nodes[0], true);
5552         check_added_monitors!(nodes[0], 1);
5553         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5554         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5555
5556         let htlc_timeout = {
5557                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5558                 assert_eq!(node_txn.len(), 2);
5559                 check_spends!(node_txn[0], chan_1.3);
5560                 assert_eq!(node_txn[1].input.len(), 1);
5561                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5562                 check_spends!(node_txn[1], local_txn[0]);
5563                 node_txn[1].clone()
5564         };
5565
5566         mine_transaction(&nodes[0], &htlc_timeout);
5567         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5568         expect_payment_failed!(nodes[0], our_payment_hash, true);
5569
5570         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5571         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5572         assert_eq!(spend_txn.len(), 3);
5573         check_spends!(spend_txn[0], local_txn[0]);
5574         assert_eq!(spend_txn[1].input.len(), 1);
5575         check_spends!(spend_txn[1], htlc_timeout);
5576         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5577         assert_eq!(spend_txn[2].input.len(), 2);
5578         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5579         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5580                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5581 }
5582
5583 #[test]
5584 fn test_key_derivation_params() {
5585         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5586         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5587         // let us re-derive the channel key set to then derive a delayed_payment_key.
5588
5589         let chanmon_cfgs = create_chanmon_cfgs(3);
5590
5591         // We manually create the node configuration to backup the seed.
5592         let seed = [42; 32];
5593         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5594         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);
5595         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() };
5596         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5597         node_cfgs.remove(0);
5598         node_cfgs.insert(0, node);
5599
5600         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5601         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5602
5603         // Create some initial channels
5604         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5605         // for node 0
5606         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5607         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5608         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5609
5610         // Ensure all nodes are at the same height
5611         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5612         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5613         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5614         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5615
5616         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5617         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5618         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5619         assert_eq!(local_txn_1[0].input.len(), 1);
5620         check_spends!(local_txn_1[0], chan_1.3);
5621
5622         // We check funding pubkey are unique
5623         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]));
5624         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]));
5625         if from_0_funding_key_0 == from_1_funding_key_0
5626             || from_0_funding_key_0 == from_1_funding_key_1
5627             || from_0_funding_key_1 == from_1_funding_key_0
5628             || from_0_funding_key_1 == from_1_funding_key_1 {
5629                 panic!("Funding pubkeys aren't unique");
5630         }
5631
5632         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5633         mine_transaction(&nodes[0], &local_txn_1[0]);
5634         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5635         check_closed_broadcast!(nodes[0], true);
5636         check_added_monitors!(nodes[0], 1);
5637         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5638
5639         let htlc_timeout = {
5640                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5641                 assert_eq!(node_txn[1].input.len(), 1);
5642                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5643                 check_spends!(node_txn[1], local_txn_1[0]);
5644                 node_txn[1].clone()
5645         };
5646
5647         mine_transaction(&nodes[0], &htlc_timeout);
5648         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5649         expect_payment_failed!(nodes[0], our_payment_hash, true);
5650
5651         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5652         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5653         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5654         assert_eq!(spend_txn.len(), 3);
5655         check_spends!(spend_txn[0], local_txn_1[0]);
5656         assert_eq!(spend_txn[1].input.len(), 1);
5657         check_spends!(spend_txn[1], htlc_timeout);
5658         assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5659         assert_eq!(spend_txn[2].input.len(), 2);
5660         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5661         assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5662                 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5663 }
5664
5665 #[test]
5666 fn test_static_output_closing_tx() {
5667         let chanmon_cfgs = create_chanmon_cfgs(2);
5668         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5669         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5670         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5671
5672         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5673
5674         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5675         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5676
5677         mine_transaction(&nodes[0], &closing_tx);
5678         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5679         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5680
5681         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5682         assert_eq!(spend_txn.len(), 1);
5683         check_spends!(spend_txn[0], closing_tx);
5684
5685         mine_transaction(&nodes[1], &closing_tx);
5686         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5687         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5688
5689         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5690         assert_eq!(spend_txn.len(), 1);
5691         check_spends!(spend_txn[0], closing_tx);
5692 }
5693
5694 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5695         let chanmon_cfgs = create_chanmon_cfgs(2);
5696         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5697         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5698         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5699         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5700
5701         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5702
5703         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5704         // present in B's local commitment transaction, but none of A's commitment transactions.
5705         assert!(nodes[1].node.claim_funds(our_payment_preimage));
5706         check_added_monitors!(nodes[1], 1);
5707
5708         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5709         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5710         let events = nodes[0].node.get_and_clear_pending_events();
5711         assert_eq!(events.len(), 1);
5712         match events[0] {
5713                 Event::PaymentSent { payment_preimage, payment_hash } => {
5714                         assert_eq!(payment_preimage, our_payment_preimage);
5715                         assert_eq!(payment_hash, our_payment_hash);
5716                 },
5717                 _ => panic!("Unexpected event"),
5718         }
5719
5720         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5721         check_added_monitors!(nodes[0], 1);
5722         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5723         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5724         check_added_monitors!(nodes[1], 1);
5725
5726         let starting_block = nodes[1].best_block_info();
5727         let mut block = Block {
5728                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5729                 txdata: vec![],
5730         };
5731         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5732                 connect_block(&nodes[1], &block);
5733                 block.header.prev_blockhash = block.block_hash();
5734         }
5735         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5736         check_closed_broadcast!(nodes[1], true);
5737         check_added_monitors!(nodes[1], 1);
5738         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5739 }
5740
5741 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5742         let chanmon_cfgs = create_chanmon_cfgs(2);
5743         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5744         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5745         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5746         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5747
5748         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5749         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5750         check_added_monitors!(nodes[0], 1);
5751
5752         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5753
5754         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5755         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5756         // to "time out" the HTLC.
5757
5758         let starting_block = nodes[1].best_block_info();
5759         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5760
5761         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5762                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5763                 header.prev_blockhash = header.block_hash();
5764         }
5765         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5766         check_closed_broadcast!(nodes[0], true);
5767         check_added_monitors!(nodes[0], 1);
5768         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5769 }
5770
5771 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5772         let chanmon_cfgs = create_chanmon_cfgs(3);
5773         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5774         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5775         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5776         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5777
5778         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5779         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5780         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5781         // actually revoked.
5782         let htlc_value = if use_dust { 50000 } else { 3000000 };
5783         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5784         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5785         expect_pending_htlcs_forwardable!(nodes[1]);
5786         check_added_monitors!(nodes[1], 1);
5787
5788         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5789         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5790         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5791         check_added_monitors!(nodes[0], 1);
5792         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5793         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5794         check_added_monitors!(nodes[1], 1);
5795         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5796         check_added_monitors!(nodes[1], 1);
5797         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5798
5799         if check_revoke_no_close {
5800                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5801                 check_added_monitors!(nodes[0], 1);
5802         }
5803
5804         let starting_block = nodes[1].best_block_info();
5805         let mut block = Block {
5806                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5807                 txdata: vec![],
5808         };
5809         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5810                 connect_block(&nodes[0], &block);
5811                 block.header.prev_blockhash = block.block_hash();
5812         }
5813         if !check_revoke_no_close {
5814                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5815                 check_closed_broadcast!(nodes[0], true);
5816                 check_added_monitors!(nodes[0], 1);
5817                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5818         } else {
5819                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5820         }
5821 }
5822
5823 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5824 // There are only a few cases to test here:
5825 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5826 //    broadcastable commitment transactions result in channel closure,
5827 //  * its included in an unrevoked-but-previous remote commitment transaction,
5828 //  * its included in the latest remote or local commitment transactions.
5829 // We test each of the three possible commitment transactions individually and use both dust and
5830 // non-dust HTLCs.
5831 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5832 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5833 // tested for at least one of the cases in other tests.
5834 #[test]
5835 fn htlc_claim_single_commitment_only_a() {
5836         do_htlc_claim_local_commitment_only(true);
5837         do_htlc_claim_local_commitment_only(false);
5838
5839         do_htlc_claim_current_remote_commitment_only(true);
5840         do_htlc_claim_current_remote_commitment_only(false);
5841 }
5842
5843 #[test]
5844 fn htlc_claim_single_commitment_only_b() {
5845         do_htlc_claim_previous_remote_commitment_only(true, false);
5846         do_htlc_claim_previous_remote_commitment_only(false, false);
5847         do_htlc_claim_previous_remote_commitment_only(true, true);
5848         do_htlc_claim_previous_remote_commitment_only(false, true);
5849 }
5850
5851 #[test]
5852 #[should_panic]
5853 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5854         let chanmon_cfgs = create_chanmon_cfgs(2);
5855         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5856         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5857         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5858         //Force duplicate channel ids
5859         for node in nodes.iter() {
5860                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5861         }
5862
5863         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5864         let channel_value_satoshis=10000;
5865         let push_msat=10001;
5866         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5867         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5868         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5869
5870         //Create a second channel with a channel_id collision
5871         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5872 }
5873
5874 #[test]
5875 fn bolt2_open_channel_sending_node_checks_part2() {
5876         let chanmon_cfgs = create_chanmon_cfgs(2);
5877         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5878         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5879         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5880
5881         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5882         let channel_value_satoshis=2^24;
5883         let push_msat=10001;
5884         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5885
5886         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5887         let channel_value_satoshis=10000;
5888         // Test when push_msat is equal to 1000 * funding_satoshis.
5889         let push_msat=1000*channel_value_satoshis+1;
5890         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5891
5892         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5893         let channel_value_satoshis=10000;
5894         let push_msat=10001;
5895         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
5896         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5897         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5898
5899         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5900         // 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
5901         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5902
5903         // 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.
5904         assert!(BREAKDOWN_TIMEOUT>0);
5905         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5906
5907         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5908         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5909         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5910
5911         // 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.
5912         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5913         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5914         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5915         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5916         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5917 }
5918
5919 #[test]
5920 fn bolt2_open_channel_sane_dust_limit() {
5921         let chanmon_cfgs = create_chanmon_cfgs(2);
5922         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5923         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5924         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5925
5926         let channel_value_satoshis=1000000;
5927         let push_msat=10001;
5928         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5929         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5930         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5931         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5932
5933         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5934         let events = nodes[1].node.get_and_clear_pending_msg_events();
5935         let err_msg = match events[0] {
5936                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5937                         msg.clone()
5938                 },
5939                 _ => panic!("Unexpected event"),
5940         };
5941         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5942 }
5943
5944 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5945 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5946 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5947 // is no longer affordable once it's freed.
5948 #[test]
5949 fn test_fail_holding_cell_htlc_upon_free() {
5950         let chanmon_cfgs = create_chanmon_cfgs(2);
5951         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5952         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5953         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5954         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5955
5956         // First nodes[0] generates an update_fee, setting the channel's
5957         // pending_update_fee.
5958         {
5959                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5960                 *feerate_lock += 20;
5961         }
5962         nodes[0].node.timer_tick_occurred();
5963         check_added_monitors!(nodes[0], 1);
5964
5965         let events = nodes[0].node.get_and_clear_pending_msg_events();
5966         assert_eq!(events.len(), 1);
5967         let (update_msg, commitment_signed) = match events[0] {
5968                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5969                         (update_fee.as_ref(), commitment_signed)
5970                 },
5971                 _ => panic!("Unexpected event"),
5972         };
5973
5974         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5975
5976         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5977         let channel_reserve = chan_stat.channel_reserve_msat;
5978         let feerate = get_feerate!(nodes[0], chan.2);
5979
5980         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5981         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5982         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5983
5984         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5985         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
5986         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5987         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5988
5989         // Flush the pending fee update.
5990         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5991         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5992         check_added_monitors!(nodes[1], 1);
5993         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5994         check_added_monitors!(nodes[0], 1);
5995
5996         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5997         // HTLC, but now that the fee has been raised the payment will now fail, causing
5998         // us to surface its failure to the user.
5999         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6000         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6001         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);
6002         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 {}",
6003                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6004         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6005
6006         // Check that the payment failed to be sent out.
6007         let events = nodes[0].node.get_and_clear_pending_events();
6008         assert_eq!(events.len(), 1);
6009         match &events[0] {
6010                 &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 } => {
6011                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6012                         assert_eq!(*rejected_by_dest, false);
6013                         assert_eq!(*all_paths_failed, true);
6014                         assert_eq!(*network_update, None);
6015                         assert_eq!(*short_channel_id, None);
6016                         assert_eq!(*error_code, None);
6017                         assert_eq!(*error_data, None);
6018                 },
6019                 _ => panic!("Unexpected event"),
6020         }
6021 }
6022
6023 // Test that if multiple HTLCs are released from the holding cell and one is
6024 // valid but the other is no longer valid upon release, the valid HTLC can be
6025 // successfully completed while the other one fails as expected.
6026 #[test]
6027 fn test_free_and_fail_holding_cell_htlcs() {
6028         let chanmon_cfgs = create_chanmon_cfgs(2);
6029         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6030         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6031         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6032         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6033
6034         // First nodes[0] generates an update_fee, setting the channel's
6035         // pending_update_fee.
6036         {
6037                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6038                 *feerate_lock += 200;
6039         }
6040         nodes[0].node.timer_tick_occurred();
6041         check_added_monitors!(nodes[0], 1);
6042
6043         let events = nodes[0].node.get_and_clear_pending_msg_events();
6044         assert_eq!(events.len(), 1);
6045         let (update_msg, commitment_signed) = match events[0] {
6046                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6047                         (update_fee.as_ref(), commitment_signed)
6048                 },
6049                 _ => panic!("Unexpected event"),
6050         };
6051
6052         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6053
6054         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6055         let channel_reserve = chan_stat.channel_reserve_msat;
6056         let feerate = get_feerate!(nodes[0], chan.2);
6057
6058         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6059         let amt_1 = 20000;
6060         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6061         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6062         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6063
6064         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6065         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6066         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6067         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6068         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6069         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6070         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6071
6072         // Flush the pending fee update.
6073         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6074         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6075         check_added_monitors!(nodes[1], 1);
6076         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6077         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6078         check_added_monitors!(nodes[0], 2);
6079
6080         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6081         // but now that the fee has been raised the second payment will now fail, causing us
6082         // to surface its failure to the user. The first payment should succeed.
6083         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6084         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6085         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);
6086         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 {}",
6087                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6088         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6089
6090         // Check that the second payment failed to be sent out.
6091         let events = nodes[0].node.get_and_clear_pending_events();
6092         assert_eq!(events.len(), 1);
6093         match &events[0] {
6094                 &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 } => {
6095                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6096                         assert_eq!(*rejected_by_dest, false);
6097                         assert_eq!(*all_paths_failed, true);
6098                         assert_eq!(*network_update, None);
6099                         assert_eq!(*short_channel_id, None);
6100                         assert_eq!(*error_code, None);
6101                         assert_eq!(*error_data, None);
6102                 },
6103                 _ => panic!("Unexpected event"),
6104         }
6105
6106         // Complete the first payment and the RAA from the fee update.
6107         let (payment_event, send_raa_event) = {
6108                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6109                 assert_eq!(msgs.len(), 2);
6110                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6111         };
6112         let raa = match send_raa_event {
6113                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6114                 _ => panic!("Unexpected event"),
6115         };
6116         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6117         check_added_monitors!(nodes[1], 1);
6118         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6119         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6120         let events = nodes[1].node.get_and_clear_pending_events();
6121         assert_eq!(events.len(), 1);
6122         match events[0] {
6123                 Event::PendingHTLCsForwardable { .. } => {},
6124                 _ => panic!("Unexpected event"),
6125         }
6126         nodes[1].node.process_pending_htlc_forwards();
6127         let events = nodes[1].node.get_and_clear_pending_events();
6128         assert_eq!(events.len(), 1);
6129         match events[0] {
6130                 Event::PaymentReceived { .. } => {},
6131                 _ => panic!("Unexpected event"),
6132         }
6133         nodes[1].node.claim_funds(payment_preimage_1);
6134         check_added_monitors!(nodes[1], 1);
6135         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6136         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6137         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6138         let events = nodes[0].node.get_and_clear_pending_events();
6139         assert_eq!(events.len(), 1);
6140         match events[0] {
6141                 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
6142                         assert_eq!(*payment_preimage, payment_preimage_1);
6143                         assert_eq!(*payment_hash, payment_hash_1);
6144                 }
6145                 _ => panic!("Unexpected event"),
6146         }
6147 }
6148
6149 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6150 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6151 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6152 // once it's freed.
6153 #[test]
6154 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6155         let chanmon_cfgs = create_chanmon_cfgs(3);
6156         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6157         // When this test was written, the default base fee floated based on the HTLC count.
6158         // It is now fixed, so we simply set the fee to the expected value here.
6159         let mut config = test_default_channel_config();
6160         config.channel_options.forwarding_fee_base_msat = 196;
6161         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6162         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6163         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6164         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6165
6166         // First nodes[1] generates an update_fee, setting the channel's
6167         // pending_update_fee.
6168         {
6169                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6170                 *feerate_lock += 20;
6171         }
6172         nodes[1].node.timer_tick_occurred();
6173         check_added_monitors!(nodes[1], 1);
6174
6175         let events = nodes[1].node.get_and_clear_pending_msg_events();
6176         assert_eq!(events.len(), 1);
6177         let (update_msg, commitment_signed) = match events[0] {
6178                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6179                         (update_fee.as_ref(), commitment_signed)
6180                 },
6181                 _ => panic!("Unexpected event"),
6182         };
6183
6184         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6185
6186         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6187         let channel_reserve = chan_stat.channel_reserve_msat;
6188         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6189
6190         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6191         let feemsat = 239;
6192         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6193         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6194         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6195         let payment_event = {
6196                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6197                 check_added_monitors!(nodes[0], 1);
6198
6199                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6200                 assert_eq!(events.len(), 1);
6201
6202                 SendEvent::from_event(events.remove(0))
6203         };
6204         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6205         check_added_monitors!(nodes[1], 0);
6206         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6207         expect_pending_htlcs_forwardable!(nodes[1]);
6208
6209         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6210         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6211
6212         // Flush the pending fee update.
6213         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6214         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6215         check_added_monitors!(nodes[2], 1);
6216         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6217         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6218         check_added_monitors!(nodes[1], 2);
6219
6220         // A final RAA message is generated to finalize the fee update.
6221         let events = nodes[1].node.get_and_clear_pending_msg_events();
6222         assert_eq!(events.len(), 1);
6223
6224         let raa_msg = match &events[0] {
6225                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6226                         msg.clone()
6227                 },
6228                 _ => panic!("Unexpected event"),
6229         };
6230
6231         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6232         check_added_monitors!(nodes[2], 1);
6233         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6234
6235         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6236         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6237         assert_eq!(process_htlc_forwards_event.len(), 1);
6238         match &process_htlc_forwards_event[0] {
6239                 &Event::PendingHTLCsForwardable { .. } => {},
6240                 _ => panic!("Unexpected event"),
6241         }
6242
6243         // In response, we call ChannelManager's process_pending_htlc_forwards
6244         nodes[1].node.process_pending_htlc_forwards();
6245         check_added_monitors!(nodes[1], 1);
6246
6247         // This causes the HTLC to be failed backwards.
6248         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6249         assert_eq!(fail_event.len(), 1);
6250         let (fail_msg, commitment_signed) = match &fail_event[0] {
6251                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6252                         assert_eq!(updates.update_add_htlcs.len(), 0);
6253                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6254                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6255                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6256                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6257                 },
6258                 _ => panic!("Unexpected event"),
6259         };
6260
6261         // Pass the failure messages back to nodes[0].
6262         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6263         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6264
6265         // Complete the HTLC failure+removal process.
6266         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6267         check_added_monitors!(nodes[0], 1);
6268         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6269         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6270         check_added_monitors!(nodes[1], 2);
6271         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6272         assert_eq!(final_raa_event.len(), 1);
6273         let raa = match &final_raa_event[0] {
6274                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6275                 _ => panic!("Unexpected event"),
6276         };
6277         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6278         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6279         check_added_monitors!(nodes[0], 1);
6280 }
6281
6282 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6283 // 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.
6284 //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.
6285
6286 #[test]
6287 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6288         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6289         let chanmon_cfgs = create_chanmon_cfgs(2);
6290         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6291         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6292         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6293         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6294
6295         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6296         route.paths[0][0].fee_msat = 100;
6297
6298         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6299                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6300         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6301         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6302 }
6303
6304 #[test]
6305 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6306         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6307         let chanmon_cfgs = create_chanmon_cfgs(2);
6308         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6309         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6310         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6311         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6312
6313         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6314         route.paths[0][0].fee_msat = 0;
6315         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6316                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6317
6318         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6319         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6320 }
6321
6322 #[test]
6323 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6324         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6325         let chanmon_cfgs = create_chanmon_cfgs(2);
6326         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6327         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6328         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6329         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6330
6331         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6332         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6333         check_added_monitors!(nodes[0], 1);
6334         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6335         updates.update_add_htlcs[0].amount_msat = 0;
6336
6337         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6338         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6339         check_closed_broadcast!(nodes[1], true).unwrap();
6340         check_added_monitors!(nodes[1], 1);
6341         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6342 }
6343
6344 #[test]
6345 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6346         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6347         //It is enforced when constructing a route.
6348         let chanmon_cfgs = create_chanmon_cfgs(2);
6349         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6350         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6351         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6352         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6353
6354         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], vec![], 100000000, 500000001);
6355         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6356                 assert_eq!(err, &"Channel CLTV overflowed?"));
6357 }
6358
6359 #[test]
6360 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6361         //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.
6362         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6363         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6364         let chanmon_cfgs = create_chanmon_cfgs(2);
6365         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6366         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6367         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6368         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6369         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6370
6371         for i in 0..max_accepted_htlcs {
6372                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6373                 let payment_event = {
6374                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6375                         check_added_monitors!(nodes[0], 1);
6376
6377                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6378                         assert_eq!(events.len(), 1);
6379                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6380                                 assert_eq!(htlcs[0].htlc_id, i);
6381                         } else {
6382                                 assert!(false);
6383                         }
6384                         SendEvent::from_event(events.remove(0))
6385                 };
6386                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6387                 check_added_monitors!(nodes[1], 0);
6388                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6389
6390                 expect_pending_htlcs_forwardable!(nodes[1]);
6391                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6392         }
6393         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6394         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6395                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6396
6397         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6398         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6399 }
6400
6401 #[test]
6402 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6403         //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.
6404         let chanmon_cfgs = create_chanmon_cfgs(2);
6405         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6406         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6407         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6408         let channel_value = 100000;
6409         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6410         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6411
6412         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6413
6414         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6415         // Manually create a route over our max in flight (which our router normally automatically
6416         // limits us to.
6417         route.paths[0][0].fee_msat =  max_in_flight + 1;
6418         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6419                 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)));
6420
6421         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6422         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);
6423
6424         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6425 }
6426
6427 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6428 #[test]
6429 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6430         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6431         let chanmon_cfgs = create_chanmon_cfgs(2);
6432         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6433         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6434         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6435         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6436         let htlc_minimum_msat: u64;
6437         {
6438                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6439                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6440                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6441         }
6442
6443         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6444         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6445         check_added_monitors!(nodes[0], 1);
6446         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6447         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6448         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6449         assert!(nodes[1].node.list_channels().is_empty());
6450         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6451         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()));
6452         check_added_monitors!(nodes[1], 1);
6453         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6454 }
6455
6456 #[test]
6457 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6458         //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
6459         let chanmon_cfgs = create_chanmon_cfgs(2);
6460         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6461         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6462         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6463         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6464
6465         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6466         let channel_reserve = chan_stat.channel_reserve_msat;
6467         let feerate = get_feerate!(nodes[0], chan.2);
6468         // The 2* and +1 are for the fee spike reserve.
6469         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6470
6471         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6472         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6473         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6474         check_added_monitors!(nodes[0], 1);
6475         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6476
6477         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6478         // at this time channel-initiatee receivers are not required to enforce that senders
6479         // respect the fee_spike_reserve.
6480         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6481         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6482
6483         assert!(nodes[1].node.list_channels().is_empty());
6484         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6485         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6486         check_added_monitors!(nodes[1], 1);
6487         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6488 }
6489
6490 #[test]
6491 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6492         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6493         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6494         let chanmon_cfgs = create_chanmon_cfgs(2);
6495         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6496         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6497         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6498         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6499
6500         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6501         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6502         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6503         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6504         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6505         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6506
6507         let mut msg = msgs::UpdateAddHTLC {
6508                 channel_id: chan.2,
6509                 htlc_id: 0,
6510                 amount_msat: 1000,
6511                 payment_hash: our_payment_hash,
6512                 cltv_expiry: htlc_cltv,
6513                 onion_routing_packet: onion_packet.clone(),
6514         };
6515
6516         for i in 0..super::channel::OUR_MAX_HTLCS {
6517                 msg.htlc_id = i as u64;
6518                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6519         }
6520         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6521         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6522
6523         assert!(nodes[1].node.list_channels().is_empty());
6524         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6525         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6526         check_added_monitors!(nodes[1], 1);
6527         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6528 }
6529
6530 #[test]
6531 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6532         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6533         let chanmon_cfgs = create_chanmon_cfgs(2);
6534         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6535         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6536         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6537         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6538
6539         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6540         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6541         check_added_monitors!(nodes[0], 1);
6542         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6543         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6544         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6545
6546         assert!(nodes[1].node.list_channels().is_empty());
6547         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6548         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6549         check_added_monitors!(nodes[1], 1);
6550         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6551 }
6552
6553 #[test]
6554 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6555         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6556         let chanmon_cfgs = create_chanmon_cfgs(2);
6557         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6558         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6559         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6560
6561         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6562         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6563         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6564         check_added_monitors!(nodes[0], 1);
6565         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6566         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6567         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6568
6569         assert!(nodes[1].node.list_channels().is_empty());
6570         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6571         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6572         check_added_monitors!(nodes[1], 1);
6573         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6574 }
6575
6576 #[test]
6577 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6578         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6579         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6580         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6581         let chanmon_cfgs = create_chanmon_cfgs(2);
6582         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6583         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6584         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6585
6586         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6587         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6588         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6589         check_added_monitors!(nodes[0], 1);
6590         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6591         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6592
6593         //Disconnect and Reconnect
6594         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6595         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6596         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6597         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6598         assert_eq!(reestablish_1.len(), 1);
6599         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6600         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6601         assert_eq!(reestablish_2.len(), 1);
6602         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6603         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6604         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6605         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6606
6607         //Resend HTLC
6608         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6609         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6610         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6611         check_added_monitors!(nodes[1], 1);
6612         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6613
6614         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6615
6616         assert!(nodes[1].node.list_channels().is_empty());
6617         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6618         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6619         check_added_monitors!(nodes[1], 1);
6620         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6621 }
6622
6623 #[test]
6624 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6625         //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.
6626
6627         let chanmon_cfgs = create_chanmon_cfgs(2);
6628         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6629         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6630         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6631         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6632         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6633         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6634
6635         check_added_monitors!(nodes[0], 1);
6636         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6637         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6638
6639         let update_msg = msgs::UpdateFulfillHTLC{
6640                 channel_id: chan.2,
6641                 htlc_id: 0,
6642                 payment_preimage: our_payment_preimage,
6643         };
6644
6645         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6646
6647         assert!(nodes[0].node.list_channels().is_empty());
6648         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6649         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()));
6650         check_added_monitors!(nodes[0], 1);
6651         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6652 }
6653
6654 #[test]
6655 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6656         //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.
6657
6658         let chanmon_cfgs = create_chanmon_cfgs(2);
6659         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6660         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6661         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6662         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6663
6664         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6665         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6666         check_added_monitors!(nodes[0], 1);
6667         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6668         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6669
6670         let update_msg = msgs::UpdateFailHTLC{
6671                 channel_id: chan.2,
6672                 htlc_id: 0,
6673                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6674         };
6675
6676         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6677
6678         assert!(nodes[0].node.list_channels().is_empty());
6679         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6680         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()));
6681         check_added_monitors!(nodes[0], 1);
6682         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6683 }
6684
6685 #[test]
6686 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6687         //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.
6688
6689         let chanmon_cfgs = create_chanmon_cfgs(2);
6690         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6691         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6692         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6693         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6694
6695         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6696         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6697         check_added_monitors!(nodes[0], 1);
6698         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6699         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6700         let update_msg = msgs::UpdateFailMalformedHTLC{
6701                 channel_id: chan.2,
6702                 htlc_id: 0,
6703                 sha256_of_onion: [1; 32],
6704                 failure_code: 0x8000,
6705         };
6706
6707         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6708
6709         assert!(nodes[0].node.list_channels().is_empty());
6710         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6711         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()));
6712         check_added_monitors!(nodes[0], 1);
6713         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6714 }
6715
6716 #[test]
6717 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6718         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6719
6720         let chanmon_cfgs = create_chanmon_cfgs(2);
6721         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6722         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6723         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6724         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6725
6726         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6727
6728         nodes[1].node.claim_funds(our_payment_preimage);
6729         check_added_monitors!(nodes[1], 1);
6730
6731         let events = nodes[1].node.get_and_clear_pending_msg_events();
6732         assert_eq!(events.len(), 1);
6733         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6734                 match events[0] {
6735                         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, .. } } => {
6736                                 assert!(update_add_htlcs.is_empty());
6737                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6738                                 assert!(update_fail_htlcs.is_empty());
6739                                 assert!(update_fail_malformed_htlcs.is_empty());
6740                                 assert!(update_fee.is_none());
6741                                 update_fulfill_htlcs[0].clone()
6742                         },
6743                         _ => panic!("Unexpected event"),
6744                 }
6745         };
6746
6747         update_fulfill_msg.htlc_id = 1;
6748
6749         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6750
6751         assert!(nodes[0].node.list_channels().is_empty());
6752         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6753         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6754         check_added_monitors!(nodes[0], 1);
6755         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6756 }
6757
6758 #[test]
6759 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6760         //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.
6761
6762         let chanmon_cfgs = create_chanmon_cfgs(2);
6763         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6764         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6765         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6766         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6767
6768         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6769
6770         nodes[1].node.claim_funds(our_payment_preimage);
6771         check_added_monitors!(nodes[1], 1);
6772
6773         let events = nodes[1].node.get_and_clear_pending_msg_events();
6774         assert_eq!(events.len(), 1);
6775         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6776                 match events[0] {
6777                         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, .. } } => {
6778                                 assert!(update_add_htlcs.is_empty());
6779                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6780                                 assert!(update_fail_htlcs.is_empty());
6781                                 assert!(update_fail_malformed_htlcs.is_empty());
6782                                 assert!(update_fee.is_none());
6783                                 update_fulfill_htlcs[0].clone()
6784                         },
6785                         _ => panic!("Unexpected event"),
6786                 }
6787         };
6788
6789         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6790
6791         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6792
6793         assert!(nodes[0].node.list_channels().is_empty());
6794         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6795         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6796         check_added_monitors!(nodes[0], 1);
6797         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6798 }
6799
6800 #[test]
6801 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6802         //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.
6803
6804         let chanmon_cfgs = create_chanmon_cfgs(2);
6805         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6806         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6807         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6808         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6809
6810         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6811         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6812         check_added_monitors!(nodes[0], 1);
6813
6814         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6815         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6816
6817         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6818         check_added_monitors!(nodes[1], 0);
6819         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6820
6821         let events = nodes[1].node.get_and_clear_pending_msg_events();
6822
6823         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6824                 match events[0] {
6825                         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, .. } } => {
6826                                 assert!(update_add_htlcs.is_empty());
6827                                 assert!(update_fulfill_htlcs.is_empty());
6828                                 assert!(update_fail_htlcs.is_empty());
6829                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6830                                 assert!(update_fee.is_none());
6831                                 update_fail_malformed_htlcs[0].clone()
6832                         },
6833                         _ => panic!("Unexpected event"),
6834                 }
6835         };
6836         update_msg.failure_code &= !0x8000;
6837         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6838
6839         assert!(nodes[0].node.list_channels().is_empty());
6840         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6841         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6842         check_added_monitors!(nodes[0], 1);
6843         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6844 }
6845
6846 #[test]
6847 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6848         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6849         //    * 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.
6850
6851         let chanmon_cfgs = create_chanmon_cfgs(3);
6852         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6853         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6854         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6855         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6856         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6857
6858         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6859
6860         //First hop
6861         let mut payment_event = {
6862                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6863                 check_added_monitors!(nodes[0], 1);
6864                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6865                 assert_eq!(events.len(), 1);
6866                 SendEvent::from_event(events.remove(0))
6867         };
6868         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6869         check_added_monitors!(nodes[1], 0);
6870         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6871         expect_pending_htlcs_forwardable!(nodes[1]);
6872         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6873         assert_eq!(events_2.len(), 1);
6874         check_added_monitors!(nodes[1], 1);
6875         payment_event = SendEvent::from_event(events_2.remove(0));
6876         assert_eq!(payment_event.msgs.len(), 1);
6877
6878         //Second Hop
6879         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6880         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6881         check_added_monitors!(nodes[2], 0);
6882         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6883
6884         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6885         assert_eq!(events_3.len(), 1);
6886         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6887                 match events_3[0] {
6888                         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 } } => {
6889                                 assert!(update_add_htlcs.is_empty());
6890                                 assert!(update_fulfill_htlcs.is_empty());
6891                                 assert!(update_fail_htlcs.is_empty());
6892                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6893                                 assert!(update_fee.is_none());
6894                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6895                         },
6896                         _ => panic!("Unexpected event"),
6897                 }
6898         };
6899
6900         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6901
6902         check_added_monitors!(nodes[1], 0);
6903         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6904         expect_pending_htlcs_forwardable!(nodes[1]);
6905         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6906         assert_eq!(events_4.len(), 1);
6907
6908         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6909         match events_4[0] {
6910                 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, .. } } => {
6911                         assert!(update_add_htlcs.is_empty());
6912                         assert!(update_fulfill_htlcs.is_empty());
6913                         assert_eq!(update_fail_htlcs.len(), 1);
6914                         assert!(update_fail_malformed_htlcs.is_empty());
6915                         assert!(update_fee.is_none());
6916                 },
6917                 _ => panic!("Unexpected event"),
6918         };
6919
6920         check_added_monitors!(nodes[1], 1);
6921 }
6922
6923 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6924         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6925         // 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
6926         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6927
6928         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6929         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6930         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6931         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6932         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6933         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6934
6935         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6936
6937         // We route 2 dust-HTLCs between A and B
6938         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6939         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6940         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6941
6942         // Cache one local commitment tx as previous
6943         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6944
6945         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6946         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
6947         check_added_monitors!(nodes[1], 0);
6948         expect_pending_htlcs_forwardable!(nodes[1]);
6949         check_added_monitors!(nodes[1], 1);
6950
6951         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6952         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6953         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6954         check_added_monitors!(nodes[0], 1);
6955
6956         // Cache one local commitment tx as lastest
6957         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6958
6959         let events = nodes[0].node.get_and_clear_pending_msg_events();
6960         match events[0] {
6961                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6962                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6963                 },
6964                 _ => panic!("Unexpected event"),
6965         }
6966         match events[1] {
6967                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6968                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6969                 },
6970                 _ => panic!("Unexpected event"),
6971         }
6972
6973         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6974         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6975         if announce_latest {
6976                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6977         } else {
6978                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6979         }
6980
6981         check_closed_broadcast!(nodes[0], true);
6982         check_added_monitors!(nodes[0], 1);
6983         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6984
6985         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6986         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6987         let events = nodes[0].node.get_and_clear_pending_events();
6988         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6989         assert_eq!(events.len(), 2);
6990         let mut first_failed = false;
6991         for event in events {
6992                 match event {
6993                         Event::PaymentPathFailed { payment_hash, .. } => {
6994                                 if payment_hash == payment_hash_1 {
6995                                         assert!(!first_failed);
6996                                         first_failed = true;
6997                                 } else {
6998                                         assert_eq!(payment_hash, payment_hash_2);
6999                                 }
7000                         }
7001                         _ => panic!("Unexpected event"),
7002                 }
7003         }
7004 }
7005
7006 #[test]
7007 fn test_failure_delay_dust_htlc_local_commitment() {
7008         do_test_failure_delay_dust_htlc_local_commitment(true);
7009         do_test_failure_delay_dust_htlc_local_commitment(false);
7010 }
7011
7012 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7013         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7014         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7015         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7016         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7017         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7018         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7019
7020         let chanmon_cfgs = create_chanmon_cfgs(3);
7021         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7022         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7023         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7024         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7025
7026         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7027
7028         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7029         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7030
7031         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7032         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7033
7034         // We revoked bs_commitment_tx
7035         if revoked {
7036                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7037                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7038         }
7039
7040         let mut timeout_tx = Vec::new();
7041         if local {
7042                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7043                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7044                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7045                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7046                 expect_payment_failed!(nodes[0], dust_hash, true);
7047
7048                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7049                 check_closed_broadcast!(nodes[0], true);
7050                 check_added_monitors!(nodes[0], 1);
7051                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7052                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7053                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7054                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7055                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7056                 mine_transaction(&nodes[0], &timeout_tx[0]);
7057                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7058                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7059         } else {
7060                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7061                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7062                 check_closed_broadcast!(nodes[0], true);
7063                 check_added_monitors!(nodes[0], 1);
7064                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7065                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7066                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7067                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7068                 if !revoked {
7069                         expect_payment_failed!(nodes[0], dust_hash, true);
7070                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7071                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7072                         mine_transaction(&nodes[0], &timeout_tx[0]);
7073                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7074                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7075                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7076                 } else {
7077                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7078                         // commitment tx
7079                         let events = nodes[0].node.get_and_clear_pending_events();
7080                         assert_eq!(events.len(), 2);
7081                         let first;
7082                         match events[0] {
7083                                 Event::PaymentPathFailed { payment_hash, .. } => {
7084                                         if payment_hash == dust_hash { first = true; }
7085                                         else { first = false; }
7086                                 },
7087                                 _ => panic!("Unexpected event"),
7088                         }
7089                         match events[1] {
7090                                 Event::PaymentPathFailed { payment_hash, .. } => {
7091                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7092                                         else { assert_eq!(payment_hash, dust_hash); }
7093                                 },
7094                                 _ => panic!("Unexpected event"),
7095                         }
7096                 }
7097         }
7098 }
7099
7100 #[test]
7101 fn test_sweep_outbound_htlc_failure_update() {
7102         do_test_sweep_outbound_htlc_failure_update(false, true);
7103         do_test_sweep_outbound_htlc_failure_update(false, false);
7104         do_test_sweep_outbound_htlc_failure_update(true, false);
7105 }
7106
7107 #[test]
7108 fn test_user_configurable_csv_delay() {
7109         // We test our channel constructors yield errors when we pass them absurd csv delay
7110
7111         let mut low_our_to_self_config = UserConfig::default();
7112         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7113         let mut high_their_to_self_config = UserConfig::default();
7114         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7115         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7116         let chanmon_cfgs = create_chanmon_cfgs(2);
7117         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7118         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7119         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7120
7121         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7122         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) {
7123                 match error {
7124                         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())); },
7125                         _ => panic!("Unexpected event"),
7126                 }
7127         } else { assert!(false) }
7128
7129         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7130         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7131         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7132         open_channel.to_self_delay = 200;
7133         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) {
7134                 match error {
7135                         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()));  },
7136                         _ => panic!("Unexpected event"),
7137                 }
7138         } else { assert!(false); }
7139
7140         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7141         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7142         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()));
7143         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7144         accept_channel.to_self_delay = 200;
7145         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7146         let reason_msg;
7147         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7148                 match action {
7149                         &ErrorAction::SendErrorMessage { ref msg } => {
7150                                 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()));
7151                                 reason_msg = msg.data.clone();
7152                         },
7153                         _ => { panic!(); }
7154                 }
7155         } else { panic!(); }
7156         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7157
7158         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7159         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7160         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7161         open_channel.to_self_delay = 200;
7162         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) {
7163                 match error {
7164                         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())); },
7165                         _ => panic!("Unexpected event"),
7166                 }
7167         } else { assert!(false); }
7168 }
7169
7170 #[test]
7171 fn test_data_loss_protect() {
7172         // We want to be sure that :
7173         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7174         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7175         // * we close channel in case of detecting other being fallen behind
7176         // * we are able to claim our own outputs thanks to to_remote being static
7177         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7178         let persister;
7179         let logger;
7180         let fee_estimator;
7181         let tx_broadcaster;
7182         let chain_source;
7183         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7184         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7185         // during signing due to revoked tx
7186         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7187         let keys_manager = &chanmon_cfgs[0].keys_manager;
7188         let monitor;
7189         let node_state_0;
7190         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7191         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7192         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7193
7194         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7195
7196         // Cache node A state before any channel update
7197         let previous_node_state = nodes[0].node.encode();
7198         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7199         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7200
7201         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7202         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7203
7204         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7205         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7206
7207         // Restore node A from previous state
7208         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7209         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7210         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7211         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7212         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7213         persister = test_utils::TestPersister::new();
7214         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7215         node_state_0 = {
7216                 let mut channel_monitors = HashMap::new();
7217                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7218                 <(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 {
7219                         keys_manager: keys_manager,
7220                         fee_estimator: &fee_estimator,
7221                         chain_monitor: &monitor,
7222                         logger: &logger,
7223                         tx_broadcaster: &tx_broadcaster,
7224                         default_config: UserConfig::default(),
7225                         channel_monitors,
7226                 }).unwrap().1
7227         };
7228         nodes[0].node = &node_state_0;
7229         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7230         nodes[0].chain_monitor = &monitor;
7231         nodes[0].chain_source = &chain_source;
7232
7233         check_added_monitors!(nodes[0], 1);
7234
7235         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7236         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7237
7238         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7239
7240         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7241         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7242         check_added_monitors!(nodes[0], 1);
7243
7244         {
7245                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7246                 assert_eq!(node_txn.len(), 0);
7247         }
7248
7249         let mut reestablish_1 = Vec::with_capacity(1);
7250         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7251                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7252                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7253                         reestablish_1.push(msg.clone());
7254                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7255                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7256                         match action {
7257                                 &ErrorAction::SendErrorMessage { ref msg } => {
7258                                         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");
7259                                 },
7260                                 _ => panic!("Unexpected event!"),
7261                         }
7262                 } else {
7263                         panic!("Unexpected event")
7264                 }
7265         }
7266
7267         // Check we close channel detecting A is fallen-behind
7268         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7269         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7270         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7271         check_added_monitors!(nodes[1], 1);
7272
7273         // Check A is able to claim to_remote output
7274         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7275         assert_eq!(node_txn.len(), 1);
7276         check_spends!(node_txn[0], chan.3);
7277         assert_eq!(node_txn[0].output.len(), 2);
7278         mine_transaction(&nodes[0], &node_txn[0]);
7279         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7280         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() });
7281         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7282         assert_eq!(spend_txn.len(), 1);
7283         check_spends!(spend_txn[0], node_txn[0]);
7284 }
7285
7286 #[test]
7287 fn test_check_htlc_underpaying() {
7288         // Send payment through A -> B but A is maliciously
7289         // sending a probe payment (i.e less than expected value0
7290         // to B, B should refuse payment.
7291
7292         let chanmon_cfgs = create_chanmon_cfgs(2);
7293         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7294         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7295         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7296
7297         // Create some initial channels
7298         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7299
7300         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();
7301         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7302         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, 0).unwrap();
7303         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7304         check_added_monitors!(nodes[0], 1);
7305
7306         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7307         assert_eq!(events.len(), 1);
7308         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7309         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7310         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7311
7312         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7313         // and then will wait a second random delay before failing the HTLC back:
7314         expect_pending_htlcs_forwardable!(nodes[1]);
7315         expect_pending_htlcs_forwardable!(nodes[1]);
7316
7317         // Node 3 is expecting payment of 100_000 but received 10_000,
7318         // it should fail htlc like we didn't know the preimage.
7319         nodes[1].node.process_pending_htlc_forwards();
7320
7321         let events = nodes[1].node.get_and_clear_pending_msg_events();
7322         assert_eq!(events.len(), 1);
7323         let (update_fail_htlc, commitment_signed) = match events[0] {
7324                 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 } } => {
7325                         assert!(update_add_htlcs.is_empty());
7326                         assert!(update_fulfill_htlcs.is_empty());
7327                         assert_eq!(update_fail_htlcs.len(), 1);
7328                         assert!(update_fail_malformed_htlcs.is_empty());
7329                         assert!(update_fee.is_none());
7330                         (update_fail_htlcs[0].clone(), commitment_signed)
7331                 },
7332                 _ => panic!("Unexpected event"),
7333         };
7334         check_added_monitors!(nodes[1], 1);
7335
7336         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7337         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7338
7339         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7340         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7341         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7342         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7343 }
7344
7345 #[test]
7346 fn test_announce_disable_channels() {
7347         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7348         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7349
7350         let chanmon_cfgs = create_chanmon_cfgs(2);
7351         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7352         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7353         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7354
7355         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7356         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7357         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7358
7359         // Disconnect peers
7360         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7361         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7362
7363         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7364         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7365         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7366         assert_eq!(msg_events.len(), 3);
7367         let mut chans_disabled: HashSet<u64> = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7368         for e in msg_events {
7369                 match e {
7370                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7371                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7372                                 // Check that each channel gets updated exactly once
7373                                 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7374                                         panic!("Generated ChannelUpdate for wrong chan!");
7375                                 }
7376                         },
7377                         _ => panic!("Unexpected event"),
7378                 }
7379         }
7380         // Reconnect peers
7381         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7382         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7383         assert_eq!(reestablish_1.len(), 3);
7384         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7385         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7386         assert_eq!(reestablish_2.len(), 3);
7387
7388         // Reestablish chan_1
7389         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7390         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7391         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7392         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7393         // Reestablish chan_2
7394         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7395         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7396         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7397         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7398         // Reestablish chan_3
7399         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7400         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7401         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7402         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7403
7404         nodes[0].node.timer_tick_occurred();
7405         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7406         nodes[0].node.timer_tick_occurred();
7407         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7408         assert_eq!(msg_events.len(), 3);
7409         chans_disabled = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7410         for e in msg_events {
7411                 match e {
7412                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7413                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7414                                 // Check that each channel gets updated exactly once
7415                                 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7416                                         panic!("Generated ChannelUpdate for wrong chan!");
7417                                 }
7418                         },
7419                         _ => panic!("Unexpected event"),
7420                 }
7421         }
7422 }
7423
7424 #[test]
7425 fn test_priv_forwarding_rejection() {
7426         // If we have a private channel with outbound liquidity, and
7427         // UserConfig::accept_forwards_to_priv_channels is set to false, we should reject any attempts
7428         // to forward through that channel.
7429         let chanmon_cfgs = create_chanmon_cfgs(3);
7430         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7431         let mut no_announce_cfg = test_default_channel_config();
7432         no_announce_cfg.channel_options.announced_channel = false;
7433         no_announce_cfg.accept_forwards_to_priv_channels = false;
7434         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]);
7435         let persister: test_utils::TestPersister;
7436         let new_chain_monitor: test_utils::TestChainMonitor;
7437         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
7438         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7439
7440         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;
7441
7442         // Note that the create_*_chan functions in utils requires announcement_signatures, which we do
7443         // not send for private channels.
7444         nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
7445         let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[2].node.get_our_node_id());
7446         nodes[2].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
7447         let accept_channel = get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
7448         nodes[1].node.handle_accept_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7449
7450         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[1], 1_000_000, 42);
7451         nodes[1].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
7452         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()));
7453         check_added_monitors!(nodes[2], 1);
7454
7455         let cs_funding_signed = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[1].node.get_our_node_id());
7456         nodes[1].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &cs_funding_signed);
7457         check_added_monitors!(nodes[1], 1);
7458
7459         let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[2].best_block_info().1 + 1);
7460         confirm_transaction_at(&nodes[1], &tx, conf_height);
7461         connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
7462         confirm_transaction_at(&nodes[2], &tx, conf_height);
7463         connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
7464         let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[2].node.get_our_node_id());
7465         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()));
7466         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7467         nodes[2].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
7468         get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7469
7470         assert!(nodes[0].node.list_usable_channels()[0].is_public);
7471         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
7472         assert!(!nodes[2].node.list_usable_channels()[0].is_public);
7473
7474         // We should always be able to forward through nodes[1] as long as its out through a public
7475         // channel:
7476         send_payment(&nodes[2], &[&nodes[1], &nodes[0]], 10_000);
7477
7478         // ... however, if we send to nodes[2], we will have to pass the private channel from nodes[1]
7479         // to nodes[2], which should be rejected:
7480         let route_hint = RouteHint(vec![RouteHintHop {
7481                 src_node_id: nodes[1].node.get_our_node_id(),
7482                 short_channel_id: nodes[2].node.list_channels()[0].short_channel_id.unwrap(),
7483                 fees: RoutingFees { base_msat: 1000, proportional_millionths: 0 },
7484                 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
7485                 htlc_minimum_msat: None,
7486                 htlc_maximum_msat: None,
7487         }]);
7488         let last_hops = vec![&route_hint];
7489         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);
7490
7491         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7492         check_added_monitors!(nodes[0], 1);
7493         let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7494         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7495         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
7496
7497         let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7498         assert!(htlc_fail_updates.update_add_htlcs.is_empty());
7499         assert_eq!(htlc_fail_updates.update_fail_htlcs.len(), 1);
7500         assert!(htlc_fail_updates.update_fail_malformed_htlcs.is_empty());
7501         assert!(htlc_fail_updates.update_fee.is_none());
7502
7503         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
7504         commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, true, true);
7505         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, nodes[2].node.list_channels()[0].short_channel_id.unwrap(), true);
7506
7507         // Now disconnect nodes[1] from its peers and restart with accept_forwards_to_priv_channels set
7508         // to true. Sadly there is currently no way to change it at runtime.
7509
7510         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7511         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7512
7513         let nodes_1_serialized = nodes[1].node.encode();
7514         let mut monitor_a_serialized = test_utils::TestVecWriter(Vec::new());
7515         let mut monitor_b_serialized = test_utils::TestVecWriter(Vec::new());
7516         get_monitor!(nodes[1], chan_id_1).write(&mut monitor_a_serialized).unwrap();
7517         get_monitor!(nodes[1], cs_funding_signed.channel_id).write(&mut monitor_b_serialized).unwrap();
7518
7519         persister = test_utils::TestPersister::new();
7520         let keys_manager = &chanmon_cfgs[1].keys_manager;
7521         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);
7522         nodes[1].chain_monitor = &new_chain_monitor;
7523
7524         let mut monitor_a_read = &monitor_a_serialized.0[..];
7525         let mut monitor_b_read = &monitor_b_serialized.0[..];
7526         let (_, mut monitor_a) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_a_read, keys_manager).unwrap();
7527         let (_, mut monitor_b) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_b_read, keys_manager).unwrap();
7528         assert!(monitor_a_read.is_empty());
7529         assert!(monitor_b_read.is_empty());
7530
7531         no_announce_cfg.accept_forwards_to_priv_channels = true;
7532
7533         let mut nodes_1_read = &nodes_1_serialized[..];
7534         let (_, nodes_1_deserialized_tmp) = {
7535                 let mut channel_monitors = HashMap::new();
7536                 channel_monitors.insert(monitor_a.get_funding_txo().0, &mut monitor_a);
7537                 channel_monitors.insert(monitor_b.get_funding_txo().0, &mut monitor_b);
7538                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
7539                         default_config: no_announce_cfg,
7540                         keys_manager,
7541                         fee_estimator: node_cfgs[1].fee_estimator,
7542                         chain_monitor: nodes[1].chain_monitor,
7543                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
7544                         logger: nodes[1].logger,
7545                         channel_monitors,
7546                 }).unwrap()
7547         };
7548         assert!(nodes_1_read.is_empty());
7549         nodes_1_deserialized = nodes_1_deserialized_tmp;
7550
7551         assert!(nodes[1].chain_monitor.watch_channel(monitor_a.get_funding_txo().0, monitor_a).is_ok());
7552         assert!(nodes[1].chain_monitor.watch_channel(monitor_b.get_funding_txo().0, monitor_b).is_ok());
7553         check_added_monitors!(nodes[1], 2);
7554         nodes[1].node = &nodes_1_deserialized;
7555
7556         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7557         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7558         let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7559         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
7560         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
7561         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7562         get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7563         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
7564
7565         nodes[1].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7566         nodes[2].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7567         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[2].node.get_our_node_id());
7568         let cs_reestablish = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7569         nodes[2].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7570         nodes[1].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &cs_reestablish);
7571         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7572         get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7573
7574         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7575         check_added_monitors!(nodes[0], 1);
7576         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 10_000, our_payment_hash, our_payment_secret);
7577         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage);
7578 }
7579
7580 #[test]
7581 fn test_bump_penalty_txn_on_revoked_commitment() {
7582         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7583         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7584
7585         let chanmon_cfgs = create_chanmon_cfgs(2);
7586         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7587         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7588         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7589
7590         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7591
7592         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7593         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], vec![], 3000000, 30);
7594         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7595
7596         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7597         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7598         assert_eq!(revoked_txn[0].output.len(), 4);
7599         assert_eq!(revoked_txn[0].input.len(), 1);
7600         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7601         let revoked_txid = revoked_txn[0].txid();
7602
7603         let mut penalty_sum = 0;
7604         for outp in revoked_txn[0].output.iter() {
7605                 if outp.script_pubkey.is_v0_p2wsh() {
7606                         penalty_sum += outp.value;
7607                 }
7608         }
7609
7610         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7611         let header_114 = connect_blocks(&nodes[1], 14);
7612
7613         // Actually revoke tx by claiming a HTLC
7614         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7615         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7616         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7617         check_added_monitors!(nodes[1], 1);
7618
7619         // One or more justice tx should have been broadcast, check it
7620         let penalty_1;
7621         let feerate_1;
7622         {
7623                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7624                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7625                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7626                 assert_eq!(node_txn[0].output.len(), 1);
7627                 check_spends!(node_txn[0], revoked_txn[0]);
7628                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7629                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7630                 penalty_1 = node_txn[0].txid();
7631                 node_txn.clear();
7632         };
7633
7634         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7635         connect_blocks(&nodes[1], 15);
7636         let mut penalty_2 = penalty_1;
7637         let mut feerate_2 = 0;
7638         {
7639                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7640                 assert_eq!(node_txn.len(), 1);
7641                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7642                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7643                         assert_eq!(node_txn[0].output.len(), 1);
7644                         check_spends!(node_txn[0], revoked_txn[0]);
7645                         penalty_2 = node_txn[0].txid();
7646                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7647                         assert_ne!(penalty_2, penalty_1);
7648                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7649                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7650                         // Verify 25% bump heuristic
7651                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7652                         node_txn.clear();
7653                 }
7654         }
7655         assert_ne!(feerate_2, 0);
7656
7657         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7658         connect_blocks(&nodes[1], 1);
7659         let penalty_3;
7660         let mut feerate_3 = 0;
7661         {
7662                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7663                 assert_eq!(node_txn.len(), 1);
7664                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7665                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7666                         assert_eq!(node_txn[0].output.len(), 1);
7667                         check_spends!(node_txn[0], revoked_txn[0]);
7668                         penalty_3 = node_txn[0].txid();
7669                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7670                         assert_ne!(penalty_3, penalty_2);
7671                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7672                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7673                         // Verify 25% bump heuristic
7674                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7675                         node_txn.clear();
7676                 }
7677         }
7678         assert_ne!(feerate_3, 0);
7679
7680         nodes[1].node.get_and_clear_pending_events();
7681         nodes[1].node.get_and_clear_pending_msg_events();
7682 }
7683
7684 #[test]
7685 fn test_bump_penalty_txn_on_revoked_htlcs() {
7686         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7687         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7688
7689         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7690         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7691         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7692         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7693         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7694
7695         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7696         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7697         let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph,
7698                 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
7699         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7700         let route = get_route(&nodes[1].node.get_our_node_id(), &nodes[1].net_graph_msg_handler.network_graph,
7701                 &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
7702         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7703
7704         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7705         assert_eq!(revoked_local_txn[0].input.len(), 1);
7706         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7707
7708         // Revoke local commitment tx
7709         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7710
7711         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7712         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7713         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7714         check_closed_broadcast!(nodes[1], true);
7715         check_added_monitors!(nodes[1], 1);
7716         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7717         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7718
7719         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7720         assert_eq!(revoked_htlc_txn.len(), 3);
7721         check_spends!(revoked_htlc_txn[1], chan.3);
7722
7723         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7724         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7725         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7726
7727         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7728         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7729         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7730         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7731
7732         // Broadcast set of revoked txn on A
7733         let hash_128 = connect_blocks(&nodes[0], 40);
7734         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7735         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7736         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7737         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7738         let events = nodes[0].node.get_and_clear_pending_events();
7739         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7740         match events[1] {
7741                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7742                 _ => panic!("Unexpected event"),
7743         }
7744         let first;
7745         let feerate_1;
7746         let penalty_txn;
7747         {
7748                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7749                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7750                 // Verify claim tx are spending revoked HTLC txn
7751
7752                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7753                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7754                 // which are included in the same block (they are broadcasted because we scan the
7755                 // transactions linearly and generate claims as we go, they likely should be removed in the
7756                 // future).
7757                 assert_eq!(node_txn[0].input.len(), 1);
7758                 check_spends!(node_txn[0], revoked_local_txn[0]);
7759                 assert_eq!(node_txn[1].input.len(), 1);
7760                 check_spends!(node_txn[1], revoked_local_txn[0]);
7761                 assert_eq!(node_txn[2].input.len(), 1);
7762                 check_spends!(node_txn[2], revoked_local_txn[0]);
7763
7764                 // Each of the three justice transactions claim a separate (single) output of the three
7765                 // available, which we check here:
7766                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7767                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7768                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7769
7770                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7771                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7772
7773                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7774                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7775                 // a remote commitment tx has already been confirmed).
7776                 check_spends!(node_txn[3], chan.3);
7777
7778                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7779                 // output, checked above).
7780                 assert_eq!(node_txn[4].input.len(), 2);
7781                 assert_eq!(node_txn[4].output.len(), 1);
7782                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7783
7784                 first = node_txn[4].txid();
7785                 // Store both feerates for later comparison
7786                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7787                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7788                 penalty_txn = vec![node_txn[2].clone()];
7789                 node_txn.clear();
7790         }
7791
7792         // Connect one more block to see if bumped penalty are issued for HTLC txn
7793         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7794         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7795         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7796         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7797         {
7798                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7799                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7800
7801                 check_spends!(node_txn[0], revoked_local_txn[0]);
7802                 check_spends!(node_txn[1], revoked_local_txn[0]);
7803                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7804                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7805                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7806                 } else {
7807                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7808                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7809                 }
7810
7811                 node_txn.clear();
7812         };
7813
7814         // Few more blocks to confirm penalty txn
7815         connect_blocks(&nodes[0], 4);
7816         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7817         let header_144 = connect_blocks(&nodes[0], 9);
7818         let node_txn = {
7819                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7820                 assert_eq!(node_txn.len(), 1);
7821
7822                 assert_eq!(node_txn[0].input.len(), 2);
7823                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7824                 // Verify bumped tx is different and 25% bump heuristic
7825                 assert_ne!(first, node_txn[0].txid());
7826                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7827                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7828                 assert!(feerate_2 * 100 > feerate_1 * 125);
7829                 let txn = vec![node_txn[0].clone()];
7830                 node_txn.clear();
7831                 txn
7832         };
7833         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7834         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7835         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7836         connect_blocks(&nodes[0], 20);
7837         {
7838                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7839                 // We verify than no new transaction has been broadcast because previously
7840                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7841                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7842                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7843                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7844                 // up bumped justice generation.
7845                 assert_eq!(node_txn.len(), 0);
7846                 node_txn.clear();
7847         }
7848         check_closed_broadcast!(nodes[0], true);
7849         check_added_monitors!(nodes[0], 1);
7850 }
7851
7852 #[test]
7853 fn test_bump_penalty_txn_on_remote_commitment() {
7854         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7855         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7856
7857         // Create 2 HTLCs
7858         // Provide preimage for one
7859         // Check aggregation
7860
7861         let chanmon_cfgs = create_chanmon_cfgs(2);
7862         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7863         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7864         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7865
7866         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7867         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7868         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7869
7870         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7871         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7872         assert_eq!(remote_txn[0].output.len(), 4);
7873         assert_eq!(remote_txn[0].input.len(), 1);
7874         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7875
7876         // Claim a HTLC without revocation (provide B monitor with preimage)
7877         nodes[1].node.claim_funds(payment_preimage);
7878         mine_transaction(&nodes[1], &remote_txn[0]);
7879         check_added_monitors!(nodes[1], 2);
7880         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7881
7882         // One or more claim tx should have been broadcast, check it
7883         let timeout;
7884         let preimage;
7885         let preimage_bump;
7886         let feerate_timeout;
7887         let feerate_preimage;
7888         {
7889                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7890                 // 9 transactions including:
7891                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7892                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7893                 // 2 * HTLC-Success (one RBF bump we'll check later)
7894                 // 1 * HTLC-Timeout
7895                 assert_eq!(node_txn.len(), 8);
7896                 assert_eq!(node_txn[0].input.len(), 1);
7897                 assert_eq!(node_txn[6].input.len(), 1);
7898                 check_spends!(node_txn[0], remote_txn[0]);
7899                 check_spends!(node_txn[6], remote_txn[0]);
7900                 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7901                 preimage_bump = node_txn[3].clone();
7902
7903                 check_spends!(node_txn[1], chan.3);
7904                 check_spends!(node_txn[2], node_txn[1]);
7905                 assert_eq!(node_txn[1], node_txn[4]);
7906                 assert_eq!(node_txn[2], node_txn[5]);
7907
7908                 timeout = node_txn[6].txid();
7909                 let index = node_txn[6].input[0].previous_output.vout;
7910                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
7911                 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
7912
7913                 preimage = node_txn[0].txid();
7914                 let index = node_txn[0].input[0].previous_output.vout;
7915                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7916                 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7917
7918                 node_txn.clear();
7919         };
7920         assert_ne!(feerate_timeout, 0);
7921         assert_ne!(feerate_preimage, 0);
7922
7923         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7924         connect_blocks(&nodes[1], 15);
7925         {
7926                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7927                 assert_eq!(node_txn.len(), 1);
7928                 assert_eq!(node_txn[0].input.len(), 1);
7929                 assert_eq!(preimage_bump.input.len(), 1);
7930                 check_spends!(node_txn[0], remote_txn[0]);
7931                 check_spends!(preimage_bump, remote_txn[0]);
7932
7933                 let index = preimage_bump.input[0].previous_output.vout;
7934                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7935                 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
7936                 assert!(new_feerate * 100 > feerate_timeout * 125);
7937                 assert_ne!(timeout, preimage_bump.txid());
7938
7939                 let index = node_txn[0].input[0].previous_output.vout;
7940                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7941                 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7942                 assert!(new_feerate * 100 > feerate_preimage * 125);
7943                 assert_ne!(preimage, node_txn[0].txid());
7944
7945                 node_txn.clear();
7946         }
7947
7948         nodes[1].node.get_and_clear_pending_events();
7949         nodes[1].node.get_and_clear_pending_msg_events();
7950 }
7951
7952 #[test]
7953 fn test_counterparty_raa_skip_no_crash() {
7954         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7955         // commitment transaction, we would have happily carried on and provided them the next
7956         // commitment transaction based on one RAA forward. This would probably eventually have led to
7957         // channel closure, but it would not have resulted in funds loss. Still, our
7958         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7959         // check simply that the channel is closed in response to such an RAA, but don't check whether
7960         // we decide to punish our counterparty for revoking their funds (as we don't currently
7961         // implement that).
7962         let chanmon_cfgs = create_chanmon_cfgs(2);
7963         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7964         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7965         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7966         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7967
7968         let mut guard = nodes[0].node.channel_state.lock().unwrap();
7969         let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7970
7971         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7972
7973         // Make signer believe we got a counterparty signature, so that it allows the revocation
7974         keys.get_enforcement_state().last_holder_commitment -= 1;
7975         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7976
7977         // Must revoke without gaps
7978         keys.get_enforcement_state().last_holder_commitment -= 1;
7979         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7980
7981         keys.get_enforcement_state().last_holder_commitment -= 1;
7982         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7983                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7984
7985         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7986                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7987         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7988         check_added_monitors!(nodes[1], 1);
7989         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7990 }
7991
7992 #[test]
7993 fn test_bump_txn_sanitize_tracking_maps() {
7994         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7995         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7996
7997         let chanmon_cfgs = create_chanmon_cfgs(2);
7998         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7999         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8000         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8001
8002         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8003         // Lock HTLC in both directions
8004         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8005         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8006
8007         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8008         assert_eq!(revoked_local_txn[0].input.len(), 1);
8009         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8010
8011         // Revoke local commitment tx
8012         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8013
8014         // Broadcast set of revoked txn on A
8015         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8016         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8017         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8018
8019         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8020         check_closed_broadcast!(nodes[0], true);
8021         check_added_monitors!(nodes[0], 1);
8022         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8023         let penalty_txn = {
8024                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8025                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8026                 check_spends!(node_txn[0], revoked_local_txn[0]);
8027                 check_spends!(node_txn[1], revoked_local_txn[0]);
8028                 check_spends!(node_txn[2], revoked_local_txn[0]);
8029                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8030                 node_txn.clear();
8031                 penalty_txn
8032         };
8033         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8034         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8035         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8036         {
8037                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8038                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8039                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8040         }
8041 }
8042
8043 #[test]
8044 fn test_override_channel_config() {
8045         let chanmon_cfgs = create_chanmon_cfgs(2);
8046         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8047         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8048         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8049
8050         // Node0 initiates a channel to node1 using the override config.
8051         let mut override_config = UserConfig::default();
8052         override_config.own_channel_config.our_to_self_delay = 200;
8053
8054         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8055
8056         // Assert the channel created by node0 is using the override config.
8057         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8058         assert_eq!(res.channel_flags, 0);
8059         assert_eq!(res.to_self_delay, 200);
8060 }
8061
8062 #[test]
8063 fn test_override_0msat_htlc_minimum() {
8064         let mut zero_config = UserConfig::default();
8065         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8066         let chanmon_cfgs = create_chanmon_cfgs(2);
8067         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8068         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8069         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8070
8071         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8072         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8073         assert_eq!(res.htlc_minimum_msat, 1);
8074
8075         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8076         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8077         assert_eq!(res.htlc_minimum_msat, 1);
8078 }
8079
8080 #[test]
8081 fn test_simple_mpp() {
8082         // Simple test of sending a multi-path payment.
8083         let chanmon_cfgs = create_chanmon_cfgs(4);
8084         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8085         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8086         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8087
8088         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8089         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8090         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8091         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8092
8093         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8094         let path = route.paths[0].clone();
8095         route.paths.push(path);
8096         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8097         route.paths[0][0].short_channel_id = chan_1_id;
8098         route.paths[0][1].short_channel_id = chan_3_id;
8099         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8100         route.paths[1][0].short_channel_id = chan_2_id;
8101         route.paths[1][1].short_channel_id = chan_4_id;
8102         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8103         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8104 }
8105
8106 #[test]
8107 fn test_preimage_storage() {
8108         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8109         let chanmon_cfgs = create_chanmon_cfgs(2);
8110         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8111         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8112         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8113
8114         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8115
8116         {
8117                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, 42);
8118                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8119                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8120                 check_added_monitors!(nodes[0], 1);
8121                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8122                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8123                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8124                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8125         }
8126         // Note that after leaving the above scope we have no knowledge of any arguments or return
8127         // values from previous calls.
8128         expect_pending_htlcs_forwardable!(nodes[1]);
8129         let events = nodes[1].node.get_and_clear_pending_events();
8130         assert_eq!(events.len(), 1);
8131         match events[0] {
8132                 Event::PaymentReceived { ref purpose, .. } => {
8133                         match &purpose {
8134                                 PaymentPurpose::InvoicePayment { payment_preimage, user_payment_id, .. } => {
8135                                         assert_eq!(*user_payment_id, 42);
8136                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8137                                 },
8138                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8139                         }
8140                 },
8141                 _ => panic!("Unexpected event"),
8142         }
8143 }
8144
8145 #[test]
8146 fn test_secret_timeout() {
8147         // Simple test of payment secret storage time outs
8148         let chanmon_cfgs = create_chanmon_cfgs(2);
8149         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8150         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8151         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8152
8153         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8154
8155         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8156
8157         // We should fail to register the same payment hash twice, at least until we've connected a
8158         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8159         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8160                 assert_eq!(err, "Duplicate payment hash");
8161         } else { panic!(); }
8162         let mut block = {
8163                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8164                 Block {
8165                         header: BlockHeader {
8166                                 version: 0x2000000,
8167                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8168                                 merkle_root: Default::default(),
8169                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8170                         txdata: vec![],
8171                 }
8172         };
8173         connect_block(&nodes[1], &block);
8174         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8175                 assert_eq!(err, "Duplicate payment hash");
8176         } else { panic!(); }
8177
8178         // If we then connect the second block, we should be able to register the same payment hash
8179         // again with a different user_payment_id (this time getting a new payment secret).
8180         block.header.prev_blockhash = block.header.block_hash();
8181         block.header.time += 1;
8182         connect_block(&nodes[1], &block);
8183         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 42).unwrap();
8184         assert_ne!(payment_secret_1, our_payment_secret);
8185
8186         {
8187                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8188                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8189                 check_added_monitors!(nodes[0], 1);
8190                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8191                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8192                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8193                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8194         }
8195         // Note that after leaving the above scope we have no knowledge of any arguments or return
8196         // values from previous calls.
8197         expect_pending_htlcs_forwardable!(nodes[1]);
8198         let events = nodes[1].node.get_and_clear_pending_events();
8199         assert_eq!(events.len(), 1);
8200         match events[0] {
8201                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, user_payment_id }, .. } => {
8202                         assert!(payment_preimage.is_none());
8203                         assert_eq!(user_payment_id, 42);
8204                         assert_eq!(payment_secret, our_payment_secret);
8205                         // We don't actually have the payment preimage with which to claim this payment!
8206                 },
8207                 _ => panic!("Unexpected event"),
8208         }
8209 }
8210
8211 #[test]
8212 fn test_bad_secret_hash() {
8213         // Simple test of unregistered payment hash/invalid payment secret handling
8214         let chanmon_cfgs = create_chanmon_cfgs(2);
8215         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8216         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8217         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8218
8219         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8220
8221         let random_payment_hash = PaymentHash([42; 32]);
8222         let random_payment_secret = PaymentSecret([43; 32]);
8223         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8224         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8225
8226         // All the below cases should end up being handled exactly identically, so we macro the
8227         // resulting events.
8228         macro_rules! handle_unknown_invalid_payment_data {
8229                 () => {
8230                         check_added_monitors!(nodes[0], 1);
8231                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8232                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8233                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8234                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8235
8236                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8237                         // again to process the pending backwards-failure of the HTLC
8238                         expect_pending_htlcs_forwardable!(nodes[1]);
8239                         expect_pending_htlcs_forwardable!(nodes[1]);
8240                         check_added_monitors!(nodes[1], 1);
8241
8242                         // We should fail the payment back
8243                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8244                         match events.pop().unwrap() {
8245                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8246                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8247                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8248                                 },
8249                                 _ => panic!("Unexpected event"),
8250                         }
8251                 }
8252         }
8253
8254         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8255         // Error data is the HTLC value (100,000) and current block height
8256         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8257
8258         // Send a payment with the right payment hash but the wrong payment secret
8259         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8260         handle_unknown_invalid_payment_data!();
8261         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8262
8263         // Send a payment with a random payment hash, but the right payment secret
8264         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8265         handle_unknown_invalid_payment_data!();
8266         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8267
8268         // Send a payment with a random payment hash and random payment secret
8269         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8270         handle_unknown_invalid_payment_data!();
8271         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8272 }
8273
8274 #[test]
8275 fn test_update_err_monitor_lockdown() {
8276         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8277         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8278         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8279         //
8280         // This scenario may happen in a watchtower setup, where watchtower process a block height
8281         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8282         // commitment at same time.
8283
8284         let chanmon_cfgs = create_chanmon_cfgs(2);
8285         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8286         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8287         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8288
8289         // Create some initial channel
8290         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8291         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8292
8293         // Rebalance the network to generate htlc in the two directions
8294         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8295
8296         // Route a HTLC from node 0 to node 1 (but don't settle)
8297         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8298
8299         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8300         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8301         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8302         let persister = test_utils::TestPersister::new();
8303         let watchtower = {
8304                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8305                 let mut w = test_utils::TestVecWriter(Vec::new());
8306                 monitor.write(&mut w).unwrap();
8307                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8308                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8309                 assert!(new_monitor == *monitor);
8310                 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);
8311                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8312                 watchtower
8313         };
8314         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8315         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8316         // transaction lock time requirements here.
8317         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8318         watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8319
8320         // Try to update ChannelMonitor
8321         assert!(nodes[1].node.claim_funds(preimage));
8322         check_added_monitors!(nodes[1], 1);
8323         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8324         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8325         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8326         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8327                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8328                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8329                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8330                 } else { assert!(false); }
8331         } else { assert!(false); };
8332         // Our local monitor is in-sync and hasn't processed yet timeout
8333         check_added_monitors!(nodes[0], 1);
8334         let events = nodes[0].node.get_and_clear_pending_events();
8335         assert_eq!(events.len(), 1);
8336 }
8337
8338 #[test]
8339 fn test_concurrent_monitor_claim() {
8340         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8341         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8342         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8343         // state N+1 confirms. Alice claims output from state N+1.
8344
8345         let chanmon_cfgs = create_chanmon_cfgs(2);
8346         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8347         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8348         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8349
8350         // Create some initial channel
8351         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8352         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8353
8354         // Rebalance the network to generate htlc in the two directions
8355         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8356
8357         // Route a HTLC from node 0 to node 1 (but don't settle)
8358         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8359
8360         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8361         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8362         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8363         let persister = test_utils::TestPersister::new();
8364         let watchtower_alice = {
8365                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8366                 let mut w = test_utils::TestVecWriter(Vec::new());
8367                 monitor.write(&mut w).unwrap();
8368                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8369                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8370                 assert!(new_monitor == *monitor);
8371                 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);
8372                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8373                 watchtower
8374         };
8375         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8376         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8377         // transaction lock time requirements here.
8378         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8379         watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8380
8381         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8382         {
8383                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8384                 assert_eq!(txn.len(), 2);
8385                 txn.clear();
8386         }
8387
8388         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8389         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8390         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8391         let persister = test_utils::TestPersister::new();
8392         let watchtower_bob = {
8393                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8394                 let mut w = test_utils::TestVecWriter(Vec::new());
8395                 monitor.write(&mut w).unwrap();
8396                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8397                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8398                 assert!(new_monitor == *monitor);
8399                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8400                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8401                 watchtower
8402         };
8403         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8404         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8405
8406         // Route another payment to generate another update with still previous HTLC pending
8407         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8408         {
8409                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8410         }
8411         check_added_monitors!(nodes[1], 1);
8412
8413         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8414         assert_eq!(updates.update_add_htlcs.len(), 1);
8415         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8416         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8417                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8418                         // Watchtower Alice should already have seen the block and reject the update
8419                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8420                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8421                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8422                 } else { assert!(false); }
8423         } else { assert!(false); };
8424         // Our local monitor is in-sync and hasn't processed yet timeout
8425         check_added_monitors!(nodes[0], 1);
8426
8427         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8428         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8429         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8430
8431         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8432         let bob_state_y;
8433         {
8434                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8435                 assert_eq!(txn.len(), 2);
8436                 bob_state_y = txn[0].clone();
8437                 txn.clear();
8438         };
8439
8440         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8441         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8442         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);
8443         {
8444                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8445                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8446                 // the onchain detection of the HTLC output
8447                 assert_eq!(htlc_txn.len(), 2);
8448                 check_spends!(htlc_txn[0], bob_state_y);
8449                 check_spends!(htlc_txn[1], bob_state_y);
8450         }
8451 }
8452
8453 #[test]
8454 fn test_pre_lockin_no_chan_closed_update() {
8455         // Test that if a peer closes a channel in response to a funding_created message we don't
8456         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8457         // message).
8458         //
8459         // Doing so would imply a channel monitor update before the initial channel monitor
8460         // registration, violating our API guarantees.
8461         //
8462         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8463         // then opening a second channel with the same funding output as the first (which is not
8464         // rejected because the first channel does not exist in the ChannelManager) and closing it
8465         // before receiving funding_signed.
8466         let chanmon_cfgs = create_chanmon_cfgs(2);
8467         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8468         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8469         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8470
8471         // Create an initial channel
8472         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8473         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8474         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8475         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8476         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8477
8478         // Move the first channel through the funding flow...
8479         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8480
8481         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8482         check_added_monitors!(nodes[0], 0);
8483
8484         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8485         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8486         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8487         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8488         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8489 }
8490
8491 #[test]
8492 fn test_htlc_no_detection() {
8493         // This test is a mutation to underscore the detection logic bug we had
8494         // before #653. HTLC value routed is above the remaining balance, thus
8495         // inverting HTLC and `to_remote` output. HTLC will come second and
8496         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8497         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8498         // outputs order detection for correct spending children filtring.
8499
8500         let chanmon_cfgs = create_chanmon_cfgs(2);
8501         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8502         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8503         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8504
8505         // Create some initial channels
8506         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8507
8508         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8509         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8510         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8511         assert_eq!(local_txn[0].input.len(), 1);
8512         assert_eq!(local_txn[0].output.len(), 3);
8513         check_spends!(local_txn[0], chan_1.3);
8514
8515         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8516         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8517         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8518         // We deliberately connect the local tx twice as this should provoke a failure calling
8519         // this test before #653 fix.
8520         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);
8521         check_closed_broadcast!(nodes[0], true);
8522         check_added_monitors!(nodes[0], 1);
8523         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8524         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8525
8526         let htlc_timeout = {
8527                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8528                 assert_eq!(node_txn[1].input.len(), 1);
8529                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8530                 check_spends!(node_txn[1], local_txn[0]);
8531                 node_txn[1].clone()
8532         };
8533
8534         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8535         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8536         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8537         expect_payment_failed!(nodes[0], our_payment_hash, true);
8538 }
8539
8540 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8541         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8542         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8543         // Carol, Alice would be the upstream node, and Carol the downstream.)
8544         //
8545         // Steps of the test:
8546         // 1) Alice sends a HTLC to Carol through Bob.
8547         // 2) Carol doesn't settle the HTLC.
8548         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8549         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8550         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8551         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8552         // 5) Carol release the preimage to Bob off-chain.
8553         // 6) Bob claims the offered output on the broadcasted commitment.
8554         let chanmon_cfgs = create_chanmon_cfgs(3);
8555         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8556         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8557         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8558
8559         // Create some initial channels
8560         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8561         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8562
8563         // Steps (1) and (2):
8564         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8565         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8566
8567         // Check that Alice's commitment transaction now contains an output for this HTLC.
8568         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8569         check_spends!(alice_txn[0], chan_ab.3);
8570         assert_eq!(alice_txn[0].output.len(), 2);
8571         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8572         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8573         assert_eq!(alice_txn.len(), 2);
8574
8575         // Steps (3) and (4):
8576         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8577         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8578         let mut force_closing_node = 0; // Alice force-closes
8579         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8580         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8581         check_closed_broadcast!(nodes[force_closing_node], true);
8582         check_added_monitors!(nodes[force_closing_node], 1);
8583         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8584         if go_onchain_before_fulfill {
8585                 let txn_to_broadcast = match broadcast_alice {
8586                         true => alice_txn.clone(),
8587                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8588                 };
8589                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8590                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8591                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8592                 if broadcast_alice {
8593                         check_closed_broadcast!(nodes[1], true);
8594                         check_added_monitors!(nodes[1], 1);
8595                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8596                 }
8597                 assert_eq!(bob_txn.len(), 1);
8598                 check_spends!(bob_txn[0], chan_ab.3);
8599         }
8600
8601         // Step (5):
8602         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8603         // process of removing the HTLC from their commitment transactions.
8604         assert!(nodes[2].node.claim_funds(payment_preimage));
8605         check_added_monitors!(nodes[2], 1);
8606         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8607         assert!(carol_updates.update_add_htlcs.is_empty());
8608         assert!(carol_updates.update_fail_htlcs.is_empty());
8609         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8610         assert!(carol_updates.update_fee.is_none());
8611         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8612
8613         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8614         expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8615         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8616         if !go_onchain_before_fulfill && broadcast_alice {
8617                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8618                 assert_eq!(events.len(), 1);
8619                 match events[0] {
8620                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8621                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8622                         },
8623                         _ => panic!("Unexpected event"),
8624                 };
8625         }
8626         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8627         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8628         // Carol<->Bob's updated commitment transaction info.
8629         check_added_monitors!(nodes[1], 2);
8630
8631         let events = nodes[1].node.get_and_clear_pending_msg_events();
8632         assert_eq!(events.len(), 2);
8633         let bob_revocation = match events[0] {
8634                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8635                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8636                         (*msg).clone()
8637                 },
8638                 _ => panic!("Unexpected event"),
8639         };
8640         let bob_updates = match events[1] {
8641                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8642                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8643                         (*updates).clone()
8644                 },
8645                 _ => panic!("Unexpected event"),
8646         };
8647
8648         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8649         check_added_monitors!(nodes[2], 1);
8650         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8651         check_added_monitors!(nodes[2], 1);
8652
8653         let events = nodes[2].node.get_and_clear_pending_msg_events();
8654         assert_eq!(events.len(), 1);
8655         let carol_revocation = match events[0] {
8656                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8657                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8658                         (*msg).clone()
8659                 },
8660                 _ => panic!("Unexpected event"),
8661         };
8662         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8663         check_added_monitors!(nodes[1], 1);
8664
8665         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8666         // here's where we put said channel's commitment tx on-chain.
8667         let mut txn_to_broadcast = alice_txn.clone();
8668         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8669         if !go_onchain_before_fulfill {
8670                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8671                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8672                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8673                 if broadcast_alice {
8674                         check_closed_broadcast!(nodes[1], true);
8675                         check_added_monitors!(nodes[1], 1);
8676                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8677                 }
8678                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8679                 if broadcast_alice {
8680                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8681                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8682                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8683                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8684                         // broadcasted.
8685                         assert_eq!(bob_txn.len(), 3);
8686                         check_spends!(bob_txn[1], chan_ab.3);
8687                 } else {
8688                         assert_eq!(bob_txn.len(), 2);
8689                         check_spends!(bob_txn[0], chan_ab.3);
8690                 }
8691         }
8692
8693         // Step (6):
8694         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8695         // broadcasted commitment transaction.
8696         {
8697                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8698                 if go_onchain_before_fulfill {
8699                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8700                         assert_eq!(bob_txn.len(), 2);
8701                 }
8702                 let script_weight = match broadcast_alice {
8703                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8704                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8705                 };
8706                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8707                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8708                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8709                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8710                 if broadcast_alice && !go_onchain_before_fulfill {
8711                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8712                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8713                 } else {
8714                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8715                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8716                 }
8717         }
8718 }
8719
8720 #[test]
8721 fn test_onchain_htlc_settlement_after_close() {
8722         do_test_onchain_htlc_settlement_after_close(true, true);
8723         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8724         do_test_onchain_htlc_settlement_after_close(true, false);
8725         do_test_onchain_htlc_settlement_after_close(false, false);
8726 }
8727
8728 #[test]
8729 fn test_duplicate_chan_id() {
8730         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8731         // already open we reject it and keep the old channel.
8732         //
8733         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8734         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8735         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8736         // updating logic for the existing channel.
8737         let chanmon_cfgs = create_chanmon_cfgs(2);
8738         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8739         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8740         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8741
8742         // Create an initial channel
8743         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8744         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8745         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8746         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()));
8747
8748         // Try to create a second channel with the same temporary_channel_id as the first and check
8749         // that it is rejected.
8750         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8751         {
8752                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8753                 assert_eq!(events.len(), 1);
8754                 match events[0] {
8755                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8756                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8757                                 // first (valid) and second (invalid) channels are closed, given they both have
8758                                 // the same non-temporary channel_id. However, currently we do not, so we just
8759                                 // move forward with it.
8760                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8761                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8762                         },
8763                         _ => panic!("Unexpected event"),
8764                 }
8765         }
8766
8767         // Move the first channel through the funding flow...
8768         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8769
8770         nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8771         check_added_monitors!(nodes[0], 0);
8772
8773         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8774         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8775         {
8776                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8777                 assert_eq!(added_monitors.len(), 1);
8778                 assert_eq!(added_monitors[0].0, funding_output);
8779                 added_monitors.clear();
8780         }
8781         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8782
8783         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8784         let channel_id = funding_outpoint.to_channel_id();
8785
8786         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8787         // temporary one).
8788
8789         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8790         // Technically this is allowed by the spec, but we don't support it and there's little reason
8791         // to. Still, it shouldn't cause any other issues.
8792         open_chan_msg.temporary_channel_id = channel_id;
8793         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8794         {
8795                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8796                 assert_eq!(events.len(), 1);
8797                 match events[0] {
8798                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8799                                 // Technically, at this point, nodes[1] would be justified in thinking both
8800                                 // channels are closed, but currently we do not, so we just move forward with it.
8801                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8802                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8803                         },
8804                         _ => panic!("Unexpected event"),
8805                 }
8806         }
8807
8808         // Now try to create a second channel which has a duplicate funding output.
8809         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8810         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8811         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8812         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()));
8813         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8814
8815         let funding_created = {
8816                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8817                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8818                 let logger = test_utils::TestLogger::new();
8819                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8820         };
8821         check_added_monitors!(nodes[0], 0);
8822         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8823         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8824         // still needs to be cleared here.
8825         check_added_monitors!(nodes[1], 1);
8826
8827         // ...still, nodes[1] will reject the duplicate channel.
8828         {
8829                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8830                 assert_eq!(events.len(), 1);
8831                 match events[0] {
8832                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8833                                 // Technically, at this point, nodes[1] would be justified in thinking both
8834                                 // channels are closed, but currently we do not, so we just move forward with it.
8835                                 assert_eq!(msg.channel_id, channel_id);
8836                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8837                         },
8838                         _ => panic!("Unexpected event"),
8839                 }
8840         }
8841
8842         // finally, finish creating the original channel and send a payment over it to make sure
8843         // everything is functional.
8844         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8845         {
8846                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8847                 assert_eq!(added_monitors.len(), 1);
8848                 assert_eq!(added_monitors[0].0, funding_output);
8849                 added_monitors.clear();
8850         }
8851
8852         let events_4 = nodes[0].node.get_and_clear_pending_events();
8853         assert_eq!(events_4.len(), 0);
8854         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8855         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
8856
8857         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8858         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8859         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8860         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8861 }
8862
8863 #[test]
8864 fn test_error_chans_closed() {
8865         // Test that we properly handle error messages, closing appropriate channels.
8866         //
8867         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8868         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8869         // we can test various edge cases around it to ensure we don't regress.
8870         let chanmon_cfgs = create_chanmon_cfgs(3);
8871         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8872         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8873         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8874
8875         // Create some initial channels
8876         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8877         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8878         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8879
8880         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8881         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8882         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8883
8884         // Closing a channel from a different peer has no effect
8885         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8886         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8887
8888         // Closing one channel doesn't impact others
8889         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8890         check_added_monitors!(nodes[0], 1);
8891         check_closed_broadcast!(nodes[0], false);
8892         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8893         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8894         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8895         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);
8896         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);
8897
8898         // A null channel ID should close all channels
8899         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8900         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8901         check_added_monitors!(nodes[0], 2);
8902         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8903         let events = nodes[0].node.get_and_clear_pending_msg_events();
8904         assert_eq!(events.len(), 2);
8905         match events[0] {
8906                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8907                         assert_eq!(msg.contents.flags & 2, 2);
8908                 },
8909                 _ => panic!("Unexpected event"),
8910         }
8911         match events[1] {
8912                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8913                         assert_eq!(msg.contents.flags & 2, 2);
8914                 },
8915                 _ => panic!("Unexpected event"),
8916         }
8917         // Note that at this point users of a standard PeerHandler will end up calling
8918         // peer_disconnected with no_connection_possible set to false, duplicating the
8919         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8920         // users with their own peer handling logic. We duplicate the call here, however.
8921         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8922         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8923
8924         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8925         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8926         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8927 }
8928
8929 #[test]
8930 fn test_invalid_funding_tx() {
8931         // Test that we properly handle invalid funding transactions sent to us from a peer.
8932         //
8933         // Previously, all other major lightning implementations had failed to properly sanitize
8934         // funding transactions from their counterparties, leading to a multi-implementation critical
8935         // security vulnerability (though we always sanitized properly, we've previously had
8936         // un-released crashes in the sanitization process).
8937         let chanmon_cfgs = create_chanmon_cfgs(2);
8938         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8939         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8940         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8941
8942         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8943         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()));
8944         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()));
8945
8946         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
8947         for output in tx.output.iter_mut() {
8948                 // Make the confirmed funding transaction have a bogus script_pubkey
8949                 output.script_pubkey = bitcoin::Script::new();
8950         }
8951
8952         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
8953         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()));
8954         check_added_monitors!(nodes[1], 1);
8955
8956         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()));
8957         check_added_monitors!(nodes[0], 1);
8958
8959         let events_1 = nodes[0].node.get_and_clear_pending_events();
8960         assert_eq!(events_1.len(), 0);
8961
8962         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8963         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8964         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8965
8966         confirm_transaction_at(&nodes[1], &tx, 1);
8967         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8968         check_added_monitors!(nodes[1], 1);
8969         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8970         assert_eq!(events_2.len(), 1);
8971         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
8972                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8973                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
8974                         assert_eq!(msg.data, "funding tx had wrong script/value or output index");
8975                 } else { panic!(); }
8976         } else { panic!(); }
8977         assert_eq!(nodes[1].node.list_channels().len(), 0);
8978 }
8979
8980 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
8981         // In the first version of the chain::Confirm interface, after a refactor was made to not
8982         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
8983         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
8984         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
8985         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
8986         // spending transaction until height N+1 (or greater). This was due to the way
8987         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
8988         // spending transaction at the height the input transaction was confirmed at, not whether we
8989         // should broadcast a spending transaction at the current height.
8990         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
8991         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
8992         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
8993         // until we learned about an additional block.
8994         //
8995         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
8996         // aren't broadcasting transactions too early (ie not broadcasting them at all).
8997         let chanmon_cfgs = create_chanmon_cfgs(3);
8998         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8999         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9000         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9001         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9002
9003         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9004         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9005         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9006         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9007         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9008
9009         nodes[1].node.force_close_channel(&channel_id).unwrap();
9010         check_closed_broadcast!(nodes[1], true);
9011         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9012         check_added_monitors!(nodes[1], 1);
9013         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9014         assert_eq!(node_txn.len(), 1);
9015
9016         let conf_height = nodes[1].best_block_info().1;
9017         if !test_height_before_timelock {
9018                 connect_blocks(&nodes[1], 24 * 6);
9019         }
9020         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9021                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9022         if test_height_before_timelock {
9023                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9024                 // generate any events or broadcast any transactions
9025                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9026                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9027         } else {
9028                 // We should broadcast an HTLC transaction spending our funding transaction first
9029                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9030                 assert_eq!(spending_txn.len(), 2);
9031                 assert_eq!(spending_txn[0], node_txn[0]);
9032                 check_spends!(spending_txn[1], node_txn[0]);
9033                 // We should also generate a SpendableOutputs event with the to_self output (as its
9034                 // timelock is up).
9035                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9036                 assert_eq!(descriptor_spend_txn.len(), 1);
9037
9038                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9039                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9040                 // additional block built on top of the current chain.
9041                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9042                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9043                 expect_pending_htlcs_forwardable!(nodes[1]);
9044                 check_added_monitors!(nodes[1], 1);
9045
9046                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9047                 assert!(updates.update_add_htlcs.is_empty());
9048                 assert!(updates.update_fulfill_htlcs.is_empty());
9049                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9050                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9051                 assert!(updates.update_fee.is_none());
9052                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9053                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9054                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9055         }
9056 }
9057
9058 #[test]
9059 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9060         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9061         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9062 }
9063
9064 #[test]
9065 fn test_forwardable_regen() {
9066         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9067         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9068         // HTLCs.
9069         // We test it for both payment receipt and payment forwarding.
9070
9071         let chanmon_cfgs = create_chanmon_cfgs(3);
9072         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9073         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9074         let persister: test_utils::TestPersister;
9075         let new_chain_monitor: test_utils::TestChainMonitor;
9076         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9077         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9078         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9079         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9080
9081         // First send a payment to nodes[1]
9082         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9083         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9084         check_added_monitors!(nodes[0], 1);
9085
9086         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9087         assert_eq!(events.len(), 1);
9088         let payment_event = SendEvent::from_event(events.pop().unwrap());
9089         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9090         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9091
9092         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9093
9094         // Next send a payment which is forwarded by nodes[1]
9095         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9096         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9097         check_added_monitors!(nodes[0], 1);
9098
9099         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9100         assert_eq!(events.len(), 1);
9101         let payment_event = SendEvent::from_event(events.pop().unwrap());
9102         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9103         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9104
9105         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9106         // generated
9107         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9108
9109         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9110         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9111         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9112
9113         let nodes_1_serialized = nodes[1].node.encode();
9114         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9115         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9116         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9117         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9118
9119         persister = test_utils::TestPersister::new();
9120         let keys_manager = &chanmon_cfgs[1].keys_manager;
9121         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);
9122         nodes[1].chain_monitor = &new_chain_monitor;
9123
9124         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9125         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9126                 &mut chan_0_monitor_read, keys_manager).unwrap();
9127         assert!(chan_0_monitor_read.is_empty());
9128         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9129         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9130                 &mut chan_1_monitor_read, keys_manager).unwrap();
9131         assert!(chan_1_monitor_read.is_empty());
9132
9133         let mut nodes_1_read = &nodes_1_serialized[..];
9134         let (_, nodes_1_deserialized_tmp) = {
9135                 let mut channel_monitors = HashMap::new();
9136                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9137                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9138                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9139                         default_config: UserConfig::default(),
9140                         keys_manager,
9141                         fee_estimator: node_cfgs[1].fee_estimator,
9142                         chain_monitor: nodes[1].chain_monitor,
9143                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9144                         logger: nodes[1].logger,
9145                         channel_monitors,
9146                 }).unwrap()
9147         };
9148         nodes_1_deserialized = nodes_1_deserialized_tmp;
9149         assert!(nodes_1_read.is_empty());
9150
9151         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9152         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9153         nodes[1].node = &nodes_1_deserialized;
9154         check_added_monitors!(nodes[1], 2);
9155
9156         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9157         // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9158         // the commitment state.
9159         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9160
9161         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9162
9163         expect_pending_htlcs_forwardable!(nodes[1]);
9164         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9165         check_added_monitors!(nodes[1], 1);
9166
9167         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9168         assert_eq!(events.len(), 1);
9169         let payment_event = SendEvent::from_event(events.pop().unwrap());
9170         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9171         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9172         expect_pending_htlcs_forwardable!(nodes[2]);
9173         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9174
9175         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9176         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9177 }
9178
9179 #[test]
9180 fn test_keysend_payments_to_public_node() {
9181         let chanmon_cfgs = create_chanmon_cfgs(2);
9182         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9183         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9184         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9185
9186         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9187         let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
9188         let payer_pubkey = nodes[0].node.get_our_node_id();
9189         let payee_pubkey = nodes[1].node.get_our_node_id();
9190         let route = get_keysend_route(
9191                 &payer_pubkey, &network_graph, &payee_pubkey, None, &vec![], 10000, 40, nodes[0].logger
9192         ).unwrap();
9193
9194         let test_preimage = PaymentPreimage([42; 32]);
9195         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9196         check_added_monitors!(nodes[0], 1);
9197         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9198         assert_eq!(events.len(), 1);
9199         let event = events.pop().unwrap();
9200         let path = vec![&nodes[1]];
9201         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9202         claim_payment(&nodes[0], &path, test_preimage);
9203 }
9204
9205 #[test]
9206 fn test_keysend_payments_to_private_node() {
9207         let chanmon_cfgs = create_chanmon_cfgs(2);
9208         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9209         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9210         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9211
9212         let payer_pubkey = nodes[0].node.get_our_node_id();
9213         let payee_pubkey = nodes[1].node.get_our_node_id();
9214         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known() });
9215         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known() });
9216
9217         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9218         let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
9219         let first_hops = nodes[0].node.list_usable_channels();
9220         let route = get_keysend_route(
9221                 &payer_pubkey, &network_graph, &payee_pubkey, Some(&first_hops.iter().collect::<Vec<_>>()),
9222                 &vec![], 10000, 40, nodes[0].logger
9223         ).unwrap();
9224
9225         let test_preimage = PaymentPreimage([42; 32]);
9226         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9227         check_added_monitors!(nodes[0], 1);
9228         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9229         assert_eq!(events.len(), 1);
9230         let event = events.pop().unwrap();
9231         let path = vec![&nodes[1]];
9232         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9233         claim_payment(&nodes[0], &path, test_preimage);
9234 }